import 'mantine-datatable/styles.css';
import { DataTable } from '@/components/Shared/DataTable';

export interface JourneySessionRow {
    id: string;
    session_id: string;
    visitor_id: string;
    user_id?: string;
    user_name?: string;
    user?: {
        id: string;
        name: string;
        email?: string;
        phone?: string;
    } | null;
    entry_page: string;
    exit_page: string;
    entry_channel_group?: string;
    entry_utm_source?: string;
    entry_utm_medium?: string;
    entry_utm_campaign?: string;
    entry_utm_content?: string;
    entry_utm_term?: string;
    entry_city?: string;
    entry_region?: string;
    entry_country?: string;
    entry_geo_source?: string;
    started_at: string;
    last_seen_at?: string;
    ended_at?: string | null;
    end_reason?: string;
    event_count: number;
    page_views: number;
    duration_ms: number;
    reached_checkout: boolean;
    has_purchase: boolean;
    has_auth: boolean;
    exit_modal_shown: boolean;
    has_add_to_cart: boolean;
    has_wedding: boolean;
    event_types?: string[];
    session_count?: number;
    grouped?: boolean;
}

interface SessionListTableProps {
    records: JourneySessionRow[];
    page: number;
    pageSize: number;
    totalRecords: number;
    isLoading: boolean;
    onPageChange: (page: number) => void;
    onRowClick: (row: JourneySessionRow) => void;
}

const formatDuration = (ms: number) => {
    if (!ms || ms < 0) return '—';
    const minutes = Math.floor(ms / 60000);
    const seconds = Math.floor((ms % 60000) / 1000);
    if (minutes <= 0) return `${seconds}s`;
    return `${minutes}m ${seconds}s`;
};

const Badge = ({ show, label, color }: { show: boolean; label: string; color: string }) => {
    if (!show) return null;
    return (
        <span className={`badge my-0 px-1.5 py-0 text-[10px] font-medium ${color}`}>
            {label}
        </span>
    );
};

const SessionListTable = ({
    records,
    page,
    pageSize,
    totalRecords,
    isLoading,
    onPageChange,
    onRowClick,
}: SessionListTableProps) => {
    return (
        <div className="datatables">
            <DataTable
                className="whitespace-nowrap table-hover cursor-pointer"
                records={records}
                idAccessor="id"
                fetching={isLoading}
                columns={[
                    {
                        accessor: 'started_at',
                        title: 'Started',
                        render: ({ started_at, session_count }) => (
                            <div>
                                <div>
                                    {started_at ? new Date(started_at).toLocaleString('id-ID') : '—'}
                                </div>
                                {session_count && session_count > 1 ? (
                                    <div className="text-xs text-gray-500">{session_count} sessions</div>
                                ) : null}
                            </div>
                        ),
                    },
                    {
                        accessor: 'visitor_id',
                        title: 'Visitor / User',
                        render: ({ visitor_id, user_id, user_name, user }) => (
                            <div>
                                <div className="font-mono text-xs">{visitor_id}</div>
                                {user_id ? (
                                    <div className="text-xs text-gray-500">
                                        {user_name || user?.name ? (
                                            <span className="font-semibold text-black dark:text-white-light">
                                                {user_name || user?.name}
                                            </span>
                                        ) : (
                                            <span>user: {user_id}</span>
                                        )}
                                    </div>
                                ) : null}
                            </div>
                        ),
                    },
                    {
                        accessor: 'entry_page',
                        title: 'Entry → Exit',
                        render: ({ entry_page, exit_page }) => (
                            <div className="max-w-xs truncate text-xs">
                                <div>{entry_page || '/'}</div>
                                <div className="text-gray-500">→ {exit_page || '/'}</div>
                            </div>
                        ),
                    },
                    {
                        accessor: 'entry_channel_group',
                        title: 'Channel',
                        render: ({ entry_channel_group }) => (
                            <span className="text-xs">{entry_channel_group || '—'}</span>
                        ),
                    },
                    {
                        accessor: 'entry_city',
                        title: 'City',
                        render: ({ entry_city, entry_region, entry_country }) => {
                            if (!entry_city && !entry_country) {
                                return <span className="text-xs text-gray-400">—</span>;
                            }
                            return (
                                <div className="text-xs">
                                    <div>{entry_city || '—'}</div>
                                    {entry_region || entry_country ? (
                                        <div className="text-gray-500">
                                            {[entry_region, entry_country].filter(Boolean).join(', ')}
                                        </div>
                                    ) : null}
                                </div>
                            );
                        },
                    },
                    {
                        accessor: 'entry_utm_source',
                        title: 'Source',
                        render: ({ entry_utm_source }) => (
                            <span className="text-xs">{entry_utm_source || '—'}</span>
                        ),
                    },
                    {
                        accessor: 'entry_utm_medium',
                        title: 'Medium',
                        render: ({ entry_utm_medium }) => (
                            <span className="text-xs">{entry_utm_medium || '—'}</span>
                        ),
                    },
                    {
                        accessor: 'entry_utm_campaign',
                        title: 'Campaign',
                        render: ({ entry_utm_campaign }) => (
                            <span className="text-xs">{entry_utm_campaign || '—'}</span>
                        ),
                    },
                    {
                        accessor: 'flags',
                        title: 'Flags',
                        render: (row) => {
                            const hasAny =
                                row.has_add_to_cart ||
                                row.reached_checkout ||
                                row.has_purchase ||
                                row.has_auth ||
                                row.has_wedding ||
                                row.exit_modal_shown;
                            if (!hasAny) return <span className="text-xs text-gray-400">—</span>;
                            return (
                                <div className="flex flex-wrap gap-1">
                                    <Badge show={row.has_add_to_cart} label="ATC" color="badge-outline-primary" />
                                    <Badge show={row.reached_checkout} label="Checkout" color="badge-outline-warning" />
                                    <Badge show={row.has_purchase} label="Purchase" color="badge-outline-success" />
                                    <Badge show={row.has_auth} label="Auth" color="badge-outline-info" />
                                    <Badge show={row.has_wedding} label="Wedding" color="badge-outline-secondary" />
                                    <Badge show={row.exit_modal_shown} label="Exit modal" color="badge-outline-danger" />
                                </div>
                            );
                        },
                    },
                    {
                        accessor: 'page_views',
                        title: 'Pages',
                    },
                    {
                        accessor: 'duration_ms',
                        title: 'Duration',
                        render: ({ duration_ms }) => formatDuration(duration_ms),
                    },
                    {
                        accessor: 'event_count',
                        title: 'Events',
                    },
                ]}
                totalRecords={totalRecords}
                recordsPerPage={pageSize}
                page={page}
                onPageChange={onPageChange}
                onRowClick={({ record }) => {
                    if (record) onRowClick(record);
                }}
                minHeight={200}
                noRecordsText="No sessions found"
            />
        </div>
    );
};

export default SessionListTable;
