'use client';

import React, { useEffect, useState } from 'react';
import { App, Button, DatePicker, Drawer, Input, Modal, Popconfirm, Tag } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { DataTable, FilterTabsBar, PageHeader, type DataTableColumn } from '../platform/PlatformPrimitives';
import { UserAvatar } from '../ui/UserAvatar';
import { invoicesApi, quotesApi, type QuoteRecord, type QuoteStatus } from '../../lib/finance';
import { usePermissions } from '../../lib/usePermissions';
import { QuoteCreateModal } from './QuoteCreateModal';

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

export function QuotesView() {
  const { message } = App.useApp();
  const { can } = usePermissions();
  const canCreate = can('quotes', 'create');
  const canEdit = can('quotes', 'update');
  const mayDelete = can('quotes', 'delete');
  const canCreateInvoice = can('invoices', 'create');

  const [activeTab, setActiveTab] = useState<'all' | 'open' | 'accepted' | 'draft'>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(true);
  const [quotes, setQuotes] = useState<QuoteRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [summary, setSummary] = useState({
    allCount: 0,
    allTotal: 0,
    sentCount: 0,
    sentTotal: 0,
    acceptedCount: 0,
    acceptedTotal: 0,
    draftCount: 0,
    draftTotal: 0,
  });

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

  // Modals & Drawers state
  const [createModalOpen, setCreateModalOpen] = useState(false);

  // Detail Drawer state
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState<QuoteRecord | null>(null);

  // Convert to Invoice Modal
  const [invoiceModalOpen, setInvoiceModalOpen] = useState(false);
  const [invoiceDueDate, setInvoiceDueDate] = useState<dayjs.Dayjs | null>(dayjs().add(15, 'day'));
  const [converting, setConverting] = useState(false);

  // Load quotes list & statistics
  useEffect(() => {
    let active = true;
    void (async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const statusFilter: QuoteStatus | undefined = activeTab === 'open' ? 'SENT' : activeTab === 'accepted' ? 'ACCEPTED' : activeTab === 'draft' ? 'DRAFT' : undefined;

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

        if (!active) return;
        setQuotes(res.data || []);
        setTotal(res.meta?.total ?? 0);
        if (res.summary) {
          setSummary(res.summary);
        }
      } catch (err) {
        if (active) {
          message.error(err instanceof Error ? err.message : 'Failed to load quotes');
        }
      } finally {
        if (active) setLoading(false);
      }
    })();

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

  const handleViewQuote = async (q: QuoteRecord) => {
    try {
      const full = await quotesApi.get(q.id);
      setSelectedQuote(full);
      setDrawerOpen(true);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to load quote details');
    }
  };

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

  const handleRevise = async (id: string) => {
    try {
      const revised = await quotesApi.revise(id);
      message.success(`Revised quote ${revised.quoteNumber} v${revised.version} created`);
      setSelectedQuote(revised);
      setReload((r) => r + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to create quote revision');
    }
  };

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

  const handleConvertToInvoice = async () => {
    if (!selectedQuote || !invoiceDueDate) return;
    setConverting(true);
    try {
      const inv = await invoicesApi.createFromQuote(selectedQuote.id, {
        dueDate: invoiceDueDate.toISOString(),
      });
      message.success(`Invoice ${inv.invoiceNumber} generated from quote!`);
      setInvoiceModalOpen(false);
      setDrawerOpen(false);
      setReload((r) => r + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to generate invoice');
    } finally {
      setConverting(false);
    }
  };

  const handleDownloadPDF = async (q: QuoteRecord) => {
    try {
      message.loading({ content: 'Generating Quote PDF...', key: 'quote-pdf' });
      await quotesApi.downloadPdf(q.id, q.quoteNumber);
      message.success({ content: `Quote ${q.quoteNumber} downloaded successfully`, key: 'quote-pdf' });
    } catch (err) {
      message.error({ content: err instanceof Error ? err.message : 'Failed to download PDF', key: 'quote-pdf' });
    }
  };

  const getStatusColor = (s: QuoteStatus) => {
    switch (s) {
      case 'ACCEPTED':
        return 'green';
      case 'SENT':
        return 'blue';
      case 'DECLINED':
        return 'red';
      case 'EXPIRED':
        return 'orange';
      default:
        return 'default';
    }
  };

  const columns: DataTableColumn<QuoteRecord>[] = [
    {
      key: 'quoteNumber',
      title: 'Quote',
      render: (_val, r) => (
        <div className="cursor-pointer" onClick={() => handleViewQuote(r)}>
          <div className="font-semibold text-[13.5px] text-[var(--tcx-text)] hover:text-[var(--tcx-primary)]">
            {r.quoteNumber} <span className="font-mono text-[11px] text-[var(--tcx-muted)]">v{r.version}</span>
          </div>
          <div className="text-[12px] text-[var(--tcx-muted)]">
            {r.account?.name || 'No client'} {r.serviceName ? `· ${r.serviceName}` : ''}
          </div>
        </div>
      ),
    },
    {
      key: 'status',
      title: 'Status',
      render: (_val, r) => <Tag color={getStatusColor(r.status)}>{r.status}</Tag>,
    },
    {
      key: 'totalAmount',
      title: 'Total Value',
      align: 'right',
      render: (_val, r) => <span className="font-bold text-[13.5px] text-[var(--tcx-text)]">{formatINR(r.totalAmount)}</span>,
    },
    {
      key: 'issueDate',
      title: 'Issued Date',
      render: (_val, r) => <span className="text-[12.5px] text-[var(--tcx-muted)]">{dayjs(r.issueDate).format('DD MMM YYYY')}</span>,
    },
    {
      key: 'expiryDate',
      title: 'Valid Until',
      render: (_val, r) => {
        const isExpired = dayjs().isAfter(dayjs(r.expiryDate)) && r.status === 'SENT';
        return <span className={`text-[12.5px] ${isExpired ? 'font-semibold text-rose-600' : 'text-[var(--tcx-muted)]'}`}>{dayjs(r.expiryDate).format('DD MMM YYYY')}</span>;
      },
    },
    {
      key: 'owner',
      title: 'Owner',
      render: (_val, r) =>
        r.owner ? (
          <div className="flex items-center gap-2">
            <UserAvatar name={r.owner.name} size={22} />
            <span className="text-[12px] text-[var(--tcx-text)]">{r.owner.name}</span>
          </div>
        ) : (
          <span className="text-[12px] text-[var(--tcx-muted)]">—</span>
        ),
    },
    {
      key: 'actions',
      title: '',
      align: 'right',
      render: (_val, r) => (
        <div className="flex items-center justify-end gap-1.5" onClick={(e) => e.stopPropagation()}>
          <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={() => handleViewQuote(r)} />
        </div>
      ),
    },
  ];

  return (
    <div className="tcx-page">
      <PageHeader
        eyebrow="Finance"
        title="Quotes & Proposals"
        subtitle={`${summary.sentCount} quotes awaiting client approval, worth ${formatINR(summary.sentTotal)}`}
        actions={
          canCreate ? (
            <Button type="primary" icon={<Icon name="plus" size={14} />} onClick={() => setCreateModalOpen(true)}>
              Create Quote
            </Button>
          ) : undefined
        }
      />

      <div className="mb-4">
        <FilterTabsBar
          tabs={[
            { key: 'all', label: 'All Quotes', count: summary.allCount },
            { key: 'open', label: 'Awaiting Customer', count: summary.sentCount },
            { key: 'accepted', label: 'Accepted', count: summary.acceptedCount },
            { key: 'draft', label: 'Drafts', count: summary.draftCount },
          ]}
          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 quote number, client account, deal..."
          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={quotes}
          loading={loading}
          onRowClick={(r) => handleViewQuote(r)}
          pagination={{
            page,
            pageSize,
            total,
            onPageChange: (p) => setPage(p),
            onPageSizeChange: (ps) => setPageSize(ps),
          }}
        />
      </div>

      {/* Create Quote Modal */}
      <QuoteCreateModal open={createModalOpen} onClose={() => setCreateModalOpen(false)} onSaved={() => setReload((r) => r + 1)} />

      {/* Quote Detail Drawer */}
      <Drawer
        title={
          selectedQuote ? (
            <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="quote" size={20} />
              </div>
              <div>
                <div className="text-[16px] font-bold text-[var(--tcx-text)]">
                  {selectedQuote.quoteNumber} <span className="font-mono text-[12px] font-normal text-[var(--tcx-muted)]">v{selectedQuote.version}</span>
                </div>
                <div className="text-[12px] text-[var(--tcx-muted)]">
                  {selectedQuote.account?.name} {selectedQuote.deal ? `· ${selectedQuote.deal.title}` : ''}
                </div>
              </div>
            </div>
          ) : (
            'Quote Proposal'
          )
        }
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        size={620}
        extra={
          selectedQuote && (
            <div className="flex items-center gap-2">
              <Button size="small" icon={<Icon name="download" size={14} />} onClick={() => handleDownloadPDF(selectedQuote)}>
                PDF
              </Button>
              {selectedQuote.status === 'DRAFT' && canEdit && (
                <Button size="small" type="primary" icon={<Icon name="send" size={14} />} onClick={() => handleStatusChange(selectedQuote.id, 'SENT')}>
                  Send to Client
                </Button>
              )}
              {selectedQuote.status === 'SENT' && canEdit && (
                <>
                  <Button size="small" onClick={() => handleStatusChange(selectedQuote.id, 'ACCEPTED')}>
                    Mark Accepted
                  </Button>
                  <Button size="small" onClick={() => handleRevise(selectedQuote.id)}>
                    Revise (v{selectedQuote.version + 1})
                  </Button>
                </>
              )}
              {selectedQuote.status === 'ACCEPTED' && canCreateInvoice && (
                <Button size="small" type="primary" icon={<Icon name="receipt" size={14} />} onClick={() => setInvoiceModalOpen(true)}>
                  Create Invoice
                </Button>
              )}
              {mayDelete && (
                <Popconfirm title="Delete this quote?" okText="Delete" cancelText="Cancel" okButtonProps={{ danger: true }} onConfirm={() => handleDelete(selectedQuote.id)}>
                  <Button size="small" danger icon={<Icon name="trash" size={14} />} />
                </Popconfirm>
              )}
            </div>
          )
        }
      >
        {selectedQuote && (
          <div className="space-y-6">
            <div className="flex items-center justify-between rounded-xl border border-[var(--tcx-border)] bg-[var(--tcx-surface-2)] p-4">
              <div>
                <div className="text-[12px] font-bold uppercase tracking-wider text-[var(--tcx-muted)]">Total Proposal Amount</div>
                <div className="text-[28px] font-bold text-[var(--tcx-text)]">{formatINR(selectedQuote.totalAmount)}</div>
                <div className="text-[12px] text-[var(--tcx-muted)]">Valid until {dayjs(selectedQuote.expiryDate).format('DD MMM YYYY')}</div>
              </div>
              <Tag color={getStatusColor(selectedQuote.status)} className="px-3 py-1 text-[13px] font-semibold">
                {selectedQuote.status}
              </Tag>
            </div>

            {/* Line items table */}
            <div>
              <div className="mb-2 font-semibold text-[13.5px] text-[var(--tcx-text)]">Priced Deliverables</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)]">
                  {(selectedQuote.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(selectedQuote.subtotal)}</span>
                </div>
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>Discount:</span>
                  <span>− {formatINR(selectedQuote.discountTotal)}</span>
                </div>
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>GST (18%):</span>
                  <span>{formatINR(selectedQuote.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>Grand Total:</span>
                  <span className="text-[var(--tcx-primary)]">{formatINR(selectedQuote.totalAmount)}</span>
                </div>
              </div>
            </div>

            {selectedQuote.notes && (
              <div>
                <div className="text-[13px] font-semibold text-[var(--tcx-text)]">Proposal Notes</div>
                <div className="mt-1 text-[13px] text-[var(--tcx-muted)]">{selectedQuote.notes}</div>
              </div>
            )}

            {selectedQuote.terms && (
              <div>
                <div className="text-[13px] font-semibold text-[var(--tcx-text)]">Terms & Payment Schedule</div>
                <div className="mt-1 text-[13px] text-[var(--tcx-muted)]">{selectedQuote.terms}</div>
              </div>
            )}
          </div>
        )}
      </Drawer>

      {/* Convert to Invoice Modal */}
      <Modal title="Generate GST Tax Invoice" open={invoiceModalOpen} onOk={handleConvertToInvoice} confirmLoading={converting} onCancel={() => setInvoiceModalOpen(false)} okText="Generate Invoice">
        <p className="text-[13px] text-[var(--tcx-muted)]">This will generate a tax invoice directly copying all priced items, GST calculations, and customer details from {selectedQuote?.quoteNumber}.</p>
        <div className="mt-4">
          <label className="mb-1 block text-[13px] font-semibold text-[var(--tcx-text)]">Payment Due Date</label>
          <DatePicker className="w-full" value={invoiceDueDate} onChange={(d) => setInvoiceDueDate(d)} format="DD MMM YYYY" />
        </div>
      </Modal>
    </div>
  );
}
