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

import HeadingSmall from '@/components/heading-small';
import { SortableHeader } from '@/components/sortable-header';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
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, show as productsShow } from '@/routes/admin/products';
import { index as supplierProductsIndex } from '@/routes/admin/supplier-products';

type SupplierProduct = {
    id: number;
    external_id: string;
    supplier: { id: number; name: 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; electric_usage_uom: string | null; gas_usage_uom: string | null } | null;
    state: { id: number; code: string } | null;
    supplier_product: SupplierProduct | null;
};

type PaginatedProducts = {
    data: Product[];
    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;
    status: string;
    supplier_id: string;
    utility_id: string;
    state_id: string;
    sort_by: string;
    sort_direction: string;
};

type Props = {
    products: PaginatedProducts;
    filters: Filters;
    suppliers: { id: number; name: string }[];
    utilities: { id: number; name: string }[];
    states: { id: number; code: string; name: string }[];
};


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] ?? 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400'}`}
        >
            {status}
        </span>
    );
}

function formatRate(rate: string | null, uom: string | null = null): string {
    if (!rate) return '—';
    const formatted = parseFloat(rate).toFixed(4);
    return uom ? `${formatted} ${uom}` : formatted;
}

function getUom(product: Product): string | null {
    if (!product.utility) return null;
    if (product.energy_type === 'electric') return product.utility.electric_usage_uom;
    if (product.energy_type === 'gas') return product.utility.gas_usage_uom;
    return null;
}

const breadcrumbs = [{ title: 'Products', href: productsIndex.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 Products({ products, filters, suppliers, utilities, states }: Props) {
    const timezone = useUserTimezone();
    const [search, setSearch] = useState(filters.search);
    const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);

    const sortColumn = filters.sort_by || 'updated_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(
            productsIndex.url(),
            Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== '')),
            { preserveState: true, replace: true },
        );
    }

    const hasActiveFilters =
        filters.search || filters.status !== 'active' || filters.supplier_id || filters.utility_id || filters.state_id;

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

            <h1 className="sr-only">Products</h1>

            <div className="space-y-6">
                <HeadingSmall
                    title="Products"
                    description="Canonical product models normalized from supplier data."
                />

                {/* Filters */}
                <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-[240px]">
                        <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="Product name, utility, or state…"
                            className={selectClasses}
                        />
                    </div>

                    <div className="flex flex-col gap-1">
                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                            Supplier
                        </label>
                        <select
                            value={filters.supplier_id}
                            onChange={(e) => applyFilters({ supplier_id: e.target.value })}
                            className={selectClasses}
                        >
                            <option value="">All suppliers</option>
                            {suppliers.map((s) => (
                                <option key={s.id} value={s.id}>
                                    {s.name}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="flex flex-col gap-1">
                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                            Utility
                        </label>
                        <select
                            value={filters.utility_id}
                            onChange={(e) => applyFilters({ utility_id: e.target.value })}
                            className={selectClasses}
                        >
                            <option value="">All utilities</option>
                            {utilities.map((u) => (
                                <option key={u.id} value={u.id}>
                                    {u.name}
                                </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_id}
                            onChange={(e) => applyFilters({ state_id: e.target.value })}
                            className={selectClasses}
                        >
                            <option value="">All states</option>
                            {states.map((s) => (
                                <option key={s.id} value={s.id}>
                                    {s.code} — {s.name}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="flex flex-col gap-1">
                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                            Status
                        </label>
                        <select
                            value={filters.status}
                            onChange={(e) => applyFilters({ status: e.target.value })}
                            className={selectClasses}
                        >
                            <option value="all">All</option>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                            <option value="archived">Archived</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: '',
                                    status: '',
                                    supplier_id: '',
                                    utility_id: '',
                                    state_id: '',
                                });
                            }}
                            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>

                {/* Products table */}
                <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>
                                    <SortableHeader label="ID" column="id" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Name" column="name" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <th className="px-4 py-3">Utility</th>
                                    <th className="px-4 py-3">State</th>
                                    <SortableHeader label="Energy" column="energy_type" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Rate" column="rate" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Type" column="rate_type" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Term Months" column="term_months" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Term" column="term_text" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Status" column="status" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <th className="px-4 py-3">Supplier Product</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {products.data.map((product) => (
                                    <tr
                                        key={product.id}
                                        className="cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-900"
                                        onClick={() => setSelectedProduct(product)}
                                    >
                                        <td className="px-4 py-3">
                                            <Link
                                                href={productsShow.url(product.id)}
                                                className="font-mono text-xs text-blue-600 hover:underline dark:text-blue-400"
                                                onClick={(e) => e.stopPropagation()}
                                            >
                                                {product.id}
                                            </Link>
                                        </td>
                                        <td className="px-4 py-3 font-medium">
                                            {productProperName(product.name)}
                                        </td>
                                        <td className="px-4 py-3">
                                            {product.utility?.name ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 font-mono text-xs">
                                            {product.state?.code ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-xs text-zinc-600 dark:text-zinc-400">
                                            {product.energy_type ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 font-mono text-xs">
                                            {formatRate(product.rate, getUom(product))}
                                        </td>
                                        <td className="px-4 py-3 text-xs text-zinc-600 dark:text-zinc-400">
                                            {product.rate_type ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-xs">
                                            {product.term_months ?? '-'}
                                        </td>
                                        <td className="px-4 py-3 text-xs">
                                            {product.term_text ?? '—'}
                                        </td>
                                        <td className="px-4 py-3">
                                            <StatusBadge status={product.status} />
                                        </td>
                                        <td className="px-4 py-3">
                                            {product.supplier_product ? (
                                                <Link
                                                    href={supplierProductsIndex.url({
                                                        query: {
                                                            supplier_id:
                                                                product.supplier_product.supplier
                                                                    ?.id ?? '',
                                                        },
                                                    })}
                                                    className="font-mono text-xs text-blue-600 hover:underline dark:text-blue-400"
                                                    onClick={(e) => e.stopPropagation()}
                                                >
                                                    {product.supplier_product.supplier?.name ?? 'Unknown'}{' '}
                                                    / {product.supplier_product.external_id}
                                                </Link>
                                            ) : (
                                                <span className="text-xs text-zinc-400">—</span>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

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

                {/* Pagination */}
                {products.last_page > 1 && (
                    <div className="flex items-center justify-between text-sm">
                        <span className="text-zinc-500 dark:text-zinc-400">
                            Showing {(products.current_page - 1) * products.per_page + 1}–
                            {Math.min(products.current_page * products.per_page, products.total)} of{' '}
                            {products.total}
                        </span>
                        <div className="flex gap-1">
                            {products.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>
            <Dialog open={selectedProduct !== null} onOpenChange={(open) => { if (!open) setSelectedProduct(null); }}>
                <DialogContent className="max-w-2xl">
                    {selectedProduct && (
                        <>
                            <DialogHeader>
                                <DialogTitle>{productProperName(selectedProduct.name)}</DialogTitle>
                            </DialogHeader>

                            <div className="grid grid-cols-2 gap-x-8 gap-y-3 sm:grid-cols-3">
                                <Detail label="ID" value={String(selectedProduct.id)} />
                                <Detail label="Status" value={selectedProduct.status} />
                                <Detail label="Utility" value={selectedProduct.utility?.name ?? null} />
                                <Detail label="State" value={selectedProduct.state?.code ?? null} />
                                <Detail label="Energy type" value={selectedProduct.energy_type} />
                                <Detail label="Account type" value={selectedProduct.account_type} />
                                <Detail label="Rate" value={formatRate(selectedProduct.rate, getUom(selectedProduct))} />
                                <Detail label="Rate type" value={selectedProduct.rate_type} />
                                <Detail label="Base rate" value={selectedProduct.base_rate ? `$${selectedProduct.base_rate}` : null} />
                                <Detail label="Rate caption" value={selectedProduct.rate_caption} />
                                <Detail label="Term months" value={selectedProduct.term_months !== null ? String(selectedProduct.term_months) : null} />
                                <Detail label="Term" value={selectedProduct.term_text} />
                                <Detail label="ETF" value={selectedProduct.etf_amount !== null ? `$${selectedProduct.etf_amount}` : null} />
                                <Detail label="Reward" value={selectedProduct.reward_type ? `${selectedProduct.reward_type}: ${selectedProduct.reward_amount ?? '—'}` : null} />
                                <Detail label="Starts" value={formatDate(selectedProduct.starts_at, timezone)} />
                                <Detail label="Ends" value={formatDate(selectedProduct.ends_at, timezone)} />
                                <Detail label="Updated" value={formatDate(selectedProduct.updated_at, timezone)} />
                                {selectedProduct.supplier_product && (
                                    <Detail
                                        label="Supplier product"
                                        value={`${selectedProduct.supplier_product.supplier?.name ?? 'Unknown'} / ${selectedProduct.supplier_product.external_id}`}
                                    />
                                )}
                            </div>

                            {(selectedProduct.renewal_text || selectedProduct.notes) && (
                                <div className="space-y-3 border-t border-zinc-200 pt-4 dark:border-zinc-800">
                                    {selectedProduct.renewal_text && (
                                        <div>
                                            <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Renewal terms</span>
                                            <p className="mt-1 text-xs text-zinc-700 dark:text-zinc-300">{selectedProduct.renewal_text}</p>
                                        </div>
                                    )}
                                    {selectedProduct.notes && (
                                        <div>
                                            <span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Notes</span>
                                            <p className="mt-1 text-xs text-zinc-700 dark:text-zinc-300">{selectedProduct.notes}</p>
                                        </div>
                                    )}
                                </div>
                            )}
                        </>
                    )}
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}

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