import { Head, usePage } from '@inertiajs/react';
import AppLayout from '@/layouts/app-layout';
import IndexPageLayout from '@/components/core/IndexPageLayout';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { TablePagination } from '@/components/core/TablePagination';
import { Badge } from '@/components/ui/badge';
import { CirclePlus } from 'lucide-react';
import LinkButton from '@/components/core/LinkButton';
import { PaginationLink } from '@/types/dashboard';
import { ExchangeRateType } from '@/types/dashboard/currency';
import ExchangeRateMaker from './ExchangeRateMaker';
import { useState } from 'react';
import { SharedData } from '@/types';
import { DeleteAlertButton } from '@/components/core/DeleteAlertButton';

const breadcrumbs = [
    {
        title: 'Currency Settings',
        href: '/dashboard/currency-settings',
    },
    {
        title: 'Exchange Rates',
        href: '/dashboard/exchange-rates',
    },
];


interface ExchangeRatesPageProps {
    exchange_rates: {
        data: ExchangeRateType[];
        links: PaginationLink[];
        path: string;
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    },
    currency_settings: Record<string, string>
}

export default function Index({ exchange_rates, currency_settings }: ExchangeRatesPageProps) {

    const { auth } = usePage<SharedData>().props;

    const [open, setOpen] = useState(false)

    const { data, links, current_page, last_page, per_page, total, path } = exchange_rates;
    const meta = { current_page, last_page, per_page, total, path };


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

            <IndexPageLayout title="Exchange Rates" path="/dashboard/exchange-rates" headerButtons={<ExchangeRateMaker rate={null} systemCurrency={currency_settings?.system_currency ?? ''} currencyType={JSON.parse(currency_settings?.website_currency_types || '[]')} open={open} setOpen={setOpen} email={auth.user.email} />}>
                <Card className='py-4 rounded-sm shadow-none gap-2'>
                    <CardContent className='px-4'>

                        {data.length === 0 ? (
                            <div className="flex flex-col items-center justify-center py-16 text-center space-y-4">
                                <h3 className="text-lg font-semibold">No Exchange Rates Found</h3>
                                <p className="text-sm text-muted-foreground">
                                    Add exchange rates to start currency conversions.
                                </p>

                                <LinkButton
                                    className='bg-primary text-white'
                                    href='/dashboard/exchange-rates/create'
                                >
                                    <CirclePlus className="h-4 w-4" />
                                    Add Rate
                                </LinkButton>
                            </div>
                        ) : (
                            <>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>#</TableHead>
                                            <TableHead>System Currency</TableHead>
                                            <TableHead>Rates</TableHead>
                                            <TableHead>Recorderd At</TableHead>
                                            <TableHead>Last Updated At</TableHead>
                                            <TableHead>Updated By</TableHead>
                                            <TableHead className="text-right">Action</TableHead>
                                        </TableRow>
                                    </TableHeader>

                                    <TableBody>
                                        {data.map((item) => {

                                            // const rates = JSON.parse(item.rates)

                                            return <TableRow key={item.id}>
                                                <TableCell>{item.id}</TableCell>
                                                <TableCell>{item.base_currency}</TableCell>
                                                <TableCell>
                                                    <div className="flex flex-wrap gap-2">
                                                        {Object.entries(item.rates).map(([code, value]) => (
                                                            <div
                                                                key={code}
                                                                className="px-2 py-1 border rounded text-xs bg-muted"
                                                            >
                                                                <span className="font-medium">{code}</span>: {String(value)}
                                                            </div>
                                                        ))}
                                                    </div>
                                                </TableCell>
                                                <TableCell className='truncate max-w-34'>{new Date(item.recorded_at).toLocaleString()}</TableCell>
                                                <TableCell className='truncate max-w-34'>{item.last_updated_at ? new Date(item.last_updated_at).toLocaleString() : '-'}</TableCell>
                                                <TableCell ><Badge variant={item.updated_by === 'system' ? 'outline' : 'default'}>{item.updated_by}</Badge></TableCell>
                                                <TableCell className=" flex gap-2 justify-end items-center">
                                                    <DeleteAlertButton deleteId={item.id} model='exchange-rates' title='Exchange Rate' />
                                                </TableCell>
                                            </TableRow>
                                        })}
                                    </TableBody>
                                </Table>

                                {/* 🔁 Pagination (only table updates) */}
                                <TablePagination links={links} meta={meta} />
                            </>
                        )}
                    </CardContent>
                </Card>
            </IndexPageLayout>
        </AppLayout>
    );
}