import { Head, Link } from '@inertiajs/react';
import { AlertCircle, ArrowLeft, CheckCircle2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import { formatDateID, formatIDR } from '@/lib/formatters';
import type { BreadcrumbItem, CashCount } from '@/types';

interface Props {
    cashCount: CashCount;
}

const DENOMINATION_LABELS: Record<number, string> = {
    1000: 'Rp 1.000',
    2000: 'Rp 2.000',
    5000: 'Rp 5.000',
    10000: 'Rp 10.000',
    20000: 'Rp 20.000',
    50000: 'Rp 50.000',
    100000: 'Rp 100.000',
};

const STATUS_CONFIG = {
    balanced: {
        label: 'Seimbang',
        className: 'bg-emerald-100 text-emerald-800 border-emerald-200',
        icon: <CheckCircle2 className="h-4 w-4" />,
    },
    over: {
        label: 'Lebih',
        className: 'bg-amber-100 text-amber-800 border-amber-200',
        icon: <AlertCircle className="h-4 w-4" />,
    },
    short: {
        label: 'Kurang',
        className: 'bg-red-100 text-red-800 border-red-200',
        icon: <AlertCircle className="h-4 w-4" />,
    },
} as const;

export default function Show({ cashCount }: Props) {
    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Kas & Teller', href: '/cash-counts' },
        {
            title: `Hitung Kas ${formatDateID(cashCount.date)}`,
            href: `/cash-counts/${cashCount.id}`,
        },
    ];

    const status =
        STATUS_CONFIG[cashCount.status as keyof typeof STATUS_CONFIG] ??
        STATUS_CONFIG.balanced;

    const diff = Number(cashCount.difference);
    const physicalTotal = Number(cashCount.physical_total);
    const systemBalance = Number(cashCount.system_balance);

    const submittedAt = new Date(cashCount.created_at).toLocaleString('id-ID', {
        day: '2-digit',
        month: 'long',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    });

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Hitung Kas ${cashCount.date}`} />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                {/* Header */}
                <div className="flex items-start justify-between">
                    <div className="flex flex-col gap-1">
                        <div className="flex items-center gap-3">
                            <h1 className="text-2xl font-black">
                                Hitung Kas Fisik
                            </h1>
                            <span
                                className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-sm font-semibold ${status.className}`}
                            >
                                {status.icon}
                                {status.label}
                            </span>
                        </div>
                        <span className="text-sm text-muted-foreground">
                            Tanggal {formatDateID(cashCount.date)} ·{' '}
                            {cashCount.teller?.name ?? '—'} · Disubmit{' '}
                            {submittedAt}
                        </span>
                    </div>
                    <Button variant="outline" size="sm" asChild>
                        <Link href="/cash-counts">
                            <ArrowLeft className="h-4 w-4" />
                            Kembali
                        </Link>
                    </Button>
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    {/* Denomination Breakdown */}
                    <div className="lg:col-span-2">
                        <Card>
                            <CardHeader>
                                <CardTitle className="text-base">
                                    Rincian Per Pecahan
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <div className="overflow-x-auto">
                                    <table className="w-full text-sm">
                                        <thead>
                                            <tr className="border-b text-muted-foreground">
                                                <th className="pb-3 text-left font-medium">
                                                    Pecahan
                                                </th>
                                                <th className="pb-3 text-center font-medium">
                                                    Jumlah Lembar
                                                </th>
                                                <th className="pb-3 text-right font-medium">
                                                    Subtotal
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y">
                                            {[...(cashCount.details || [])]
                                                .sort(
                                                    (a, b) =>
                                                        Number(b.denomination) -
                                                        Number(a.denomination),
                                                )
                                                .map((detail) => (
                                                    <tr
                                                        key={detail.id}
                                                        className={
                                                            detail.quantity > 0
                                                                ? ''
                                                                : 'opacity-40'
                                                        }
                                                    >
                                                        <td className="py-3 font-medium">
                                                            <div className="flex items-center gap-2">
                                                                <div
                                                                    className={`h-2 w-2 rounded-full ${detail.quantity > 0 ? 'bg-primary' : 'bg-muted-foreground'}`}
                                                                />
                                                                {DENOMINATION_LABELS[
                                                                    detail
                                                                        .denomination
                                                                ] ??
                                                                    `Rp ${detail.denomination.toLocaleString('id-ID')}`}
                                                            </div>
                                                        </td>
                                                        <td className="py-3 text-center tabular-nums">
                                                            {detail.quantity.toLocaleString(
                                                                'id-ID',
                                                            )}{' '}
                                                            lembar
                                                        </td>
                                                        <td className="py-3 text-right font-medium tabular-nums">
                                                            {detail.quantity >
                                                            0 ? (
                                                                formatIDR(
                                                                    Number(
                                                                        detail.subtotal,
                                                                    ),
                                                                )
                                                            ) : (
                                                                <span className="text-muted-foreground">
                                                                    —
                                                                </span>
                                                            )}
                                                        </td>
                                                    </tr>
                                                ))}
                                        </tbody>
                                        <tfoot>
                                            <tr className="border-t-2 bg-muted/20">
                                                <td
                                                    colSpan={2}
                                                    className="py-3 font-bold"
                                                >
                                                    Total Kas Fisik
                                                </td>
                                                <td className="py-3 text-right text-lg font-bold text-primary tabular-nums">
                                                    {formatIDR(physicalTotal)}
                                                </td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </CardContent>
                        </Card>
                    </div>

                    {/* Summary Panel */}
                    <div className="flex flex-col gap-4">
                        <Card className="border-2">
                            <CardHeader>
                                <CardTitle className="text-base">
                                    Ringkasan
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="flex flex-col gap-4">
                                <div className="rounded-lg bg-muted/40 p-3">
                                    <div className="text-xs text-muted-foreground">
                                        Saldo Kas Sistem
                                    </div>
                                    <div className="mt-1 text-xl font-bold tabular-nums">
                                        {formatIDR(systemBalance)}
                                    </div>
                                </div>

                                <div>
                                    <div className="text-xs text-muted-foreground">
                                        Total Kas Fisik
                                    </div>
                                    <div className="mt-1 text-2xl font-black text-primary tabular-nums">
                                        {formatIDR(physicalTotal)}
                                    </div>
                                </div>

                                <hr />

                                <div>
                                    <div className="text-xs text-muted-foreground">
                                        Selisih
                                    </div>
                                    <div
                                        className={`mt-1 text-xl font-bold tabular-nums ${
                                            diff === 0
                                                ? 'text-emerald-600'
                                                : diff > 0
                                                  ? 'text-amber-600'
                                                  : 'text-red-600'
                                        }`}
                                    >
                                        {diff >= 0 ? '+' : ''}
                                        {formatIDR(diff)}
                                    </div>
                                </div>
                            </CardContent>
                        </Card>

                        {/* Note if present */}
                        {cashCount.note && (
                            <Card className="border-amber-200 bg-amber-50 dark:bg-amber-950/20">
                                <CardHeader className="pb-2">
                                    <CardTitle className="text-sm text-amber-700 dark:text-amber-400">
                                        Keterangan Selisih
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <p className="text-sm text-amber-800 dark:text-amber-300">
                                        {cashCount.note}
                                    </p>
                                </CardContent>
                            </Card>
                        )}
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}
