'use client';

import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { App, Button, Tag, Tooltip } from 'antd';
import { Icon } from '../ui/Icon';
import { inr } from '../../lib/leads';
import { quotesApi, type QuoteRecord, type QuoteStatus } from '../../lib/finance';
import { QuoteCreateModal } from '../finance/QuoteCreateModal';
import { QuoteDetailDrawer } from '../finance/QuoteDetailDrawer';

function getQuoteStatusBadge(status: QuoteStatus) {
  switch (status) {
    case 'ACCEPTED':
      return <Tag color="success">Accepted</Tag>;
    case 'SENT':
      return <Tag color="processing">Sent</Tag>;
    case 'DRAFT':
      return <Tag color="default">Draft</Tag>;
    case 'DECLINED':
      return <Tag color="error">Declined</Tag>;
    case 'EXPIRED':
      return <Tag color="warning">Expired</Tag>;
    default:
      return <Tag>{status}</Tag>;
  }
}

export function DealLinkedQuotes({ dealId, accountId, onCountChange }: { dealId: string; accountId?: string; onCountChange?: (count: number) => void }) {
  const { message } = App.useApp();
  const [quotes, setQuotes] = useState<QuoteRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [downloadingId, setDownloadingId] = useState<string | null>(null);
  const [reload, setReload] = useState(0);

  // Modals / Drawer state
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [selectedQuoteId, setSelectedQuoteId] = useState<string | null>(null);

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

  const handleDownloadPdf = async (q: QuoteRecord) => {
    setDownloadingId(q.id);
    try {
      await quotesApi.downloadPdf(q.id, q.quoteNumber);
      message.success('Quote PDF downloaded');
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to download quote PDF');
    } finally {
      setDownloadingId(null);
    }
  };

  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)]">Deal Quotes & Proposals</h3>
          <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">Pricing proposals, estimates, and commercial terms prepared for this deal.</p>
        </div>
        <Button type="primary" icon={<Icon name="plus" size={13} />} onClick={() => setCreateModalOpen(true)}>
          New quote
        </Button>
      </div>

      {loading ? (
        <div className="py-8 text-center text-xs text-slate-400">Loading quotes...</div>
      ) : quotes.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 quotes created for this deal yet</p>
          <p className="m-0 mt-1 text-[12.5px] text-[var(--tcx-muted)]">Create an official commercial proposal with line items and taxes to send to the client.</p>
          <Button type="primary" icon={<Icon name="plus" size={13} />} className="mt-3" onClick={() => setCreateModalOpen(true)}>
            Create first quote
          </Button>
        </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">Quote #</th>
                <th className="p-3">Status</th>
                <th className="p-3">Issue Date</th>
                <th className="p-3">Valid Until</th>
                <th className="p-3 text-right">Total Amount</th>
                <th className="p-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--tcx-border)]">
              {quotes.map((q) => (
                <tr key={q.id} className="hover:bg-[var(--tcx-sunken)]">
                  <td className="p-3">
                    <button type="button" onClick={() => setSelectedQuoteId(q.id)} className="cursor-pointer font-semibold text-blue-600 hover:underline dark:text-blue-400">
                      {q.quoteNumber}
                    </button>
                    {q.version > 1 ? <span className="ml-1.5 rounded bg-slate-100 px-1.5 py-0.5 text-[10.5px] font-mono text-slate-500 dark:bg-slate-800 dark:text-slate-400">v{q.version}</span> : null}
                    {q.serviceName ? <div className="mt-0.5 text-[11.5px] text-[var(--tcx-muted)]">{q.serviceName}</div> : null}
                  </td>
                  <td className="p-3">{getQuoteStatusBadge(q.status)}</td>
                  <td className="p-3 text-slate-500 text-xs">{dayjs(q.issueDate).format('D MMM YYYY')}</td>
                  <td className="p-3 text-slate-500 text-xs">{dayjs(q.expiryDate).format('D MMM YYYY')}</td>
                  <td className="p-3 text-right font-bold tabular-nums text-slate-800 dark:text-slate-100">{inr(q.totalAmount)}</td>
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-1">
                      <Tooltip title="View details">
                        <Button type="text" size="small" icon={<Icon name="eye" size={14} />} onClick={() => setSelectedQuoteId(q.id)} aria-label="View" />
                      </Tooltip>
                      <Tooltip title="Download PDF">
                        <Button type="text" size="small" loading={downloadingId === q.id} icon={<Icon name="download" size={14} />} onClick={() => handleDownloadPdf(q)} aria-label="Download" />
                      </Tooltip>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

      {/* Quote Detail Drawer */}
      <QuoteDetailDrawer
        open={!!selectedQuoteId}
        quoteId={selectedQuoteId}
        onClose={() => setSelectedQuoteId(null)}
        onChanged={() => {
          setReload((r) => r + 1);
        }}
      />
    </div>
  );
}
