import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';

import { index as enrollmentRequestsIndex } from '@/actions/App/Http/Controllers/Admin/EnrollmentRequestController';
import {
    index,
    index as webFormSessionsIndex,
    show as webFormSessionsShow,
} from '@/actions/App/Http/Controllers/Admin/WebFormSessionController';
import HeadingSmall from '@/components/heading-small';
import { SortableHeader } from '@/components/sortable-header';
import { useUserTimezone } from '@/hooks/use-user-timezone';
import AppLayout from '@/layouts/app-layout';
import { formatDateTime } from '@/lib/format-date';

type WebFormSession = {
    id: number;
    session_id: string;
    web_form_identifier: string | null;
    web_form_type: string | null;
    product_id: number | null;
    ip_address: string | null;
    started_at: string | null;
    last_event_at: string | null;
    submitted_at: string | null;
    enrollment_request_id: number | null;
    events_count: number;
    created_at: string;
};

type PaginatedWebFormSessions = {
    data: WebFormSession[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    next_page_url: string | null;
    prev_page_url: string | null;
    links: { url: string | null; label: string; active: boolean }[];
};

type Filters = {
    search: string;
    web_form_type: string;
    product_id: string;
    state: string;
    sort_by: string;
    sort_direction: string;
};

type Props = {
    sessions: PaginatedWebFormSessions;
    filters: Filters;
};

function StateBadge({ submittedAt }: { submittedAt: string | null }) {
    return submittedAt ? (
        <span className="inline-block rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900 dark:text-green-300">
            Submitted
        </span>
    ) : (
        <span className="inline-block rounded-full bg-zinc-100 px-2 py-0.5 text-xs font-medium text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
            Abandoned
        </span>
    );
}

const breadcrumbs = [{ title: 'Web Form Sessions', href: index.url() }];

const selectClasses =
    'rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm shadow-sm dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100';

export default function WebFormSessions({ sessions, filters }: Props) {
    const timezone = useUserTimezone();
    const [search, setSearch] = useState(filters.search);

    const sortColumn = filters.sort_by || 'created_at';
    const sortDirection = (filters.sort_direction || 'desc') as 'asc' | 'desc';

    function toggleSort(column: string) {
        if (column === sortColumn) {
            applyFilters({
                sort_by: column,
                sort_direction: sortDirection === 'asc' ? 'desc' : 'asc',
            });
        } else {
            applyFilters({ sort_by: column, sort_direction: 'asc' });
        }
    }

    function applyFilters(overrides: Partial<Filters> = {}) {
        const merged = { ...filters, ...overrides };

        router.get(
            webFormSessionsIndex.url(),
            Object.fromEntries(
                Object.entries(merged).filter(([, v]) => v !== ''),
            ),
            { preserveState: true, replace: true },
        );
    }

    const hasActiveFilters =
        filters.search ||
        filters.web_form_type ||
        filters.product_id ||
        filters.state;

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Web Form Sessions" />

            <h1 className="sr-only">Web Form Sessions</h1>

            <div className="space-y-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Web Form Sessions"
                        description="Track customer progress through public web forms"
                    />

                    <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-end">
                        <div className="flex flex-col gap-1 sm:min-w-60">
                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                Search
                            </label>
                            <input
                                type="text"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        applyFilters({ search });
                                    }
                                }}
                                placeholder="Search session, IP, or form…"
                                className={selectClasses}
                            />
                        </div>

                        <div className="flex flex-col gap-1">
                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                Form Type
                            </label>
                            <select
                                value={filters.web_form_type}
                                onChange={(e) =>
                                    applyFilters({
                                        web_form_type: e.target.value,
                                    })
                                }
                                className={selectClasses}
                            >
                                <option value="">All</option>
                                <option value="enrollment">Enrollment</option>
                                <option value="credit_check">
                                    Credit Check
                                </option>
                            </select>
                        </div>

                        <div className="flex flex-col gap-1">
                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                State
                            </label>
                            <select
                                value={filters.state}
                                onChange={(e) =>
                                    applyFilters({ state: e.target.value })
                                }
                                className={selectClasses}
                            >
                                <option value="">All</option>
                                <option value="submitted">Submitted</option>
                                <option value="abandoned">Abandoned</option>
                            </select>
                        </div>

                        <button
                            type="button"
                            onClick={() => applyFilters({ search })}
                            className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
                        >
                            Search
                        </button>

                        {hasActiveFilters && (
                            <button
                                type="button"
                                onClick={() => {
                                    setSearch('');
                                    applyFilters({
                                        search: '',
                                        web_form_type: '',
                                        product_id: '',
                                        state: '',
                                    });
                                }}
                                className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                            >
                                Clear
                            </button>
                        )}
                    </div>
                </div>

                <div className="overflow-hidden rounded-md border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm">
                            <thead className="border-b border-zinc-200 text-xs text-zinc-600 uppercase dark:border-zinc-800 dark:text-zinc-400">
                                <tr>
                                    <th className="px-4 py-3">Session</th>
                                    <SortableHeader
                                        label="Form Type"
                                        column="web_form_type"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <th className="px-4 py-3">Product</th>
                                    <th className="px-4 py-3">IP Address</th>
                                    <th className="px-4 py-3">Events</th>
                                    <th className="px-4 py-3">State</th>
                                    <th className="px-4 py-3">Enrollment</th>
                                    <SortableHeader
                                        label="Started"
                                        column="started_at"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {sessions.data.map((session) => (
                                    <tr
                                        key={session.id}
                                        className="hover:bg-zinc-50 dark:hover:bg-zinc-900"
                                    >
                                        <td className="px-4 py-3">
                                            <Link
                                                href={webFormSessionsShow.url(
                                                    session.id,
                                                )}
                                                className="font-mono text-xs text-blue-600 hover:text-blue-800 hover:underline dark:text-blue-400 dark:hover:text-blue-300"
                                            >
                                                {session.session_id}
                                            </Link>
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {session.web_form_type ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {session.product_id ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {session.ip_address ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {session.events_count}
                                        </td>
                                        <td className="px-4 py-3">
                                            <StateBadge
                                                submittedAt={session.submitted_at}
                                            />
                                        </td>
                                        <td className="px-4 py-3">
                                            {session.enrollment_request_id ? (
                                                <Link
                                                    href={enrollmentRequestsIndex.url(
                                                        {
                                                            query: {
                                                                id: String(
                                                                    session.enrollment_request_id,
                                                                ),
                                                            },
                                                        },
                                                    )}
                                                    className="font-mono text-xs text-blue-600 hover:text-blue-800 hover:underline dark:text-blue-400 dark:hover:text-blue-300"
                                                >
                                                    #{session.enrollment_request_id}
                                                </Link>
                                            ) : (
                                                <span className="text-zinc-400">
                                                    —
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3">
                                            {formatDateTime(
                                                session.started_at ??
                                                    session.created_at,
                                                timezone,
                                                { includeSeconds: true },
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    {sessions.data.length === 0 && (
                        <div className="p-4 text-sm text-zinc-600 dark:text-zinc-400">
                            No web form sessions yet.
                        </div>
                    )}
                </div>

                {sessions.last_page > 1 && (
                    <div className="flex items-center justify-between text-sm">
                        <span className="text-zinc-500 dark:text-zinc-400">
                            Showing{' '}
                            {(sessions.current_page - 1) * sessions.per_page +
                                1}
                            –
                            {Math.min(
                                sessions.current_page * sessions.per_page,
                                sessions.total,
                            )}{' '}
                            of {sessions.total}
                        </span>
                        <div className="flex gap-1">
                            {sessions.links.map((link) => (
                                <Link
                                    key={link.label}
                                    href={link.url ?? '#'}
                                    preserveState
                                    className={`rounded-md px-3 py-1.5 text-xs ${
                                        link.active
                                            ? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
                                            : link.url
                                              ? 'text-zinc-700 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-800'
                                              : 'pointer-events-none text-zinc-300 dark:text-zinc-700'
                                    }`}
                                    dangerouslySetInnerHTML={{
                                        __html: link.label,
                                    }}
                                />
                            ))}
                        </div>
                    </div>
                )}
            </div>
        </AppLayout>
    );
}
