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, makePostRequest} from '@/lib/request';
import {notify} from '@/lib/notify';
import {useCurrencyFormatter} from '@/lib/currency';

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

function daysPastDue(value: any): number {
    if (!value) return 0;
    const due = new Date(value);
    const today = new Date();
    due.setHours(0, 0, 0, 0);
    today.setHours(0, 0, 0, 0);
    return Math.max(0, Math.floor((today.getTime() - due.getTime()) / 86400000));
}

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

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

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

    useEffect(() => {
        const t = setTimeout(() => { setPage(1); fetchInvoices(1, query); }, 350);
        return () => clearTimeout(t);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [query]);

    async function fetchInvoices(p = page, q = query) {
        setLoading(true);
        try {
            const params = new URLSearchParams({page: String(p)});
            if (q.trim()) params.append('search', q.trim());
            const res = await makeGetRequest(`/api/invoices/overdue/list?${params}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? payload ?? [];
            setInvoices(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 overdue invoices');
        } finally {
            setLoading(false);
        }
    }

    const summary = useMemo(() => ({
        outstanding: invoices.reduce((sum, invoice) => sum + Number(invoice.balance_due ?? 0), 0),
        count: meta?.total ?? invoices.length,
        oldest: invoices.reduce((max, invoice) => Math.max(max, daysPastDue(invoice.due_date)), 0),
    }), [invoices, meta]);

    const sendReminder = async (invoice: any) => {
        if (!confirm(`Send payment reminder for ${invoice.invoice_number}?`)) return;
        try {
            await makePostRequest(`/api/invoices/${invoice.id}/reminder`, {}, {token});
            notify.toastSuccessMessage('Reminder sent');
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to send reminder');
        }
    };

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

    return (
        <MainLayout>
            <AppPageHeader title="Overdue Invoices" subtitle="Billing" />

            <div className="grid grid-cols-12 gap-6 mb-6">
                <div className="col-span-12 sm:col-span-4"><div className="box"><div className="box-body"><p className="text-sm text-gray-500 mb-1">Overdue invoices</p><p className="text-2xl font-semibold">{summary.count}</p></div></div></div>
                <div className="col-span-12 sm:col-span-4"><div className="box"><div className="box-body"><p className="text-sm text-gray-500 mb-1">Outstanding</p><p className="text-2xl font-semibold text-danger">{money(summary.outstanding)}</p></div></div></div>
                <div className="col-span-12 sm:col-span-4"><div className="box"><div className="box-body"><p className="text-sm text-gray-500 mb-1">Oldest age</p><p className="text-2xl font-semibold">{summary.oldest} days</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 overdue invoices" value={query} onChange={e => setQuery(e.target.value)} /></div>
                    <Link href="/invoices" className="ti-btn ti-btn-soft-secondary py-2 px-3">All Invoices</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>Invoice</th><th>Client</th><th>Matter</th><th>Due</th><th>Days overdue</th><th>Total</th><th>Paid</th><th>Balance</th><th className="!text-end">Action</th></tr></thead><tbody>
                    {loading ? <tr><td colSpan={9} className="text-center py-8">Loading...</td></tr> : invoices.length === 0 ? <tr><td colSpan={9} className="text-center py-8">No overdue invoices found.</td></tr> : invoices.map(invoice => <tr key={invoice.id}><td className="font-semibold text-indigo-600">{invoice.invoice_number}</td><td>{invoice.client?.name ?? '-'}</td><td>{invoice.matter?.reference_number ?? '-'}</td><td>{dateLabel(invoice.due_date)}</td><td><span className="text-danger font-medium">{daysPastDue(invoice.due_date)}</span></td><td>{money(invoice.total)}</td><td>{money(invoice.amount_paid)}</td><td>{money(invoice.balance_due)}</td><td className="text-end"><button type="button" className="w-8 h-8 ti-btn rounded-full p-0 ti-btn-soft-warning" title="Send reminder" onClick={() => sendReminder(invoice)}><i className="ti ti-bell"></i></button></td></tr>)}
                </tbody></table></div>
                <div className="flex items-center justify-between mt-4"><div className="text-sm text-gray-600">showing {invoices.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>
    );
}
