'use client';

import React, { useEffect, useState } from 'react';
import { App, Button, DatePicker, Drawer, Form, Input, InputNumber, Modal, Popconfirm, Select, Tag } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { DataTable, FilterTabsBar, PageHeader, type DataTableColumn } from '../platform/PlatformPrimitives';
import { accountsApi, type AccountOption } from '../../lib/accounts';
import { projectsApi, type ProjectRecord } from '../../lib/projects';
import { timesheetsApi, type TimeEntryRecord } from '../../lib/timesheets';
import { invoicesApi, type InvoiceRecord, type InvoiceStatus } from '../../lib/finance';
import { useCrmOptions } from '../../lib/options';
import { usePermissions } from '../../lib/usePermissions';

const PAYMENT_METHOD_LABEL: Record<string, string> = { BANK_TRANSFER: 'Bank Transfer (NEFT/RTGS)', UPI: 'UPI / QR Code', CARD: 'Credit / Debit Card', NET_BANKING: 'Net Banking', CHEQUE: 'Cheque', CASH: 'Cash' };

function formatINR(val: number): string {
  return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(val);
}

export function InvoicesView() {
  const { paymentMethods, gstRates } = useCrmOptions();
  const { message } = App.useApp();
  const { can } = usePermissions();
  const canCreate = can('invoices', 'create');
  const canEdit = can('invoices', 'update');
  const mayDelete = can('invoices', 'delete');

  const [activeTab, setActiveTab] = useState<'all' | 'unpaid' | 'overdue' | 'paid'>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(true);
  const [invoices, setInvoices] = useState<InvoiceRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [stats, setStats] = useState({
    outstanding: 0,
    overdue: 0,
    collected90d: 0,
    avgDaysToPay: 0,
    totalInvoices: 0,
  });

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [reload, setReload] = useState(0);

  // Modals & Drawers state
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [accounts, setAccounts] = useState<AccountOption[]>([]);
  const [submitting, setSubmitting] = useState(false);

  // Invoice line items for manual modal
  const [formItems, setFormItems] = useState<Array<{ productId?: string; name: string; description?: string; quantity: number; unitPrice: number; discountPercent: number; gstRate: number }>>([]);

  const [createForm] = Form.useForm();

  // Invoice from Timesheets Modal
  const [timesheetModalOpen, setTimesheetModalOpen] = useState(false);
  const [projects, setProjects] = useState<ProjectRecord[]>([]);
  const [selectedProjectId, setSelectedProjectId] = useState<string | undefined>(undefined);
  const [unInvoicedEntries, setUnInvoicedEntries] = useState<TimeEntryRecord[]>([]);
  const [selectedTimeEntryIds, setSelectedTimeEntryIds] = useState<string[]>([]);
  const [hourlyRate, setHourlyRate] = useState<number>(2500);
  const [timesheetDueDate, setTimesheetDueDate] = useState<dayjs.Dayjs | null>(dayjs().add(15, 'day'));
  const [generatingFromTimesheets, setGeneratingFromTimesheets] = useState(false);

  // Detail Drawer state
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedInvoice, setSelectedInvoice] = useState<InvoiceRecord | null>(null);

  // Record Payment Modal
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [paymentForm] = Form.useForm();
  const [recordingPayment, setRecordingPayment] = useState(false);

  // Load invoices list & KPIs
  useEffect(() => {
    let active = true;
    void (async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const statusFilter: InvoiceStatus | undefined = activeTab === 'overdue' ? 'OVERDUE' : activeTab === 'paid' ? 'PAID' : undefined;

        const res = await invoicesApi.list({
          status: statusFilter,
          search: searchQuery.trim() || undefined,
          page,
          limit: pageSize,
        });

        if (!active) return;
        let dataList = res.data || [];
        if (activeTab === 'unpaid') {
          dataList = dataList.filter((i) => ['SENT', 'OVERDUE', 'PARTIALLY_PAID'].includes(i.status));
        }

        setInvoices(dataList);
        setTotal(res.meta?.total ?? 0);
        if (res.stats) {
          setStats(res.stats);
        }
      } catch (err) {
        if (active) {
          message.error(err instanceof Error ? err.message : 'Failed to load invoices');
        }
      } finally {
        if (active) setLoading(false);
      }
    })();

    return () => {
      active = false;
    };
  }, [activeTab, searchQuery, page, pageSize, reload, message]);

  const handleOpenCreateModal = async () => {
    setCreateModalOpen(true);
    createForm.resetFields();
    createForm.setFieldsValue({
      dueDate: dayjs().add(15, 'day'),
    });
    setFormItems([{ name: '', quantity: 1, unitPrice: 0, discountPercent: 0, gstRate: 18 }]);

    try {
      const accRes = await accountsApi.options();
      setAccounts(accRes || []);
    } catch {
      // non-critical
    }
  };

  const handleAddBlankItem = () => {
    setFormItems((prev) => [...prev, { name: '', quantity: 1, unitPrice: 0, discountPercent: 0, gstRate: 18 }]);
  };

  const handleRemoveItem = (index: number) => {
    setFormItems((prev) => prev.filter((_, i) => i !== index));
  };

  const handleItemChange = (index: number, field: string, val: string | number) => {
    setFormItems((prev) => {
      const copy = [...prev];
      copy[index] = { ...copy[index], [field]: val };
      return copy;
    });
  };

  const liveTotals = formItems.reduce(
    (acc, it) => {
      const gross = it.quantity * it.unitPrice;
      const disc = gross * ((it.discountPercent || 0) / 100);
      const taxable = gross - disc;
      const tax = taxable * ((it.gstRate || 0) / 100);
      return {
        subtotal: acc.subtotal + gross,
        discount: acc.discount + disc,
        tax: acc.tax + tax,
        grand: acc.grand + taxable + tax,
      };
    },
    { subtotal: 0, discount: 0, tax: 0, grand: 0 },
  );

  const handleCreateSubmit = async () => {
    try {
      const values = await createForm.validateFields();
      if (formItems.length === 0) {
        message.error('Please add at least one line item to the invoice');
        return;
      }

      setSubmitting(true);
      await invoicesApi.create({
        accountId: values.accountId,
        dueDate: values.dueDate.toISOString(),
        notes: values.notes,
        terms: values.terms,
        items: formItems,
      });

      message.success('Invoice created successfully');
      setCreateModalOpen(false);
      setReload((r) => r + 1);
    } catch (err) {
      if (err instanceof Error && 'message' in err) {
        message.error(err.message);
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleOpenTimesheetModal = async () => {
    setTimesheetModalOpen(true);
    setSelectedProjectId(undefined);
    setUnInvoicedEntries([]);
    setSelectedTimeEntryIds([]);
    try {
      const projRes = await projectsApi.list({ limit: 100 });
      setProjects(projRes.data || []);
    } catch {
      // non-critical
    }
  };

  const handleSelectProjectForTimesheets = async (projId: string) => {
    setSelectedProjectId(projId);
    try {
      const res = await timesheetsApi.list({ projectId: projId, limit: 100 });
      // Only billable time entries that do not have an invoiceId attached
      const billable = (res.data || []).filter((te) => te.isBillable && !('invoiceId' in te && Boolean(te.invoiceId)));
      setUnInvoicedEntries(billable);
      setSelectedTimeEntryIds(billable.map((b) => b.id));
    } catch {
      message.error('Failed to load project timesheets');
    }
  };

  const handleCreateFromTimesheets = async () => {
    if (!selectedProjectId || selectedTimeEntryIds.length === 0 || !timesheetDueDate) {
      message.error('Please select billable timesheets and a due date');
      return;
    }

    setGeneratingFromTimesheets(true);
    try {
      const inv = await invoicesApi.createFromTimesheets({
        projectId: selectedProjectId,
        timeEntryIds: selectedTimeEntryIds,
        hourlyRate,
        dueDate: timesheetDueDate.toISOString(),
      });
      message.success(`Invoice ${inv.invoiceNumber} created from ${selectedTimeEntryIds.length} timesheets!`);
      setTimesheetModalOpen(false);
      setReload((r) => r + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to generate invoice from timesheets');
    } finally {
      setGeneratingFromTimesheets(false);
    }
  };

  const handleViewInvoice = async (inv: InvoiceRecord) => {
    try {
      const full = await invoicesApi.get(inv.id);
      setSelectedInvoice(full);
      setDrawerOpen(true);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to load invoice details');
    }
  };

  const handleOpenRecordPayment = (inv: InvoiceRecord) => {
    setSelectedInvoice(inv);
    paymentForm.resetFields();
    paymentForm.setFieldsValue({
      amount: Math.max(0, inv.totalAmount - inv.paidAmount),
      paymentMethod: 'BANK_TRANSFER',
      paidAt: dayjs(),
    });
    setPaymentModalOpen(true);
  };

  const handleRecordPaymentSubmit = async () => {
    if (!selectedInvoice) return;
    try {
      const values = await paymentForm.validateFields();
      setRecordingPayment(true);

      const updated = await invoicesApi.recordPayment(selectedInvoice.id, {
        amount: values.amount,
        paymentMethod: values.paymentMethod,
        transactionRef: values.transactionRef,
        paidAt: values.paidAt ? values.paidAt.toISOString() : undefined,
        notes: values.notes,
      });

      message.success(`Payment of ${formatINR(values.amount)} recorded!`);
      setSelectedInvoice(updated);
      setPaymentModalOpen(false);
      setReload((r) => r + 1);
    } catch (err) {
      if (err instanceof Error && 'message' in err) {
        message.error(err.message);
      }
    } finally {
      setRecordingPayment(false);
    }
  };

  const handleStatusChange = async (id: string, newStatus: InvoiceStatus) => {
    try {
      const updated = await invoicesApi.update(id, { status: newStatus });
      setSelectedInvoice(updated);
      message.success(`Invoice marked as ${newStatus}`);
      setReload((r) => r + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to update invoice');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await invoicesApi.delete(id);
      message.success('Invoice deleted successfully');
      setDrawerOpen(false);
      setReload((r) => r + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to delete invoice');
    }
  };

  const handleDownloadPDF = async (inv: InvoiceRecord) => {
    try {
      message.loading({ content: 'Generating PDF...', key: 'pdf-dl' });
      await invoicesApi.downloadPdf(inv.id, inv.invoiceNumber);
      message.success({ content: `Invoice ${inv.invoiceNumber} downloaded successfully`, key: 'pdf-dl' });
    } catch (err) {
      message.error({ content: err instanceof Error ? err.message : 'Failed to download PDF', key: 'pdf-dl' });
    }
  };

  const getStatusColor = (s: InvoiceStatus) => {
    switch (s) {
      case 'PAID':
        return 'green';
      case 'PARTIALLY_PAID':
        return 'orange';
      case 'SENT':
        return 'blue';
      case 'OVERDUE':
        return 'red';
      default:
        return 'default';
    }
  };

  const columns: DataTableColumn<InvoiceRecord>[] = [
    {
      key: 'invoiceNumber',
      title: 'Invoice',
      render: (_val, r) => (
        <div className="cursor-pointer" onClick={() => handleViewInvoice(r)}>
          <div className="font-semibold text-[13.5px] text-[var(--tcx-text)] hover:text-[var(--tcx-primary)]">{r.invoiceNumber}</div>
          <div className="text-[12px] text-[var(--tcx-muted)]">{r.account?.name || 'No client'}</div>
        </div>
      ),
    },
    {
      key: 'status',
      title: 'Status',
      render: (_val, r) => <Tag color={getStatusColor(r.status)}>{r.status}</Tag>,
    },
    {
      key: 'totalAmount',
      title: 'Total Amount',
      align: 'right',
      render: (_val, r) => <span className="font-bold text-[13.5px] text-[var(--tcx-text)]">{formatINR(r.totalAmount)}</span>,
    },
    {
      key: 'balanceDue',
      title: 'Balance Due',
      align: 'right',
      render: (_val, r) => {
        const bal = Math.max(0, r.totalAmount - r.paidAmount);
        return bal > 0 ? <span className={`font-semibold text-[13.5px] ${r.status === 'OVERDUE' ? 'text-rose-600' : 'text-amber-600'}`}>{formatINR(bal)}</span> : <span className="text-[12.5px] text-[var(--tcx-muted)]">—</span>;
      },
    },
    {
      key: 'dueDate',
      title: 'Due Date',
      render: (_val, r) => {
        const isOverdue = dayjs().isAfter(dayjs(r.dueDate)) && r.status !== 'PAID' && r.status !== 'VOID';
        return <span className={`text-[12.5px] ${isOverdue ? 'font-semibold text-rose-600' : 'text-[var(--tcx-muted)]'}`}>{dayjs(r.dueDate).format('DD MMM YYYY')}</span>;
      },
    },
    {
      key: 'actions',
      title: '',
      align: 'right',
      render: (_val, r) => {
        const bal = Math.max(0, r.totalAmount - r.paidAmount);
        return (
          <div className="flex items-center justify-end gap-1.5" onClick={(e) => e.stopPropagation()}>
            {bal > 0 && r.status !== 'VOID' && r.status !== 'DRAFT' && canEdit && (
              <Button size="small" type="primary" onClick={() => handleOpenRecordPayment(r)}>
                Record Payment
              </Button>
            )}
            <Button size="small" type="text" icon={<Icon name="download" size={14} />} onClick={() => handleDownloadPDF(r)} />
            <Button size="small" type="text" icon={<Icon name="eye" size={14} />} onClick={() => handleViewInvoice(r)} />
          </div>
        );
      },
    },
  ];

  return (
    <div className="tcx-page">
      <PageHeader
        eyebrow="Finance"
        title="Invoices & Payments"
        subtitle="Manage client invoices, GST compliance billing, and payment collections"
        actions={
          <div className="flex flex-wrap items-center gap-2">
            {canCreate && (
              <Button icon={<Icon name="clock" size={14} />} onClick={handleOpenTimesheetModal}>
                Invoice from Timesheets
              </Button>
            )}
            {canCreate && (
              <Button type="primary" icon={<Icon name="plus" size={14} />} onClick={handleOpenCreateModal}>
                New Invoice
              </Button>
            )}
          </div>
        }
      />

      {/* Financial KPI Stats Strip */}
      <div className="mb-4 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <div className="tcx-surface-card p-4">
          <div className="text-[12px] font-medium text-[var(--tcx-muted)]">Outstanding Balance</div>
          <div className="mt-1 text-[22px] font-bold text-[var(--tcx-text)]">{formatINR(stats.outstanding)}</div>
        </div>
        <div className="tcx-surface-card p-4">
          <div className="text-[12px] font-medium text-rose-600">Overdue Invoices</div>
          <div className="mt-1 text-[22px] font-bold text-rose-600">{formatINR(stats.overdue)}</div>
        </div>
        <div className="tcx-surface-card p-4">
          <div className="text-[12px] font-medium text-emerald-600">Collected (90 Days)</div>
          <div className="mt-1 text-[22px] font-bold text-emerald-600">{formatINR(stats.collected90d)}</div>
        </div>
        <div className="tcx-surface-card p-4">
          <div className="text-[12px] font-medium text-[var(--tcx-muted)]">Average Days to Pay</div>
          <div className="mt-1 text-[22px] font-bold text-[var(--tcx-text)]">{stats.avgDaysToPay} days</div>
        </div>
      </div>

      <div className="mb-4">
        <FilterTabsBar
          tabs={[
            { key: 'all', label: 'All Invoices', count: stats.totalInvoices },
            { key: 'unpaid', label: 'Unpaid' },
            { key: 'overdue', label: 'Overdue' },
            { key: 'paid', label: 'Paid' },
          ]}
          activeKey={activeTab}
          onChange={(k) => {
            setActiveTab(k as typeof activeTab);
            setPage(1);
          }}
        />
      </div>

      <div className="mb-4 flex items-center gap-3">
        <Input
          allowClear
          prefix={<Icon name="search" size={15} />}
          placeholder="Search invoice number, client account..."
          value={searchQuery}
          onChange={(e) => {
            setSearchQuery(e.target.value);
            setPage(1);
          }}
          className="w-full sm:!w-[320px]"
        />
      </div>

      <div className="tcx-surface-card overflow-hidden">
        <DataTable
          columns={columns}
          data={invoices}
          loading={loading}
          onRowClick={(r) => handleViewInvoice(r)}
          pagination={{
            page,
            pageSize,
            total,
            onPageChange: (p) => setPage(p),
            onPageSizeChange: (ps) => setPageSize(ps),
          }}
        />
      </div>

      {/* Invoice Detail Drawer */}
      <Drawer
        title={
          selectedInvoice ? (
            <div className="flex items-center gap-3">
              <div className="grid h-10 w-10 place-items-center rounded-lg bg-[var(--tcx-surface-2)] text-[var(--tcx-primary)]">
                <Icon name="receipt" size={20} />
              </div>
              <div>
                <div className="text-[16px] font-bold text-[var(--tcx-text)]">{selectedInvoice.invoiceNumber}</div>
                <div className="text-[12px] text-[var(--tcx-muted)]">
                  {selectedInvoice.account?.name} {selectedInvoice.project ? `· Project ${selectedInvoice.project.name}` : ''}
                </div>
              </div>
            </div>
          ) : (
            'Invoice Details'
          )
        }
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        size={620}
        extra={
          selectedInvoice && (
            <div className="flex items-center gap-2">
              <Button size="small" icon={<Icon name="download" size={14} />} onClick={() => handleDownloadPDF(selectedInvoice)}>
                PDF
              </Button>
              {selectedInvoice.status === 'DRAFT' && (
                <Button size="small" type="primary" icon={<Icon name="send" size={14} />} onClick={() => handleStatusChange(selectedInvoice.id, 'SENT')}>
                  Send Invoice
                </Button>
              )}
              {Math.max(0, selectedInvoice.totalAmount - selectedInvoice.paidAmount) > 0 && selectedInvoice.status !== 'VOID' && selectedInvoice.status !== 'DRAFT' && (
                <Button size="small" type="primary" onClick={() => handleOpenRecordPayment(selectedInvoice)}>
                  Record Payment
                </Button>
              )}
              {canEdit && selectedInvoice.status !== 'DRAFT' && selectedInvoice.status !== 'VOID' && selectedInvoice.paidAmount === 0 && (
                <Popconfirm title="Void this invoice?" description="A voided invoice keeps its number but can no longer be paid." okText="Void" cancelText="Cancel" okButtonProps={{ danger: true }} onConfirm={() => handleStatusChange(selectedInvoice.id, 'VOID')}>
                  <Button size="small" danger>
                    Void
                  </Button>
                </Popconfirm>
              )}
              {mayDelete && selectedInvoice.status === 'DRAFT' && (
                <Popconfirm title="Delete this draft invoice?" okText="Delete" cancelText="Cancel" okButtonProps={{ danger: true }} onConfirm={() => handleDelete(selectedInvoice.id)}>
                  <Button size="small" danger icon={<Icon name="trash" size={14} />} />
                </Popconfirm>
              )}
            </div>
          )
        }
      >
        {selectedInvoice && (
          <div className="space-y-6">
            {/* Balance Due Card with Progress */}
            <div className="rounded-xl border border-[var(--tcx-border)] bg-[var(--tcx-surface-2)] p-4">
              <div className="flex items-start justify-between">
                <div>
                  <div className="text-[12px] font-bold uppercase tracking-wider text-[var(--tcx-muted)]">Balance Due</div>
                  <div className="text-[28px] font-bold text-[var(--tcx-text)]">{formatINR(Math.max(0, selectedInvoice.totalAmount - selectedInvoice.paidAmount))}</div>
                  <div className="text-[12px] text-[var(--tcx-muted)]">Payment due on {dayjs(selectedInvoice.dueDate).format('DD MMM YYYY')}</div>
                </div>
                <Tag color={getStatusColor(selectedInvoice.status)} className="px-3 py-1 text-[13px] font-semibold">
                  {selectedInvoice.status}
                </Tag>
              </div>

              {/* Payment Progress Bar */}
              <div className="mt-4">
                <div className="flex justify-between text-[11.5px] text-[var(--tcx-muted)] mb-1">
                  <span>Paid: {formatINR(selectedInvoice.paidAmount)}</span>
                  <span>Total: {formatINR(selectedInvoice.totalAmount)}</span>
                </div>
                <div className="h-2 w-full overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
                  <div className="h-full bg-emerald-500 transition-all duration-300" style={{ width: `${Math.min(100, (selectedInvoice.paidAmount / (selectedInvoice.totalAmount || 1)) * 100)}%` }} />
                </div>
              </div>
            </div>

            {/* Line items table */}
            <div>
              <div className="mb-2 font-semibold text-[13.5px] text-[var(--tcx-text)]">Invoiced Items</div>
              <table className="w-full text-left text-[12.5px]">
                <thead>
                  <tr className="border-b border-[var(--tcx-border)] text-[11px] font-bold uppercase tracking-wider text-[var(--tcx-muted)]">
                    <th className="py-2">Item</th>
                    <th className="py-2 text-right">Qty</th>
                    <th className="py-2 text-right">Rate</th>
                    <th className="py-2 text-right">Disc.</th>
                    <th className="py-2 text-right">Total</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[var(--tcx-border)]">
                  {(selectedInvoice.items || []).map((it) => (
                    <tr key={it.id}>
                      <td className="py-2.5">
                        <div className="font-semibold text-[var(--tcx-text)]">{it.name}</div>
                        {it.description && <div className="text-[11.5px] text-[var(--tcx-muted)]">{it.description}</div>}
                      </td>
                      <td className="py-2.5 text-right font-medium text-[var(--tcx-text)]">{it.quantity}</td>
                      <td className="py-2.5 text-right text-[var(--tcx-muted)]">{formatINR(it.unitPrice)}</td>
                      <td className="py-2.5 text-right text-[var(--tcx-muted)]">{it.discountPercent}%</td>
                      <td className="py-2.5 text-right font-bold text-[var(--tcx-text)]">{formatINR(it.lineTotal)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>

              <div className="mt-3 flex flex-col items-end border-t border-[var(--tcx-border)] pt-2 text-[12.5px]">
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>Subtotal:</span>
                  <span>{formatINR(selectedInvoice.subtotal)}</span>
                </div>
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>Discount:</span>
                  <span>− {formatINR(selectedInvoice.discountTotal)}</span>
                </div>
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>GST (18%):</span>
                  <span>{formatINR(selectedInvoice.taxTotal)}</span>
                </div>
                <div className="mt-1 flex w-52 justify-between border-t border-[var(--tcx-border)] pt-1 text-[14px] font-bold text-[var(--tcx-text)]">
                  <span>Total Amount:</span>
                  <span className="text-[var(--tcx-primary)]">{formatINR(selectedInvoice.totalAmount)}</span>
                </div>
              </div>
            </div>

            {/* Payment history list */}
            <div>
              <div className="mb-2 flex items-center justify-between">
                <span className="font-semibold text-[13.5px] text-[var(--tcx-text)]">Payment History ({(selectedInvoice.payments || []).length})</span>
                {Math.max(0, selectedInvoice.totalAmount - selectedInvoice.paidAmount) > 0 && (
                  <Button size="small" onClick={() => handleOpenRecordPayment(selectedInvoice)}>
                    + Record Payment
                  </Button>
                )}
              </div>

              {(selectedInvoice.payments || []).length === 0 ? (
                <div className="rounded-lg border border-dashed border-[var(--tcx-border)] p-4 text-center text-[12.5px] text-[var(--tcx-muted)]">No payments recorded yet for this invoice.</div>
              ) : (
                <div className="space-y-2">
                  {selectedInvoice.payments!.map((p) => (
                    <div key={p.id} className="flex items-center justify-between rounded-lg border border-[var(--tcx-border)] bg-[var(--tcx-surface)] p-3">
                      <div>
                        <div className="font-semibold text-[13.5px] text-emerald-600">{formatINR(p.amount)}</div>
                        <div className="text-[12px] text-[var(--tcx-muted)]">
                          {p.paymentMethod} {p.transactionRef ? `· Ref: ${p.transactionRef}` : ''}
                        </div>
                      </div>
                      <div className="text-right">
                        <Tag color="green">Captured</Tag>
                        <div className="mt-0.5 text-[11px] text-[var(--tcx-muted)]">{dayjs(p.paidAt).format('DD MMM YYYY')}</div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </Drawer>

      {/* Record Payment Modal */}
      <Modal title={`Record Payment for ${selectedInvoice?.invoiceNumber}`} open={paymentModalOpen} onOk={handleRecordPaymentSubmit} confirmLoading={recordingPayment} onCancel={() => setPaymentModalOpen(false)} okText="Capture Payment">
        <Form form={paymentForm} layout="vertical" className="mt-4">
          <Form.Item name="amount" label="Payment Amount (INR)" rules={[{ required: true, message: 'Please enter amount' }]}>
            <InputNumber className="w-full" min={0.01} prefix="₹" />
          </Form.Item>

          <div className="grid grid-cols-2 gap-3">
            <Form.Item name="paymentMethod" label="Payment Method" rules={[{ required: true }]}>
              <Select options={paymentMethods.map((m) => ({ value: m, label: PAYMENT_METHOD_LABEL[m] ?? m }))} />
            </Form.Item>
            <Form.Item name="paidAt" label="Payment Date">
              <DatePicker className="w-full" format="DD MMM YYYY" />
            </Form.Item>
          </div>

          <Form.Item name="transactionRef" label="UTR / Reference Number">
            <Input placeholder="Enter transaction reference or cheque number" />
          </Form.Item>

          <Form.Item name="notes" label="Notes">
            <Input.TextArea rows={2} placeholder="Optional payment receipt note" />
          </Form.Item>
        </Form>
      </Modal>

      {/* Invoice from Timesheets Modal */}
      <Modal title="Invoice from Delivery Timesheets" open={timesheetModalOpen} onOk={handleCreateFromTimesheets} confirmLoading={generatingFromTimesheets} onCancel={() => setTimesheetModalOpen(false)} okText="Generate Invoice" width={680}>
        <div className="space-y-4">
          <p className="text-[13px] text-[var(--tcx-muted)]">Select a delivery project to invoice all logged, un-invoiced billable hours into a customer invoice.</p>

          <div>
            <label className="mb-1 block text-[13px] font-semibold text-[var(--tcx-text)]">Select Delivery Project</label>
            <Select className="w-full" placeholder="Choose active project" value={selectedProjectId} onChange={handleSelectProjectForTimesheets} options={projects.map((p) => ({ value: p.id, label: `${p.name} (${p.projectNumber})` }))} showSearch filterOption={(input, opt) => (opt?.label as string).toLowerCase().includes(input.toLowerCase())} />
          </div>

          {selectedProjectId && (
            <>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="mb-1 block text-[13px] font-semibold text-[var(--tcx-text)]">Billable Hourly Rate (₹)</label>
                  <InputNumber className="w-full" min={0} value={hourlyRate} onChange={(v) => setHourlyRate(v || 0)} prefix="₹" />
                </div>
                <div>
                  <label className="mb-1 block text-[13px] font-semibold text-[var(--tcx-text)]">Invoice Due Date</label>
                  <DatePicker className="w-full" value={timesheetDueDate} onChange={(d) => setTimesheetDueDate(d)} format="DD MMM YYYY" />
                </div>
              </div>

              <div>
                <div className="mb-2 font-semibold text-[13px] text-[var(--tcx-text)]">Un-invoiced Billable Hours ({unInvoicedEntries.length} entries)</div>
                {unInvoicedEntries.length === 0 ? (
                  <div className="rounded-lg border border-dashed border-[var(--tcx-border)] p-4 text-center text-[12.5px] text-[var(--tcx-muted)]">No un-invoiced billable timesheets found for this project.</div>
                ) : (
                  <div className="max-h-60 overflow-y-auto rounded-lg border border-[var(--tcx-border)] divide-y divide-[var(--tcx-border)]">
                    {unInvoicedEntries.map((te) => (
                      <div key={te.id} className="flex items-center justify-between p-2.5 text-[12.5px]">
                        <div>
                          <div className="font-semibold text-[var(--tcx-text)]">{te.task?.title || 'Engineering Task'}</div>
                          <div className="text-[11.5px] text-[var(--tcx-muted)]">
                            {te.user?.name} · {dayjs(te.date).format('DD MMM YYYY')} {te.note ? `· "${te.note}"` : ''}
                          </div>
                        </div>
                        <div className="text-right font-bold text-[var(--tcx-text)]">{te.hours} hrs</div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </Modal>

      {/* Create Invoice Modal */}
      <Modal title="Create New Invoice" open={createModalOpen} onOk={handleCreateSubmit} confirmLoading={submitting} onCancel={() => setCreateModalOpen(false)} okText="Create Invoice" width={760}>
        <Form form={createForm} layout="vertical">
          <div className="grid grid-cols-2 gap-4">
            <Form.Item name="accountId" label="Client Account" rules={[{ required: true, message: 'Account is required' }]}>
              <Select placeholder="Select client account" options={accounts.map((a) => ({ value: a.id, label: a.name }))} showSearch filterOption={(input, opt) => (opt?.label as string).toLowerCase().includes(input.toLowerCase())} />
            </Form.Item>

            <Form.Item name="dueDate" label="Due Date" rules={[{ required: true, message: 'Due date is required' }]}>
              <DatePicker className="w-full" format="DD MMM YYYY" />
            </Form.Item>
          </div>

          <div className="mb-4">
            <div className="mb-2 flex items-center justify-between">
              <span className="text-[13px] font-semibold text-[var(--tcx-text)]">Invoice Line Items</span>
              <Button size="small" icon={<Icon name="plus" size={12} />} onClick={handleAddBlankItem}>
                Add Deliverable / Milestone
              </Button>
            </div>

            <div className="space-y-3 rounded-lg border border-[var(--tcx-border)] bg-[var(--tcx-surface-2)] p-3">
              {formItems.map((item, idx) => (
                <div key={idx} className="rounded-md border border-[var(--tcx-border)] bg-[var(--tcx-surface)] p-3">
                  <div className="flex items-start justify-between gap-2">
                    <Input className="font-semibold text-[13px]" placeholder="Item name / deliverable" value={item.name} onChange={(e) => handleItemChange(idx, 'name', e.target.value)} />
                    <Button size="small" type="text" danger icon={<Icon name="trash" size={13} />} onClick={() => handleRemoveItem(idx)} />
                  </div>
                  <div className="mt-2 grid grid-cols-4 gap-2">
                    <div>
                      <label className="text-[11px] text-[var(--tcx-muted)]">Qty</label>
                      <InputNumber className="w-full" min={1} value={item.quantity} onChange={(v) => handleItemChange(idx, 'quantity', v || 1)} />
                    </div>
                    <div>
                      <label className="text-[11px] text-[var(--tcx-muted)]">Unit Price (₹)</label>
                      <InputNumber className="w-full" min={0} value={item.unitPrice} onChange={(v) => handleItemChange(idx, 'unitPrice', v || 0)} />
                    </div>
                    <div>
                      <label className="text-[11px] text-[var(--tcx-muted)]">Disc %</label>
                      <InputNumber className="w-full" min={0} max={100} value={item.discountPercent} onChange={(v) => handleItemChange(idx, 'discountPercent', v || 0)} />
                    </div>
                    <div>
                      <label className="text-[11px] text-[var(--tcx-muted)]">GST %</label>
                      <Select className="w-full" value={item.gstRate} onChange={(v) => handleItemChange(idx, 'gstRate', v)} options={gstRates.map((r) => ({ value: r, label: `${r}%` }))} />
                    </div>
                  </div>
                </div>
              ))}

              <div className="flex justify-end pt-2 text-[12px] text-[var(--tcx-muted)]">
                <div className="w-56 space-y-1">
                  <div className="flex justify-between">
                    <span>Subtotal:</span>
                    <span>{formatINR(liveTotals.subtotal)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Discount:</span>
                    <span>-{formatINR(liveTotals.discount)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>GST Tax:</span>
                    <span>{formatINR(liveTotals.tax)}</span>
                  </div>
                  <div className="flex justify-between border-t border-[var(--tcx-border)] pt-1 font-bold text-[var(--tcx-text)]">
                    <span>Grand Total:</span>
                    <span>{formatINR(liveTotals.grand)}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <Form.Item name="notes" label="Invoice Notes / Payment Instructions">
            <Input.TextArea rows={2} placeholder="Bank details, wire instructions, or billing notes..." />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
