import { Head, Link, router } from '@inertiajs/react';
import type { ColumnDef } from '@tanstack/react-table';
import {
    ArrowLeft,
    BadgeDollarSign,
    Download,
    History,
    Printer,
    Search,
    User,
} 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 { Input } from '@/components/ui/input';
import { StatusBadge } from '@/components/ui/status-badge';
import AppLayout from '@/layouts/app-layout';
import { formatDateID, formatIDR } from '@/lib/formatters';
import savingsRoutes from '@/routes/savings';
import type { BreadcrumbItem, PaginatedData } from '@/types';
import type { SavingsAccount, SavingsTransaction } from '@/types/savings';
import { transactionTypeConfig } from '@/types/savings';

interface PageProps {
    account: SavingsAccount;
    transactions?: PaginatedData<SavingsTransaction>;
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Simpanan', href: '/savings' },
    { title: 'Transaksi', href: '#' },
];

export default function Transactions({ account, transactions }: PageProps) {
    const columns: ColumnDef<SavingsTransaction>[] = [
        {
            accessorKey: 'transaction_number',
            header: 'Nomor Transaksi',
            cell: ({ row }) => (
                <span className="font-mono text-sm">
                    {row.getValue('transaction_number')}
                </span>
            ),
        },
        {
            accessorKey: 'type',
            header: 'Jenis',
            cell: ({ row }) => {
                const type = row.getValue('type') as 'deposit' | 'withdrawal';
                const config = transactionTypeConfig[type];
                return (
                    <span
                        className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-semibold ${config.color}`}
                    >
                        {config.icon} {config.label}
                    </span>
                );
            },
        },
        {
            accessorKey: 'amount',
            header: 'Jumlah',
            cell: ({ row }) => {
                const type = row.getValue('type') as 'deposit' | 'withdrawal';
                const amount = row.getValue('amount') as number;
                return (
                    <span
                        className={`font-bold ${
                            type === 'deposit'
                                ? 'text-green-600'
                                : 'text-red-600'
                        }`}
                    >
                        {type === 'deposit' ? '+' : '-'}
                        {formatIDR(amount)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'balance_before',
            header: 'Saldo Sebelum',
            cell: ({ row }) => formatIDR(row.getValue('balance_before')),
        },
        {
            accessorKey: 'balance_after',
            header: 'Saldo Sesudah',
            cell: ({ row }) => formatIDR(row.getValue('balance_after')),
        },
        {
            accessorKey: 'description',
            header: 'Keterangan',
            cell: ({ row }) => row.getValue('description') || '-',
        },
        {
            accessorKey: 'created_at',
            header: 'Tanggal',
            cell: ({ row }) => formatDateID(row.getValue('created_at')),
        },
        {
            accessorKey: 'is_posted',
            header: 'Status',
            cell: ({ row }) => (
                <StatusBadge
                    type="member"
                    status={
                        row.getValue('is_posted') ? 'verified' : 'unverified'
                    }
                    customLabel={
                        row.getValue('is_posted') ? 'Posted' : 'Unposted'
                    }
                />
            ),
        },
        {
            id: 'actions',
            header: 'Struk',
            cell: ({ row }) => (
                <Button variant="outline" size="sm" asChild>
                    <a
                        href={
                            savingsRoutes.transactions.receipt({
                                transaction: row.original.id,
                            }).url
                        }
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        <Printer className="mr-1 h-3 w-3" />
                        Struk
                    </a>
                </Button>
            ),
        },
    ];

    const handleSearch = (value: string) => {
        const params = new URLSearchParams(window.location.search);
        if (value) {
            params.set('search', value);
        } else {
            params.delete('search');
        }
        params.delete('page');
        router.visit(
            `${savingsRoutes.transactions({ account: account.id }).url}?${params.toString()}`,
        );
    };

    const exportToCSV = () => {
        if (!transactions) return;

        const csv = [
            [
                'Nomor Transaksi',
                'Jenis',
                'Jumlah',
                'Saldo Sebelum',
                'Saldo Sesudah',
                'Keterangan',
                'Tanggal',
                'Status',
            ].join(','),
            ...transactions.data.map((transaction) =>
                [
                    transaction.transaction_number,
                    transaction.type === 'deposit' ? 'Setoran' : 'Penarikan',
                    transaction.amount.toString(),
                    transaction.balance_before.toString(),
                    transaction.balance_after.toString(),
                    transaction.description || '',
                    transaction.created_at,
                    transaction.is_posted ? 'Posted' : 'Unposted',
                ].join(','),
            ),
        ].join('\n');

        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `transaksi_${account.account_number}_${new Date().toISOString().split('T')[0]}.csv`;
        a.click();
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Transaksi ${account.account_number}`} />

            <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 items-center gap-4">
                        <Button variant="ghost" size="icon" asChild>
                            <Link
                                href={
                                    savingsRoutes.show({ account: account.id })
                                        .url
                                }
                            >
                                <ArrowLeft className="h-4 w-4" />
                            </Link>
                        </Button>
                        <div className="flex flex-col gap-1">
                            <h1 className="text-2xl font-black">
                                Riwayat Transaksi
                            </h1>
                            <div className="flex items-center gap-2">
                                <span className="text-sm text-muted-foreground">
                                    {account.account_number} -{' '}
                                    {account.account_name}
                                </span>
                                <StatusBadge
                                    type="savings"
                                    status={account.status}
                                />
                            </div>
                        </div>
                    </div>
                    <Button
                        variant="outline"
                        onClick={exportToCSV}
                        disabled={!transactions}
                    >
                        <Download className="mr-2 h-4 w-4" />
                        Export CSV
                    </Button>
                </div>

                {/* Account Summary */}
                <div className="grid gap-4 md:grid-cols-3">
                    <Card>
                        <CardHeader>
                            <CardTitle>Saldo Saat Ini</CardTitle>
                            <CardAction>
                                <BadgeDollarSign className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">
                                {formatIDR(account.balance)}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                &nbsp;
                            </p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Total Transaksi</CardTitle>
                            <CardAction>
                                <History className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">
                                {transactions?.total}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                &nbsp;
                            </p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Anggota</CardTitle>
                            <CardAction>
                                <User className="h-4 w-4" />
                            </CardAction>
                        </CardHeader>
                        <CardContent>
                            <div className="truncate text-2xl font-bold">
                                {account.member?.name || 'Unknown'}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                &nbsp;
                            </p>
                        </CardContent>
                    </Card>
                </div>

                {/* Search */}
                <div className="flex w-full md:w-1/2">
                    <div className="relative w-full">
                        <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                            id="search"
                            placeholder="Cari berdasarkan nomor transaksi..."
                            className="pl-10"
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    handleSearch(e.currentTarget.value);
                                }
                            }}
                            onBlur={(e) => handleSearch(e.currentTarget.value)}
                        />
                    </div>
                </div>

                {/* Table */}
                <DataTable
                    columns={columns}
                    data={transactions?.data || []}
                    pagination={{
                        currentPage: transactions?.current_page || 1,
                        lastPage: transactions?.last_page || 1,
                    }}
                />
            </div>
        </AppLayout>
    );
}
