import { Head, Link, router } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import AdminLayout from '@/components/Layouts/AdminLayout';
import Card from '@/components/Card/Card';
import Table, { TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '@/components/Table/Table';
import SearchInput from '@/components/SearchInput/SearchInput';
import RefreshButton from '@/components/RefreshButton/RefreshButton';
import Select from '@/components/Select/Select';

interface Transaction {
    id: string;
    type: 'topup' | 'purchase';
    user_id: number;
    user_name: string;
    user_email: string;
    reference_code?: string;
    amount: number;
    coins: number;
    fee?: number;
    status?: string;
    payment_channel?: string;
    show_id?: number;
    show_title?: string;
    created_at: string;
    paid_at?: string;
    expires_at?: string;
}

interface TransactionsPageProps {
    transactions: Transaction[];
    pagination: {
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        type: string;
        status: string;
        search: string;
    };
    stats: {
        total_topups: number;
        successful_topups: number;
        pending_topups: number;
        total_topup_amount: number;
        total_topup_fee: number;
        total_coins_distributed: number;
        total_purchases: number;
        total_coins_spent: number;
        total_purchase_amount: number;
    };
}

export default function Index({ transactions = [], pagination, filters = {}, stats }: TransactionsPageProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [typeFilter, setTypeFilter] = useState(filters.type || 'all');
    const [statusFilter, setStatusFilter] = useState(filters.status || '');

    const handleSearchClear = () => {
        setSearch('');
    };

    useEffect(() => {
        const timer = setTimeout(() => {
            router.get(
                '/admin/transactions',
                {
                    type: typeFilter,
                    status: statusFilter || undefined,
                    search: search || undefined,
                },
                {
                    preserveState: true,
                    preserveScroll: true,
                    replace: true,
                }
            );
        }, 300);

        return () => clearTimeout(timer);
    }, [search, typeFilter, statusFilter]);

    const formatPrice = (price: number): string => {
        return new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            minimumFractionDigits: 0,
        }).format(price);
    };

    const formatDate = (dateString: string): string => {
        return new Date(dateString).toLocaleString('id-ID', {
            day: 'numeric',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    const getStatusConfig = (status: string) => {
        switch (status) {
            case 'success':
                return {
                    color: 'text-green-600 dark:text-green-400',
                    bgColor: 'bg-green-100 dark:bg-green-900/30',
                    label: 'Berhasil',
                };
            case 'pending':
                return {
                    color: 'text-yellow-600 dark:text-yellow-400',
                    bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
                    label: 'Menunggu',
                };
            case 'processing':
                return {
                    color: 'text-blue-600 dark:text-blue-400',
                    bgColor: 'bg-blue-100 dark:bg-blue-900/30',
                    label: 'Diproses',
                };
            case 'failed':
                return {
                    color: 'text-red-600 dark:text-red-400',
                    bgColor: 'bg-red-100 dark:bg-red-900/30',
                    label: 'Gagal',
                };
            case 'cancelled':
                return {
                    color: 'text-gray-600 dark:text-gray-400',
                    bgColor: 'bg-gray-100 dark:bg-gray-800',
                    label: 'Dibatalkan',
                };
            default:
                return {
                    color: 'text-gray-600 dark:text-gray-400',
                    bgColor: 'bg-gray-100 dark:bg-gray-800',
                    label: status || 'N/A',
                };
        }
    };

    return (
        <AdminLayout title="Transactions Management">
            <Head title="Transactions Management" />
            <div className="space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Transactions Management</h2>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            Kelola dan monitor semua transaksi topup coin dan pembelian show
                        </p>
                    </div>
                    <RefreshButton />
                </div>

                {/* Stats Cards */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Topups</p>
                                <p className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                                    {stats.total_topups.toLocaleString('id-ID')}
                                </p>
                                <p className="mt-1 text-xs text-green-600 dark:text-green-400">
                                    {stats.successful_topups} Berhasil
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-blue-100 dark:bg-blue-900/20">
                                <CurrencyDollarIcon className="h-6 w-6 text-blue-600 dark:text-blue-400" />
                            </div>
                        </div>
                    </Card>

                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Revenue</p>
                                <p className="mt-2 text-xl font-bold text-gray-900 dark:text-white">
                                    {formatPrice(stats.total_topup_amount - stats.total_topup_fee)}
                                </p>
                                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Fee: {formatPrice(stats.total_topup_fee)}
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-green-100 dark:bg-green-900/20">
                                <BanknotesIcon className="h-6 w-6 text-green-600 dark:text-green-400" />
                            </div>
                        </div>
                    </Card>

                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Coins Distributed</p>
                                <p className="mt-2 text-2xl font-bold text-[#d4af37] dark:text-[#b8941f]">
                                    {stats.total_coins_distributed.toLocaleString('id-ID')} NGD
                                </p>
                                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    {stats.total_coins_spent.toLocaleString('id-ID')} Spent
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-[#d4af37]/10 dark:bg-[#b8941f]/20">
                                <CoinIcon className="h-6 w-6 text-[#d4af37] dark:text-[#b8941f]" />
                            </div>
                        </div>
                    </Card>

                    <Card padding="md">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Purchases</p>
                                <p className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                                    {stats.total_purchases.toLocaleString('id-ID')}
                                </p>
                                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    {formatPrice(stats.total_purchase_amount)}
                                </p>
                            </div>
                            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-purple-100 dark:bg-purple-900/20">
                                <TicketIcon className="h-6 w-6 text-purple-600 dark:text-purple-400" />
                            </div>
                        </div>
                    </Card>
                </div>

                {/* Filters */}
                <Card padding="md">
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Cari Transaksi
                            </label>
                            <SearchInput
                                placeholder="Cari berdasarkan user atau reference code..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                onClear={handleSearchClear}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Tipe
                            </label>
                            <Select
                                value={typeFilter}
                                onChange={(e) => setTypeFilter(e.target.value)}
                                options={[
                                    { value: 'all', label: 'Semua Tipe' },
                                    { value: 'topup', label: 'Topup Coin' },
                                    { value: 'purchase', label: 'Pembelian Show' },
                                ]}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Status
                            </label>
                            <Select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value)}
                                options={[
                                    { value: '', label: 'Semua Status' },
                                    { value: 'success', label: 'Berhasil' },
                                    { value: 'pending', label: 'Menunggu' },
                                    { value: 'processing', label: 'Diproses' },
                                    { value: 'failed', label: 'Gagal' },
                                    { value: 'cancelled', label: 'Dibatalkan' },
                                ]}
                            />
                        </div>
                    </div>
                </Card>

                {/* Transactions Table */}
                <Card padding="none">
                    <div className="overflow-x-auto">
                        <Table pagination={pagination}>
                            <TableHeader>
                                <TableHeaderCell>User</TableHeaderCell>
                                <TableHeaderCell>Tipe</TableHeaderCell>
                                <TableHeaderCell>Detail</TableHeaderCell>
                                <TableHeaderCell>Jumlah</TableHeaderCell>
                                <TableHeaderCell>Coins</TableHeaderCell>
                                <TableHeaderCell>Status</TableHeaderCell>
                                <TableHeaderCell>Waktu</TableHeaderCell>
                            </TableHeader>
                            <TableBody>
                                {transactions.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-8 text-gray-500 dark:text-gray-400">
                                            Tidak ada transaksi
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    transactions.map((transaction) => {
                                        const statusConfig = transaction.status ? getStatusConfig(transaction.status) : null;

                                        return (
                                            <TableRow key={transaction.id}>
                                                <TableCell>
                                                    <div>
                                                        <div className="font-medium text-gray-900 dark:text-white">
                                                            {transaction.user_name}
                                                        </div>
                                                        <div className="text-sm text-gray-500 dark:text-gray-400">
                                                            {transaction.user_email}
                                                        </div>
                                                    </div>
                                                </TableCell>
                                                <TableCell>
                                                    {transaction.type === 'topup' ? (
                                                        <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-1 text-xs font-semibold text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
                                                            <CurrencyDollarIcon className="h-3 w-3" />
                                                            Topup
                                                        </span>
                                                    ) : (
                                                        <span className="inline-flex items-center gap-1 rounded-full bg-purple-100 px-2 py-1 text-xs font-semibold text-purple-800 dark:bg-purple-900/30 dark:text-purple-400">
                                                            <TicketIcon className="h-3 w-3" />
                                                            Purchase
                                                        </span>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    {transaction.type === 'topup' ? (
                                                        <div>
                                                            <div className="text-sm font-medium text-gray-900 dark:text-white">
                                                                {transaction.reference_code || 'N/A'}
                                                            </div>
                                                            {transaction.payment_channel && (
                                                                <div className="text-xs text-gray-500 dark:text-gray-400">
                                                                    {transaction.payment_channel}
                                                                </div>
                                                            )}
                                                        </div>
                                                    ) : (
                                                        <div>
                                                            <div className="text-sm font-medium text-gray-900 dark:text-white">
                                                                {transaction.show_title || 'N/A'}
                                                            </div>
                                                            <div className="text-xs text-gray-500 dark:text-gray-400">
                                                                Show ID: {transaction.show_id || 'N/A'}
                                                            </div>
                                                        </div>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <div className="text-sm font-semibold text-gray-900 dark:text-white">
                                                        {formatPrice(transaction.amount)}
                                                    </div>
                                                    {transaction.fee && transaction.fee > 0 && (
                                                        <div className="text-xs text-gray-500 dark:text-gray-400">
                                                            Fee: {formatPrice(transaction.fee)}
                                                        </div>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-1">
                                                        <CoinIcon className="h-4 w-4 text-[#d4af37] dark:text-[#b8941f]" />
                                                        <span className="text-sm font-semibold text-[#d4af37] dark:text-[#b8941f]">
                                                            {transaction.coins.toLocaleString('id-ID')} NGD
                                                        </span>
                                                    </div>
                                                </TableCell>
                                                <TableCell>
                                                    {statusConfig ? (
                                                        <span className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${statusConfig.bgColor} ${statusConfig.color}`}>
                                                            {statusConfig.label}
                                                        </span>
                                                    ) : (
                                                        <span className="inline-flex rounded-full bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-800 dark:bg-gray-800 dark:text-gray-300">
                                                            N/A
                                                        </span>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <div className="text-sm text-gray-900 dark:text-white">
                                                        {formatDate(transaction.created_at)}
                                                    </div>
                                                    {transaction.paid_at && (
                                                        <div className="text-xs text-gray-500 dark:text-gray-400">
                                                            Paid: {formatDate(transaction.paid_at)}
                                                        </div>
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        );
                                    })
                                )}
                            </TableBody>
                        </Table>
                    </div>
                </Card>
            </div>
        </AdminLayout>
    );
}

// Icons
function CurrencyDollarIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
        </svg>
    );
}

function BanknotesIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M2.25 18.75a60.07 60.07 0 0115.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 013 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 00-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 01-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 003 15h-.75M15 10.5a3 3 0 11-6 0 3 3 0 016 0zm3 0a3 3 0 11-6 0 3 3 0 016 0z"
            />
        </svg>
    );
}

function CoinIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
        </svg>
    );
}

function TicketIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M16.5 6v.75m0 3v.75m0 3v.75m0 3V18m-9-5.25h5.25M7.5 15h3M3.375 5.25c-.621 0-1.125.504-1.125 1.125v3.026a2.999 2.999 0 010 5.198v3.026c0 .621.504 1.125 1.125 1.125h17.25c.621 0 1.125-.504 1.125-1.125v-3.026a2.999 2.999 0 010-5.198V6.375c0-.621.504-1.125 1.125-1.125H3.375z"
            />
        </svg>
    );
}

