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

import HeadingSmall from '@/components/heading-small';
import { Checkbox } from '@/components/ui/checkbox';
import { useUserTimezone } from '@/hooks/use-user-timezone';
import AppLayout from '@/layouts/app-layout';
import { formatDateTime } from '@/lib/format-date';
import { index, show } from '@/routes/admin/supplier-product-imports';

type Supplier = {
    id: number;
    name: string;
    slug: string;
};

type Import = {
    id: number;
    source: string;
    raw_file_sha256: string | null;
    total_rows: number;
    created_count: number;
    updated_count: number;
    archived_count: number;
    skipped_count: number;
    started_at: string | null;
    finished_at: string | null;
    error_message: string | null;
    operations_count: number;
    created_operations_count: number;
    updated_operations_count: number;
    archived_operations_count: number;
    skipped_operations_count: number;
};

type PaginatedImports = {
    data: Import[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
};

type Props = {
    suppliers: Supplier[];
    activeSupplierId: number | null;
    imports: PaginatedImports | never[];
};


function duration(startedAt: string | null, finishedAt: string | null): string {
    if (!startedAt || !finishedAt) return '—';
    const ms = new Date(finishedAt).getTime() - new Date(startedAt).getTime();
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
}

export default function SupplierProductImports({
    suppliers,
    activeSupplierId,
    imports,
}: Props) {
    const timezone = useUserTimezone();
    const paginated = Array.isArray(imports) ? null : imports;
    const [force, setForce] = useState(false);

    const breadcrumbs = [
        {
            title: 'Supplier Product Imports',
            href: activeSupplierId === null
                ? index.url()
                : index.url({ query: { supplier_id: activeSupplierId } }),
        },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Supplier Product Imports" />

            <div className="space-y-6">
                <HeadingSmall
                    title="Supplier Product Imports"
                    description="View import history and drill into individual import operations."
                />

                <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
                    <div className="flex w-full flex-col gap-1 sm:w-auto sm:min-w-[240px]">
                        <label className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                            Supplier
                        </label>
                        <select
                            className="w-full rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 shadow-sm dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100"
                            value={activeSupplierId ?? ''}
                            onChange={(e) => {
                                const supplierId =
                                    e.target.value === '' ? undefined : Number(e.target.value);
                                window.location.href = index.url(supplierId ? { query: { supplier_id: supplierId } } : undefined);
                            }}
                        >
                            <option value="" disabled>
                                Select supplier
                            </option>
                            {suppliers.map((s) => (
                                <option key={s.id} value={s.id}>
                                    {s.name}
                                </option>
                            ))}
                        </select>
                    </div>

                    {activeSupplierId !== null && (
                        <Form
                            method="post"
                            action="/admin/supplier-product-imports/import"
                            transform={(data) => ({
                                ...data,
                                supplier_id: activeSupplierId,
                                force,
                            })}
                        >
                            {({ processing }) => (
                                <div className="flex items-center gap-3">
                                    <label className="flex items-center gap-2 text-sm text-zinc-700 dark:text-zinc-300">
                                        <Checkbox
                                            id="force-reimport"
                                            checked={force}
                                            onCheckedChange={(checked) => setForce(checked === true)}
                                            disabled={processing}
                                        />
                                        Force reimport
                                    </label>
                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                    >
                                        {processing ? 'Dispatching…' : 'Run Import'}
                                    </button>
                                </div>
                            )}
                        </Form>
                    )}
                </div>

                {activeSupplierId === null ? (
                    <div className="rounded-md border border-zinc-200 bg-white p-4 text-sm text-zinc-700 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-200">
                        Pick a supplier to view import history.
                    </div>
                ) : paginated === null || paginated.data.length === 0 ? (
                    <div className="rounded-md border border-zinc-200 bg-white p-4 text-sm text-zinc-600 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-400">
                        No imports found for this supplier.
                    </div>
                ) : (
                    <div className="space-y-4">
                        <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 uppercase text-zinc-600 dark:border-zinc-800 dark:text-zinc-400">
                                        <tr>
                                            <th className="px-4 py-3">ID</th>
                                            <th className="px-4 py-3">Source</th>
                                            <th className="px-4 py-3">SHA-256</th>
                                            <th className="px-4 py-3">Rows</th>
                                            <th className="px-4 py-3">Created</th>
                                            <th className="px-4 py-3">Updated</th>
                                            <th className="px-4 py-3">Archived</th>
                                            <th className="px-4 py-3">Skipped</th>
                                            <th className="px-4 py-3">Duration</th>
                                            <th className="px-4 py-3">Started</th>
                                            <th className="px-4 py-3">Error</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                        {paginated.data.map((imp) => (
                                            <tr
                                                key={imp.id}
                                                className="cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-900"
                                                onClick={() => {
                                                    window.location.href = show.url(imp.id);
                                                }}
                                            >
                                                <td className="px-4 py-3 font-mono text-xs">
                                                    <Link
                                                        href={show.url(imp.id)}
                                                        className="text-blue-600 hover:underline dark:text-blue-400"
                                                    >
                                                        #{imp.id}
                                                    </Link>
                                                </td>
                                                <td className="px-4 py-3 font-mono text-xs">
                                                    {imp.source}
                                                </td>
                                                <td className="px-4 py-3 font-mono text-xs text-zinc-500">
                                                    {imp.raw_file_sha256 ? (
                                                        <span title={imp.raw_file_sha256} className="cursor-help">
                                                            {imp.raw_file_sha256.slice(0, 8)}…
                                                        </span>
                                                    ) : '—'}
                                                </td>
                                                <td className="px-4 py-3 text-center">
                                                    {imp.total_rows}
                                                </td>
                                                <td className="px-4 py-3 text-center">
                                                    {imp.created_count}
                                                </td>
                                                <td className="px-4 py-3 text-center">
                                                    {imp.updated_count}
                                                </td>
                                                <td className="px-4 py-3 text-center">
                                                    {imp.archived_count}
                                                </td>
                                                <td className="px-4 py-3 text-center">
                                                    {imp.skipped_count}
                                                </td>
                                                <td className="px-4 py-3 text-center text-xs text-zinc-500">
                                                    {duration(imp.started_at, imp.finished_at)}
                                                </td>
                                                <td className="px-4 py-3 text-xs text-zinc-500">
                                                    {formatDateTime(imp.started_at, timezone)}
                                                </td>
                                                <td className="max-w-[200px] truncate px-4 py-3 text-xs text-red-600 dark:text-red-400">
                                                    {imp.error_message ?? '—'}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        {paginated.last_page > 1 && (
                            <div className="flex items-center justify-between text-sm">
                                <span className="text-zinc-500 dark:text-zinc-400">
                                    Showing {(paginated.current_page - 1) * paginated.per_page + 1}–
                                    {Math.min(paginated.current_page * paginated.per_page, paginated.total)} of{' '}
                                    {paginated.total}
                                </span>
                                <div className="flex gap-1">
                                    {paginated.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>
                )}
            </div>
        </AppLayout>
    );
}
