import { DataTable } from '@/components/datatable';
import { FilterConfig } from '@/components/datatable-toolbar';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import AppLayout from '@/layouts/app-layout';
import { fetchDatatable } from '@/lib/datatable-fetch';
import { type PaginatedData } from '@/types';
import { Head, router, usePage } from '@inertiajs/react';
import { ColumnDef } from '@tanstack/react-table';
import {
    BadgeDollarSign,
    CalendarDays,
    CreditCard,
    Eye,
    MoreHorizontal,
    TrendingDown,
    Wallet,
} from 'lucide-react';
import StatisticCardLarge from '@/components/dashboard/StatisticCardLarge';
import { ReactNode, useEffect, useState } from 'react';

declare const route: (...args: any[]) => string;

interface SummaryItem {
    title: string;
    value: number | string;
    is_currency?: boolean;
    subtitle?: string;
    subtitle_color?: string;
}

interface CreditNoteData {
    id: number;
    uid: string;
    credit_note_number: string;
    customer_id?: number;
    customer_name?: string;
    type: string;
    type_label: string;
    amount: number;
    used_amount: number;
    balance: number;
    status: string;
    status_label: string;
    expire_at?: string | null;
    created_at: string;
}

type CreditNotesIndexData = PaginatedData<CreditNoteData> & {
    summary?: SummaryItem[];
    statuses?: { value: string; label: string }[];
    types?: { value: string; label: string }[];
};
type CreditNotesIndexProps = { creditNotesData: CreditNotesIndexData };

const statusColorMap: Record<string, string> = {
    open:      'bg-green-100 text-green-700 border-green-300',
    closed:    'bg-gray-100 text-gray-600 border-gray-300',
    cancelled: 'bg-red-100 text-red-700 border-red-300',
};

const typeColorMap: Record<string, string> = {
    money_back:          'bg-blue-100 text-blue-700 border-blue-200',
    voucher:             'bg-purple-100 text-purple-700 border-purple-200',
    exchange_difference: 'bg-amber-100 text-amber-700 border-amber-200',
};

function money(n: number) {
    return `৳ ${Number(n || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}`;
}

function Index() {
    const { creditNotesData } = usePage<CreditNotesIndexProps>().props;
    const [clientData, setClientData] = useState<any>(creditNotesData);
    const [summary, setSummary] = useState<SummaryItem[]>(creditNotesData?.summary ?? []);

    useEffect(() => {
        setClientData(creditNotesData);
        setSummary(creditNotesData?.summary ?? []);
    }, [creditNotesData]);

    const tableFilters: FilterConfig[] = [
        {
            type: 'searchable-multiselect',
            label: 'Status',
            name: 'status',
            value: clientData?.queryParams?.status || '',
            options: clientData?.statuses ?? [],
        },
        {
            type: 'searchable-multiselect',
            label: 'Type',
            name: 'type',
            value: clientData?.queryParams?.type || '',
            options: clientData?.types ?? [],
        },
        {
            type: 'date-range',
            label: 'Created Date',
            name: 'created_at',
            value: '',
        },
    ];

    const navigateNotes = async (params: Record<string, any>) => {
        const url  = route('credit-notes.index');
        const json = await fetchDatatable<CreditNoteData>(url, params);

        setClientData((prev: any) => ({
            ...prev,
            data:        json?.data,
            meta:        json?.meta,
            queryParams: params,
            statuses:    (json as any)?.statuses ?? prev.statuses,
            types:       (json as any)?.types    ?? prev.types,
            links: {
                prev: json?.meta?.current_page > 1                             ? '' : null,
                next: json?.meta?.current_page < json?.meta?.last_page ? '' : null,
            },
        }));

        if ((json as any)?.summary) {
            setSummary((json as any).summary as SummaryItem[]);
        }
    };

    const dataColumns: (ColumnDef<CreditNoteData> & { enableSorting?: boolean })[] = [
        {
            accessorKey: 'credit_note_number',
            header: 'Credit Note #',
            enableSorting: true,
            cell: ({ row }) => (
                <button
                    type="button"
                    onClick={() => router.visit(route('credit-notes.show', row.original.uid))}
                    className="font-medium text-blue-600 hover:underline"
                >
                    {row.original.credit_note_number}
                </button>
            ),
        },
        {
            accessorKey: 'customer_name',
            header: 'Customer',
            enableSorting: false,
            cell: ({ row }) => (
                <span className="font-medium text-gray-800">{row.original.customer_name || '—'}</span>
            ),
        },
        {
            accessorKey: 'type',
            header: 'Type',
            enableSorting: false,
            cell: ({ row }) => {
                const cls = typeColorMap[row.original.type] ?? 'bg-gray-100 text-gray-700 border-gray-200';
                return (
                    <span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-medium ${cls}`}>
                        {row.original.type_label}
                    </span>
                );
            },
        },
        {
            accessorKey: 'amount',
            header: 'Issued Amount',
            enableSorting: true,
            cell: ({ row }) => (
                <span className="font-semibold text-gray-800">{money(row.original.amount)}</span>
            ),
        },
        {
            accessorKey: 'used_amount',
            header: 'Used',
            enableSorting: false,
            cell: ({ row }) => (
                <span className="text-gray-500">{money(row.original.used_amount)}</span>
            ),
        },
        {
            accessorKey: 'balance',
            header: 'Balance',
            enableSorting: true,
            cell: ({ row }) => (
                <span className={`font-semibold ${row.original.balance > 0 ? 'text-green-700' : 'text-gray-400'}`}>
                    {money(row.original.balance)}
                </span>
            ),
        },
        {
            accessorKey: 'status',
            header: 'Status',
            enableSorting: false,
            cell: ({ row }) => {
                const cls = statusColorMap[row.original.status] ?? 'bg-gray-100 text-gray-700 border-gray-300';
                return (
                    <span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-medium ${cls}`}>
                        {row.original.status_label}
                    </span>
                );
            },
        },
        {
            accessorKey: 'expire_at',
            header: 'Expires',
            enableSorting: false,
            cell: ({ row }) => (
                <span className="text-sm text-gray-500">
                    {row.original.expire_at
                        ? new Date(row.original.expire_at).toLocaleDateString()
                        : <span className="text-gray-400">No expiry</span>}
                </span>
            ),
        },
        {
            accessorKey: 'created_at',
            header: 'Created',
            enableSorting: true,
            cell: ({ row }) => (
                <span className="text-sm text-gray-600">
                    {row.original.created_at ? new Date(row.original.created_at).toLocaleDateString() : '—'}
                </span>
            ),
        },
        {
            id: 'actions',
            header: 'Actions',
            cell: ({ row }) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8 p-0">
                            <span className="sr-only">Open menu</span>
                            <MoreHorizontal className="h-4 w-4" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="w-40">
                        <DropdownMenuItem
                            className="flex items-center"
                            onClick={() => router.visit(route('credit-notes.show', row.original.uid))}
                        >
                            <Eye className="mr-2 h-4 w-4" />
                            View Details
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
        },
    ];

    const statCardMeta = [
        { icon: BadgeDollarSign, iconBg: 'bg-blue-100',   iconColor: 'text-blue-600'   },
        { icon: TrendingDown,    iconBg: 'bg-orange-100', iconColor: 'text-orange-600' },
        { icon: Wallet,          iconBg: 'bg-green-100',  iconColor: 'text-green-600'  },
        { icon: CreditCard,      iconBg: 'bg-purple-100', iconColor: 'text-purple-600' },
    ];

    return (
        <>
            <Head title="Credit Notes" />
            <div className="no-scrollbar rounded-xl bg-gray-100/55 p-2 sm:p-4">
                <div className="mb-6 flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
                    <div className="grid grid-cols-1 gap-1">
                        <h2 className="text-xl font-bold sm:text-2xl">Credit Notes</h2>
                        <div className="flex items-center text-sm text-gray-600">
                            <span>Sales</span>
                            <span className="mx-2">›</span>
                            <span>Credit Notes</span>
                        </div>
                    </div>
                </div>

                {summary.length > 0 && (
                    <div className="mb-4 grid grid-cols-2 gap-4 lg:grid-cols-4">
                        {summary.map((s, idx) => {
                            const meta      = statCardMeta[idx] ?? statCardMeta[0];
                            const num       = Number(s.value ?? 0);
                            const formatted = Number.isFinite(num) ? num.toLocaleString('en-IN') : String(s.value ?? 0);
                            const value     = s.is_currency ? `৳ ${formatted}` : formatted;
                            return (
                                <StatisticCardLarge
                                    key={idx}
                                    title={s.title}
                                    value={value}
                                    change={s.subtitle ?? ''}
                                    changeType={s.subtitle_color ?? 'gray'}
                                    icon={meta.icon}
                                    iconBg={meta.iconBg}
                                    iconColor={meta.iconColor}
                                />
                            );
                        })}
                    </div>
                )}

                <div className="w-full">
                    {clientData ? (
                        <DataTable
                            columns={dataColumns}
                            data={clientData?.data || []}
                            paginatedData={clientData}
                            tableKey="credit-notes-table"
                            filters={tableFilters}
                            enableRowClick={false}
                            fullHeight={false}
                            onNavigate={async (params: Record<string, any>) => {
                                await navigateNotes(params);
                            }}
                        />
                    ) : (
                        <div className="py-8 text-center">
                            <p className="text-gray-500">Loading credit notes...</p>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

Index.layout = (page: ReactNode) => (
    <AppLayout
        title="Credit Notes"
        breadcrumbs={[
            { title: 'Home',         href: '/' },
            { title: 'Sales',        href: '#' },
            { title: 'Credit Notes', href: '#' },
        ]}
    >
        {page}
    </AppLayout>
);

export default Index;
