'use client';

import React, { useEffect, useState } from 'react';
import { App, Button, DatePicker, Drawer, Modal, Popconfirm, Tag } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { invoicesApi, quotesApi, type QuoteRecord, type QuoteStatus } from '../../lib/finance';
import { useAuth, UserRole } from '../../context/AuthContext';

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

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

export interface QuoteDetailDrawerProps {
  open: boolean;
  quoteId: string | null;
  onClose: () => void;
  onChanged?: () => void;
}

export function QuoteDetailDrawer({ open, quoteId, onClose, onChanged }: QuoteDetailDrawerProps) {
  const { message } = App.useApp();
  const { user } = useAuth();
  const isAdmin = user?.role === UserRole.ORGANIZATION_ADMIN;

  const [quote, setQuote] = useState<QuoteRecord | null>(null);
  const [loading, setLoading] = useState(false);

  // 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);

  useEffect(() => {
    let active = true;

    const loadQuote = async () => {
      await Promise.resolve();
      if (!active) return;
      if (!open || !quoteId) {
        setQuote(null);
        return;
      }
      setLoading(true);
      try {
        const full = await quotesApi.get(quoteId);
        if (!active) return;
        setQuote(full);
      } catch (err) {
        if (active) {
          message.error(err instanceof Error ? err.message : 'Failed to load quote details');
        }
      } finally {
        if (active) setLoading(false);
      }
    };
    void loadQuote();

    return () => {
      active = false;
    };
  }, [open, quoteId, message]);

  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 handleStatusChange = async (id: string, newStatus: QuoteStatus) => {
    try {
      const updated = await quotesApi.update(id, { status: newStatus });
      setQuote(updated);
      message.success(`Quote marked as ${newStatus}`);
      onChanged?.();
    } 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`);
      setQuote(revised);
      onChanged?.();
    } 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');
      onClose();
      onChanged?.();
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to delete quote');
    }
  };

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

  return (
    <>
      <Drawer
        title={
          quote ? (
            <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)]">
                  {quote.quoteNumber} <span className="font-mono text-[12px] font-normal text-[var(--tcx-muted)]">v{quote.version}</span>
                </div>
                <div className="text-[12px] text-[var(--tcx-muted)]">
                  {quote.account?.name} {quote.deal ? `· ${quote.deal.title}` : ''} {quote.serviceName ? `· ${quote.serviceName}` : ''}
                </div>
              </div>
            </div>
          ) : (
            'Quote Proposal'
          )
        }
        open={open}
        onClose={onClose}
        size={620}
        loading={loading}
        extra={
          quote && (
            <div className="flex items-center gap-2">
              <Button size="small" icon={<Icon name="download" size={14} />} onClick={() => handleDownloadPDF(quote)}>
                PDF
              </Button>
              {quote.status === 'DRAFT' && (
                <Button size="small" type="primary" icon={<Icon name="send" size={14} />} onClick={() => handleStatusChange(quote.id, 'SENT')}>
                  Send to Client
                </Button>
              )}
              {quote.status === 'SENT' && (
                <>
                  <Button size="small" onClick={() => handleStatusChange(quote.id, 'ACCEPTED')}>
                    Mark Accepted
                  </Button>
                  <Button size="small" onClick={() => handleRevise(quote.id)}>
                    Revise (v{quote.version + 1})
                  </Button>
                </>
              )}
              {quote.status === 'ACCEPTED' && (
                <Button size="small" type="primary" icon={<Icon name="receipt" size={14} />} onClick={() => setInvoiceModalOpen(true)}>
                  Create Invoice
                </Button>
              )}
              {isAdmin && (
                <Popconfirm title="Delete this quote?" okText="Delete" cancelText="Cancel" okButtonProps={{ danger: true }} onConfirm={() => handleDelete(quote.id)}>
                  <Button size="small" danger icon={<Icon name="trash" size={14} />} />
                </Popconfirm>
              )}
            </div>
          )
        }
      >
        {quote && (
          <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(quote.totalAmount)}</div>
                <div className="mt-1 flex items-center gap-2 text-[12px] text-[var(--tcx-muted)]">
                  <span>Valid until {dayjs(quote.expiryDate).format('DD MMM YYYY')}</span>
                  {quote.serviceName && (
                    <Tag color="cyan" className="m-0 font-medium text-[11px]">
                      Service: {quote.serviceName}
                    </Tag>
                  )}
                </div>
              </div>
              <Tag color={getStatusColor(quote.status)} className="px-3 py-1 text-[13px] font-semibold">
                {quote.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)]">
                  {(quote.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(quote.subtotal)}</span>
                </div>
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>Discount:</span>
                  <span>− {formatINR(quote.discountTotal)}</span>
                </div>
                <div className="flex w-52 justify-between py-0.5 text-[var(--tcx-muted)]">
                  <span>GST (18%):</span>
                  <span>{formatINR(quote.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(quote.totalAmount)}</span>
                </div>
              </div>
            </div>

            {quote.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)]">{quote.notes}</div>
              </div>
            )}

            {quote.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)]">{quote.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 {quote?.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>
    </>
  );
}
