'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import dayjs from 'dayjs';
import { App, Button, Tag, Tooltip } from 'antd';
import { Icon } from '../ui/Icon';
import { inr } from '../../lib/leads';
import { invoicesApi, type InvoiceRecord, type InvoiceStatus } from '../../lib/finance';

function getInvoiceStatusBadge(status: InvoiceStatus) {
  switch (status) {
    case 'PAID':
      return <Tag color="success">Paid</Tag>;
    case 'PARTIALLY_PAID':
      return <Tag color="warning">Partially Paid</Tag>;
    case 'SENT':
      return <Tag color="processing">Sent</Tag>;
    case 'OVERDUE':
      return <Tag color="error">Overdue</Tag>;
    case 'DRAFT':
      return <Tag color="default">Draft</Tag>;
    case 'VOID':
      return <Tag color="default">Void</Tag>;
    default:
      return <Tag>{status}</Tag>;
  }
}

export function CustomerLinkedInvoices({ customerId, onCountChange }: { customerId: string; onCountChange?: (count: number) => void }) {
  const { message } = App.useApp();
  const [invoices, setInvoices] = useState<InvoiceRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [downloadingId, setDownloadingId] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    const load = async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const res = await invoicesApi.list({ accountId: customerId, limit: 100 });
        if (!active) return;
        setInvoices(res.data);
        onCountChange?.(res.meta.total);
      } catch {
        if (!active) return;
        setInvoices([]);
      } finally {
        if (active) setLoading(false);
      }
    };
    void load();
    return () => {
      active = false;
    };
  }, [customerId, onCountChange]);

  const handleDownloadPdf = async (inv: InvoiceRecord) => {
    setDownloadingId(inv.id);
    try {
      await invoicesApi.downloadPdf(inv.id, inv.invoiceNumber);
      message.success('Invoice PDF downloaded');
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to download invoice PDF');
    } finally {
      setDownloadingId(null);
    }
  };

  const newInvoiceUrl = `/app/invoices/new?accountId=${encodeURIComponent(customerId)}`;

  return (
    <div className="pt-2">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Customer Invoices & Billing</h3>
          <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">Tax invoices, billing balance, and payment receipts for this customer account.</p>
        </div>
        <Link href={newInvoiceUrl}>
          <Button type="primary" icon={<Icon name="plus" size={13} />}>
            New invoice
          </Button>
        </Link>
      </div>

      {loading ? (
        <div className="py-8 text-center text-xs text-slate-400">Loading invoices...</div>
      ) : invoices.length === 0 ? (
        <div className="rounded-xl border border-dashed border-[var(--tcx-border)] p-8 text-center">
          <p className="m-0 text-[14px] font-semibold text-[var(--tcx-text)]">No invoices generated for this customer yet</p>
          <p className="m-0 mt-1 text-[12.5px] text-[var(--tcx-muted)]">Create GST tax invoices, bill milestones or logged timesheet hours.</p>
          <Link href={newInvoiceUrl}>
            <Button type="primary" icon={<Icon name="plus" size={13} />} className="mt-3">
              Create first invoice
            </Button>
          </Link>
        </div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-[var(--tcx-border)]">
          <table className="w-full text-left text-[13px]">
            <thead className="border-b border-[var(--tcx-border)] bg-[var(--tcx-sunken)] text-[var(--tcx-muted)]">
              <tr>
                <th className="p-3">Invoice #</th>
                <th className="p-3">Status</th>
                <th className="p-3">Issue Date</th>
                <th className="p-3">Due Date</th>
                <th className="p-3 text-right">Total Amount</th>
                <th className="p-3 text-right">Balance Due</th>
                <th className="p-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--tcx-border)]">
              {invoices.map((inv) => {
                const balanceDue = Math.max(0, inv.totalAmount - inv.paidAmount);
                return (
                  <tr key={inv.id} className="hover:bg-[var(--tcx-sunken)]">
                    <td className="p-3">
                      <Link href={`/app/invoices/${inv.id}`} className="font-semibold text-blue-600 hover:underline dark:text-blue-400">
                        {inv.invoiceNumber}
                      </Link>
                      {inv.project ? <div className="text-[11px] text-slate-400">Project: {inv.project.name}</div> : null}
                    </td>
                    <td className="p-3">{getInvoiceStatusBadge(inv.status)}</td>
                    <td className="p-3 text-slate-500 text-xs">{dayjs(inv.issueDate).format('D MMM YYYY')}</td>
                    <td className="p-3 text-slate-500 text-xs">{dayjs(inv.dueDate).format('D MMM YYYY')}</td>
                    <td className="p-3 text-right font-bold tabular-nums text-slate-800 dark:text-slate-100">{inr(inv.totalAmount)}</td>
                    <td className="p-3 text-right font-medium tabular-nums">{balanceDue > 0 ? <span className="text-amber-600 dark:text-amber-400">{inr(balanceDue)}</span> : <span className="text-emerald-600 dark:text-emerald-400 font-semibold">Settled</span>}</td>
                    <td className="p-3 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Tooltip title="View details">
                          <Link href={`/app/invoices/${inv.id}`}>
                            <Button type="text" size="small" icon={<Icon name="eye" size={14} />} aria-label="View" />
                          </Link>
                        </Tooltip>
                        <Tooltip title="Download PDF">
                          <Button type="text" size="small" loading={downloadingId === inv.id} icon={<Icon name="download" size={14} />} onClick={() => handleDownloadPdf(inv)} aria-label="Download" />
                        </Tooltip>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
