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

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

type Import = {
    id: number;
    supplier_id: number;
    source: string;
    raw_file_path: string | null;
    raw_file_sha256: string | null;
    raw_file_size_bytes: number | 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;
    meta: Record<string, unknown> | null;
    supplier: { id: number; name: string };
};

type Operation = {
    id: number;
    supplier_product_import_id: number;
    supplier_product_id: number | null;
    product_external_id: string;
    operation: string;
    skip_reason: string | null;
    attribute_changes: Record<string, unknown> | null;
    row_payload: Record<string, unknown> | null;
    supplier_product: { id: number; external_id: string } | null;
};

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

type Props = {
    import: Import;
    operations: PaginatedOperations;
};

function OperationBadge({ operation }: { operation: string }) {
    const colors: Record<string, string> = {
        created: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
        updated: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300',
        skipped: 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400',
        archived: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300',
    };

    return (
        <span
            className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium ${colors[operation] ?? 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400'}`}
        >
            {operation}
        </span>
    );
}

function formatBytes(bytes: number | null): string {
    if (bytes === null) return '—';
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

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`;
}

// Use a different name to avoid the reserved word conflict with Props
export default function SupplierProductImportShow({ import: imp, operations }: Props) {
    const timezone = useUserTimezone();
    const breadcrumbs = [
        {
            title: 'Supplier Product Imports',
            href: importsIndex.url({ query: { supplier_id: imp.supplier_id } }),
        },
        {
            title: `Import #${imp.id}`,
            href: importsShow.url(imp.id),
        },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Import #${imp.id}`} />

            <div className="space-y-6">
                <HeadingSmall
                    title={`Import #${imp.id}`}
                    description={`${imp.supplier.name} — ${imp.source} import`}
                />

                {/* Summary Cards */}
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-6">
                    <SummaryCard label="Total Rows" value={imp.total_rows} />
                    <SummaryCard label="Created" value={imp.created_count} className="text-green-600 dark:text-green-400" />
                    <SummaryCard label="Updated" value={imp.updated_count} className="text-yellow-600 dark:text-yellow-400" />
                    <SummaryCard label="Archived" value={imp.archived_count} className="text-red-600 dark:text-red-400" />
                    <SummaryCard label="Skipped" value={imp.skipped_count} />
                    <SummaryCard label="Duration" value={duration(imp.started_at, imp.finished_at)} />
                </div>

                {/* Details */}
                <div className="overflow-hidden rounded-md border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
                    <div className="grid grid-cols-1 gap-4 p-4 text-sm sm:grid-cols-2 lg:grid-cols-3">
                        <Detail label="Source" value={imp.source} />
                        <Detail label="Started" value={formatDateTime(imp.started_at, timezone)} />
                        <Detail label="Finished" value={formatDateTime(imp.finished_at, timezone)} />
                        <Detail label="File Path" value={imp.raw_file_path} />
                        <Detail label="File Size" value={formatBytes(imp.raw_file_size_bytes)} />
                        <Detail label="SHA-256" value={imp.raw_file_sha256} />
                    </div>

                    {imp.error_message && (
                        <div className="border-t border-zinc-200 p-4 dark:border-zinc-800">
                            <span className="text-xs font-medium text-red-600 dark:text-red-400">Error</span>
                            <p className="mt-1 text-sm text-red-700 dark:text-red-300">{imp.error_message}</p>
                        </div>
                    )}

                    {imp.meta && Object.keys(imp.meta).length > 0 && (
                        <div className="border-t border-zinc-200 p-4 dark:border-zinc-800">
                            <details>
                                <summary className="cursor-pointer text-xs font-medium text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300">
                                    Meta
                                </summary>
                                <pre className="mt-2 max-h-40 overflow-auto rounded bg-zinc-100 p-2 font-mono text-xs dark:bg-zinc-800">
                                    {JSON.stringify(imp.meta, null, 2)}
                                </pre>
                            </details>
                        </div>
                    )}
                </div>

                {/* Operations Table */}
                <div className="space-y-3">
                    <h2 className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                        Operations ({operations.total})
                    </h2>

                    <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">External ID</th>
                                        <th className="px-4 py-3">Operation</th>
                                        <th className="px-4 py-3">Changes</th>
                                        <th className="px-4 py-3">Payload</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                    {operations.data.map((op) => (
                                        <tr key={op.id}>
                                            <td className="px-4 py-3 font-mono text-xs">
                                                {op.product_external_id}
                                            </td>
                                            <td className="px-4 py-3">
                                                <OperationBadge operation={op.operation} />
                                                {op.skip_reason && (
                                                    <p className="mt-1 font-mono text-xs text-zinc-400 dark:text-zinc-500">
                                                        {op.skip_reason}
                                                    </p>
                                                )}
                                            </td>
                                            <td className="px-4 py-3">
                                                {op.attribute_changes && Object.keys(op.attribute_changes).length > 0 ? (
                                                    <details>
                                                        <summary className="cursor-pointer text-xs text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300">
                                                            {Object.keys(op.attribute_changes).length} field(s)
                                                        </summary>
                                                        <pre className="mt-1 max-h-96 w-[600px] max-w-full overflow-auto rounded bg-zinc-100 p-3 font-mono text-xs leading-relaxed dark:bg-zinc-800">
                                                            {JSON.stringify(op.attribute_changes, null, 2)}
                                                        </pre>
                                                    </details>
                                                ) : (
                                                    <span className="text-zinc-400">—</span>
                                                )}
                                            </td>
                                            <td className="px-4 py-3">
                                                {op.row_payload && Object.keys(op.row_payload).length > 0 ? (
                                                    <details>
                                                        <summary className="cursor-pointer text-xs text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300">
                                                            View payload
                                                        </summary>
                                                        <pre className="mt-1 max-h-96 w-[600px] max-w-full overflow-auto rounded bg-zinc-100 p-3 font-mono text-xs leading-relaxed dark:bg-zinc-800">
                                                            {JSON.stringify(op.row_payload, null, 2)}
                                                        </pre>
                                                    </details>
                                                ) : (
                                                    <span className="text-zinc-400">—</span>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {operations.data.length === 0 && (
                            <div className="p-4 text-sm text-zinc-600 dark:text-zinc-400">
                                No operations recorded for this import.
                            </div>
                        )}
                    </div>

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

function SummaryCard({ label, value, className }: { label: string; value: string | number; className?: string }) {
    return (
        <div className="rounded-md border border-zinc-200 bg-white p-3 dark:border-zinc-800 dark:bg-zinc-950">
            <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">{label}</span>
            <p className={`mt-1 text-lg font-semibold ${className ?? 'text-zinc-900 dark:text-zinc-100'}`}>
                {value}
            </p>
        </div>
    );
}

function Detail({ label, value }: { label: string; value: string | null }) {
    return (
        <div>
            <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">{label}</span>
            <p className="text-xs text-zinc-800 dark:text-zinc-200">{value ?? '—'}</p>
        </div>
    );
}
