import { Form, 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 { formatDate } from '@/lib/format-date';
import { productProperName } from '@/lib/utils';
import { index as productsIndex, refreshDocuments as refreshProductDocuments, show as productsShow } from '@/routes/admin/products';
import { show as supplierProductsShow } from '@/routes/admin/supplier-products';

type SupplierProduct = {
    id: number;
    external_id: string;
    supplier: { id: number; name: string; slug: string } | null;
};

type Product = {
    id: number;
    name: string;
    account_type: string | null;
    energy_type: string | null;
    rate: string | null;
    rate_type: string | null;
    base_rate: string | null;
    term_months: number | null;
    term_text: string | null;
    etf_amount: number | null;
    status: string | null;
    rate_caption: string | null;
    reward_type: string | null;
    reward_amount: string | null;
    renewal_text: string | null;
    notes: string | null;
    starts_at: string | null;
    ends_at: string | null;
    updated_at: string;
    utility: { id: number; name: string } | null;
    state: { id: number; code: string; name: string } | null;
    supplier_product: SupplierProduct | null;
};

type ProductDocument = {
    id: number;
    type: string | null;
    title: string | null;
    language: string;
    file_type: string | null;
    external_id: string | null;
    url: string | null;
    local_file_path: string | null;
    view_url: string | null;
};

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

type Props = {
    product: Product;
    documents: PaginatedDocuments;
};

function StatusBadge({ status }: { status: string | null }) {
    if (!status) return <span className="text-zinc-400">—</span>;

    const colors: Record<string, string> = {
        active: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
        inactive: '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[status.toLowerCase()] ?? 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400'}`}
        >
            {status}
        </span>
    );
}

function LanguageBadge({ language }: { language: string }) {
    return (
        <span className="inline-block rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900 dark:text-blue-300">
            {language}
        </span>
    );
}

function formatRate(rate: string | null): string {
    if (!rate) return '—';
    return parseFloat(rate).toFixed(4);
}

export default function ProductShow({ product, documents }: Props) {
    const timezone = useUserTimezone();
    const name = productProperName(product.name);

    const breadcrumbs = [
        { title: 'Products', href: productsIndex.url() },
        { title: name, href: productsShow.url(product.id) },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={name} />

            <div className="space-y-6">
                <div className="flex items-center gap-3">
                    <HeadingSmall
                        title={name}
                        description={`${product.utility?.name ?? '—'} · ${product.state?.code ?? '—'}`}
                    />
                    <StatusBadge status={product.status} />
                </div>

                {/* Product 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-2 gap-4 p-4 text-sm sm:grid-cols-3 lg:grid-cols-4">
                        <Detail label="Rate" value={product.rate ? `${formatRate(product.rate)} ¢/kWh` : null} />
                        <Detail label="Rate type" value={product.rate_type} />
                        <Detail label="Base rate" value={product.base_rate ? `$${product.base_rate}` : null} />
                        <Detail label="Term" value={product.term_months != null ? `${product.term_months} months` : null} />
                        <Detail label="Term text" value={product.term_text} />
                        <Detail label="Account type" value={product.account_type} />
                        <Detail label="Energy type" value={product.energy_type} />
                        <Detail label="ETF" value={product.etf_amount ? `$${product.etf_amount}` : null} />
                        <Detail label="Rate caption" value={product.rate_caption} />
                        <Detail label="Reward" value={product.reward_type ? `${product.reward_type}: ${product.reward_amount ?? '—'}` : null} />
                        <Detail label="Starts" value={formatDate(product.starts_at, timezone)} />
                        <Detail label="Ends" value={formatDate(product.ends_at, timezone)} />
                        <Detail label="Updated" value={formatDate(product.updated_at, timezone)} />
                        <div>
                            <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Supplier product</span>
                            <p className="mt-0.5 text-xs text-zinc-800 dark:text-zinc-200">
                                {product.supplier_product ? (
                                    <Link
                                        href={supplierProductsShow.url(product.supplier_product.id)}
                                        className="text-blue-600 hover:underline dark:text-blue-400"
                                    >
                                        {product.supplier_product.supplier?.name ?? 'Unknown'} / {product.supplier_product.external_id}
                                    </Link>
                                ) : (
                                    '—'
                                )}
                            </p>
                        </div>
                    </div>

                    {(product.renewal_text || product.notes) && (
                        <div className="grid grid-cols-1 gap-4 border-t border-zinc-200 p-4 text-sm dark:border-zinc-800 sm:grid-cols-2">
                            {product.renewal_text && (
                                <div>
                                    <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Renewal terms</span>
                                    <p className="mt-0.5 text-xs text-zinc-700 dark:text-zinc-300">{product.renewal_text}</p>
                                </div>
                            )}
                            {product.notes && (
                                <div>
                                    <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Notes</span>
                                    <p className="mt-0.5 text-xs text-zinc-700 dark:text-zinc-300">{product.notes}</p>
                                </div>
                            )}
                        </div>
                    )}
                </div>

                {/* Documents table */}
                <div className="space-y-3">
                    <div className="flex items-center justify-between">
                        <h2 className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                            Documents ({documents.total})
                        </h2>

                        {product.supplier_product?.supplier?.slug === 'apge' && (
                            <Form method="post" action={refreshProductDocuments.url(product.id)}>
                                {({ processing }) => (
                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-xs font-medium text-zinc-700 hover:bg-zinc-50 disabled:opacity-60 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-800"
                                    >
                                        {processing ? 'Refreshing…' : 'Refresh documents'}
                                    </button>
                                )}
                            </Form>
                        )}
                    </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 uppercase text-zinc-600 dark:border-zinc-800 dark:text-zinc-400">
                                    <tr>
                                        <th className="px-4 py-3">Type</th>
                                        <th className="px-4 py-3">Title</th>
                                        <th className="px-4 py-3">Language</th>
                                        <th className="px-4 py-3">Format</th>
                                        <th className="px-4 py-3">External ID</th>
                                        <th className="px-4 py-3">Link</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                    {documents.data.map((doc) => (
                                        <tr key={doc.id}>
                                            <td className="px-4 py-3 text-xs font-medium text-zinc-800 dark:text-zinc-200">
                                                {doc.type ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 text-xs text-zinc-700 dark:text-zinc-300">
                                                {doc.title ?? '—'}
                                            </td>
                                            <td className="px-4 py-3">
                                                <LanguageBadge language={doc.language} />
                                            </td>
                                            <td className="px-4 py-3 text-xs font-mono text-zinc-600 dark:text-zinc-400">
                                                {doc.file_type ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 font-mono text-xs text-zinc-600 dark:text-zinc-400">
                                                {doc.external_id ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 max-w-xs">
                                                {doc.view_url ? (
                                                    <a
                                                        href={doc.view_url}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="font-mono text-xs text-blue-600 hover:underline dark:text-blue-400"
                                                    >
                                                        {doc.local_file_path ? 'View PDF' : doc.view_url}
                                                    </a>
                                                ) : (
                                                    <span className="text-zinc-400">—</span>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

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

                    {documents.last_page > 1 && (
                        <div className="flex items-center justify-between text-sm">
                            <span className="text-zinc-500 dark:text-zinc-400">
                                Showing {(documents.current_page - 1) * documents.per_page + 1}–
                                {Math.min(documents.current_page * documents.per_page, documents.total)} of{' '}
                                {documents.total}
                            </span>
                            <div className="flex gap-1">
                                {documents.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 Detail({ label, value }: { label: string; value: string | null | undefined }) {
    return (
        <div>
            <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">{label}</span>
            <p className="mt-0.5 text-xs text-zinc-800 dark:text-zinc-200">{value ?? '—'}</p>
        </div>
    );
}
