import { Head, Link } from '@inertiajs/react';
import type { ColumnDef } from '@tanstack/react-table';
import { Eye, HistoryIcon, SearchIcon } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
    Card,
    CardAction,
    CardContent,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { DataTable } from '@/components/ui/data-table';
import {
    InputGroup,
    InputGroupAddon,
    InputGroupInput,
} from '@/components/ui/input-group';
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { usePermissions } from '@/hooks/use-permissions';
import AppLayout from '@/layouts/app-layout';
import { formatDateID, formatIDR } from '@/lib/formatters';
import { useFilterParams } from '@/lib/hooks/useFilterParams';
import type {
    BreadcrumbItem,
    CashCount,
    CashCountFilters,
    PaginatedData,
} from '@/types';

interface TellerOption {
    id: number;
    name: string;
}

interface Props {
    cashCounts: PaginatedData<CashCount>;
    tellers: TellerOption[];
    filters: CashCountFilters;
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Kas & Teller', href: '/cash-counts' },
];

const STATUS_CONFIG = {
    balanced: {
        label: 'Seimbang',
        className: 'bg-emerald-100 text-emerald-800 border border-emerald-200',
    },
    over: {
        label: 'Lebih',
        className: 'bg-amber-100 text-amber-800 border border-amber-200',
    },
    short: {
        label: 'Kurang',
        className: 'bg-red-100 text-red-800 border border-red-200',
    },
} as const;

export default function Index({ cashCounts, tellers, filters }: Props) {
    const { hasAnyRole } = usePermissions();

    const { updateFilter, updatePage } = useFilterParams({
        baseUrl: '/cash-counts',
    });

    const totalCounts = cashCounts.total;
    const balancedCount = cashCounts.data.filter(
        (c) => c.status === 'balanced',
    ).length;
    const discrepancyCount = cashCounts.data.filter(
        (c) => c.status !== 'balanced',
    ).length;

    const columns: ColumnDef<CashCount>[] = [
        {
            accessorKey: 'date',
            header: 'Tanggal',
            cell: ({ row }) => (
                <span className="font-medium">
                    {formatDateID(row.getValue('date'))}
                </span>
            ),
        },
        {
            accessorKey: 'teller.name',
            header: 'Teller',
            cell: ({ row }) =>
                row.original.teller?.name ?? (
                    <span className="text-muted-foreground">—</span>
                ),
        },
        {
            accessorKey: 'physical_total',
            header: 'Kas Fisik',
            cell: ({ row }) => (
                <span className="tabular-nums">
                    {formatIDR(Number(row.getValue('physical_total')))}
                </span>
            ),
        },
        {
            accessorKey: 'system_balance',
            header: 'Saldo Sistem',
            cell: ({ row }) => (
                <span className="text-muted-foreground tabular-nums">
                    {formatIDR(Number(row.getValue('system_balance')))}
                </span>
            ),
        },
        {
            accessorKey: 'difference',
            header: 'Selisih',
            cell: ({ row }) => {
                const diff = Number(row.getValue('difference'));
                return (
                    <span
                        className={`font-medium tabular-nums ${
                            diff === 0
                                ? 'text-emerald-600'
                                : diff > 0
                                  ? 'text-amber-600'
                                  : 'text-red-600'
                        }`}
                    >
                        {diff >= 0 ? '+' : ''}
                        {formatIDR(diff)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'status',
            header: 'Status',
            cell: ({ row }) => {
                const status = row.getValue(
                    'status',
                ) as keyof typeof STATUS_CONFIG;
                const cfg = STATUS_CONFIG[status] ?? STATUS_CONFIG.balanced;
                return (
                    <span
                        className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ${cfg.className}`}
                    >
                        {cfg.label}
                    </span>
                );
            },
        },
        {
            id: 'actions',
            cell: ({ row }) => (
                <Button variant="ghost" size="sm" asChild>
                    <Link href={`/cash-counts/${row.original.id}`}>
                        <Eye className="h-4 w-4" />
                        Detail
                    </Link>
                </Button>
            ),
        },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="History Hitung Kas" />

            <div className="flex h-full flex-1 flex-col gap-4 overflow-x-auto rounded-xl p-4">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div className="flex flex-col gap-1">
                        <h1 className="text-2xl font-black">
                            History Hitung Kas
                        </h1>
                        <span className="text-sm text-muted-foreground">
                            Rekap hitung kas fisik harian semua teller
                        </span>
                    </div>
                    {hasAnyRole('Administrator', 'Manager', 'Teller') && (
                        <Button asChild>
                            <Link href="/cash-counts/create">
                                Hitung Kas Hari Ini
                            </Link>
                        </Button>
                    )}
                </div>

                {/* Stats */}
                <div className="grid gap-4 md:grid-cols-3">
                    <Card>
                        <CardHeader>
                            <CardTitle>Total Hitung Kas</CardTitle>
                            <CardAction>
                                <HistoryIcon className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">
                                {totalCounts.toLocaleString('id-ID')}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Semua catatan
                            </p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardHeader>
                            <CardTitle>Seimbang</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold text-emerald-600">
                                {balancedCount}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Di halaman ini
                            </p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardHeader>
                            <CardTitle>Ada Selisih</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold text-red-600">
                                {discrepancyCount}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Perlu perhatian
                            </p>
                        </CardContent>
                    </Card>
                </div>

                {/* Filters */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center">
                    <div className="flex items-center gap-2">
                        <InputGroup className="max-w-xs">
                            <InputGroupAddon align="inline-start">
                                <SearchIcon className="h-4 w-4" />
                            </InputGroupAddon>
                            <InputGroupInput
                                id="date-filter"
                                type="date"
                                className="pl-10"
                                defaultValue={filters.date}
                                onChange={(e) =>
                                    updateFilter('date', e.target.value)
                                }
                            />
                        </InputGroup>
                    </div>

                    <Select
                        defaultValue={filters.teller_id || 'all'}
                        onValueChange={(v) =>
                            updateFilter('teller_id', v === 'all' ? '' : v)
                        }
                    >
                        <SelectTrigger className="w-full md:w-52">
                            <SelectValue placeholder="Semua Teller" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectLabel>Teller</SelectLabel>
                                <SelectItem value="all">
                                    Semua Teller
                                </SelectItem>
                                {tellers.map((t) => (
                                    <SelectItem
                                        key={t.id}
                                        value={t.id.toString()}
                                    >
                                        {t.name}
                                    </SelectItem>
                                ))}
                            </SelectGroup>
                        </SelectContent>
                    </Select>
                </div>

                {/* Table */}
                <DataTable
                    columns={columns}
                    data={cashCounts.data}
                    pagination={{
                        currentPage: cashCounts.current_page,
                        lastPage: cashCounts.last_page,
                        onNext: () => updatePage(cashCounts.current_page + 1),
                        onPrev: () => updatePage(cashCounts.current_page - 1),
                    }}
                />
            </div>
        </AppLayout>
    );
}
