import React, {useEffect, useMemo, useState} from 'react';
import {Link, usePage} from '@inertiajs/react';
import MainLayout from '@/layouts/MainLayout';
import AppPageHeader from '@/components/AppPageHeader';
import {makeGetRequest} from '@/lib/request';
import {notify} from '@/lib/notify';
import {useCurrencyFormatter} from '@/lib/currency';

function dateLabel(value: any): string {
    return value ? new Date(value).toLocaleDateString() : '-';
}

export default function Allocations(): JSX.Element {
    const {auth} = usePage<{ auth: { user: any } }>().props;
    const token = auth?.user?.token ?? auth?.user?.api_token ?? undefined;
    const money = useCurrencyFormatter(token);

    const [allocations, setAllocations] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [query, setQuery] = useState('');
    const [meta, setMeta] = useState<any>(null);

    useEffect(() => {
        fetchAllocations();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [page, token]);

    async function fetchAllocations(p = page) {
        setLoading(true);
        try {
            const params = new URLSearchParams({page: String(p)});
            const res = await makeGetRequest(`/api/payments/allocations?${params}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? payload ?? [];
            setAllocations(Array.isArray(list) ? list : []);
            setMeta(payload?.meta ?? (payload?.data ? {current_page: payload.current_page ?? p, last_page: payload.last_page ?? 1, total: payload.total ?? 0} : null));
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to load allocations');
        } finally {
            setLoading(false);
        }
    }

    const visibleAllocations = useMemo(() => {
        const needle = query.trim().toLowerCase();
        if (!needle) return allocations;
        return allocations.filter((allocation: any) => {
            const client = allocation.payment?.client?.name ?? allocation.invoice?.client?.name ?? '';
            const invoice = allocation.invoice?.invoice_number ?? '';
            const reference = allocation.payment?.reference_number ?? '';
            return `${client} ${invoice} ${reference}`.toLowerCase().includes(needle);
        });
    }, [allocations, query]);

    const summary = useMemo(() => ({
        total: visibleAllocations.reduce((sum, allocation) => sum + Number(allocation.amount ?? 0), 0),
        count: visibleAllocations.length,
    }), [visibleAllocations]);

    const gotoPage = (p: number) => {
        if (p < 1 || p > (meta?.last_page ?? p)) return;
        setPage(p);
    };

    return (
        <MainLayout>
            <AppPageHeader title="Payment Allocations" subtitle="Billing" />

            <div className="grid grid-cols-12 gap-6 mb-6">
                <div className="col-span-12 sm:col-span-6"><div className="box"><div className="box-body"><p className="text-sm text-gray-500 mb-1">Allocations shown</p><p className="text-2xl font-semibold">{summary.count}</p></div></div></div>
                <div className="col-span-12 sm:col-span-6"><div className="box"><div className="box-body"><p className="text-sm text-gray-500 mb-1">Allocated amount</p><p className="text-2xl font-semibold text-success">{money(summary.total)}</p></div></div></div>
            </div>

            <div className="box"><div className="box-body">
                <div className="flex flex-wrap justify-between gap-4 mb-5">
                    <div className="relative sm:max-w-xs max-w-[220px]"><div className="absolute inset-y-0 end-0 flex items-center pointer-events-none pe-4"><i className="ti ti-search"></i></div><input type="text" className="p-2 pe-10 ti-form-input" placeholder="Search allocations" value={query} onChange={e => setQuery(e.target.value)} /></div>
                    <Link href="/payments" className="ti-btn ti-btn-soft-secondary py-2 px-3">Payments</Link>
                </div>

                <div className="rounded-sm overflow-auto todo-table w-full"><table className="ti-custom-table ti-custom-table-head whitespace-nowrap w-full"><thead className="bg-gray-100"><tr><th>Allocated</th><th>Payment Date</th><th>Client</th><th>Payment Reference</th><th>Invoice</th><th>Matter</th><th>Payment Amount</th><th>Allocation</th></tr></thead><tbody>
                    {loading ? <tr><td colSpan={8} className="text-center py-8">Loading...</td></tr> : visibleAllocations.length === 0 ? <tr><td colSpan={8} className="text-center py-8">No allocations found.</td></tr> : visibleAllocations.map(allocation => <tr key={allocation.id}><td>{dateLabel(allocation.created_at)}</td><td>{dateLabel(allocation.payment?.payment_date)}</td><td>{allocation.payment?.client?.name ?? allocation.invoice?.client?.name ?? '-'}</td><td>{allocation.payment?.reference_number ?? '-'}</td><td className="font-semibold text-indigo-600">{allocation.invoice?.invoice_number ?? '-'}</td><td>{allocation.invoice?.matter?.reference_number ?? '-'}</td><td>{money(allocation.payment?.amount)}</td><td className="font-semibold">{money(allocation.amount)}</td></tr>)}
                </tbody></table></div>

                <div className="flex items-center justify-between mt-4"><div className="text-sm text-gray-600">showing {visibleAllocations.length} of {meta?.total ?? 0} items</div><div className="flex items-center gap-2"><button type="button" disabled={(meta?.current_page ?? 1) <= 1} onClick={() => gotoPage((meta?.current_page ?? 1) - 1)} className="px-2 py-1 border rounded disabled:opacity-40">Prev</button>{Array.from({length: meta?.last_page ?? 1}).map((_, i) => <button key={i + 1} type="button" onClick={() => gotoPage(i + 1)} className={`px-2 py-1 border rounded ${i + 1 === (meta?.current_page ?? page) ? 'bg-indigo-600 text-white' : ''}`}>{i + 1}</button>)}<button type="button" disabled={(meta?.current_page ?? 1) >= (meta?.last_page ?? 1)} onClick={() => gotoPage((meta?.current_page ?? 1) + 1)} className="px-2 py-1 border rounded disabled:opacity-40">Next</button></div></div>
            </div></div>
        </MainLayout>
    );
}
