import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import Layout from '../../components/Layout';
import { supabase } from '../../lib/supabase';
import { generateSubcontractorPOPDF } from '../../lib/invoice';
import { blobToEmailAttachment, sendEmail } from '../../lib/email';

const statusColor = { draft: 'not_started', submitted: 'in_progress', paid: 'client_approved' };

export default function SubInvoiceDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [invoice, setInvoice] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [generating, setGenerating] = useState(false);

  useEffect(() => {
    supabase
      .from('subcontractor_invoices')
      .select('*, profile:profiles!subcontractor_invoices_profile_id_fkey(id, name, email), items:subcontractor_invoice_items(*)')
      .eq('id', id)
      .single()
      .then(({ data }) => {
        setInvoice(data);
        setLoading(false);
      });
  }, [id]);

  const total = (invoice?.items || []).reduce((s, i) => s + Number(i.unit_price || 0) * Number(i.quantity || 1), 0);

  const buildPDFArgs = (inv) => ({
    po_number: inv.invoice_number,
    status: 'paid',
    profile: inv.profile,
    project: { name: 'Subcontractor Invoice', company: { name: 'Fourge Branding' } },
    date: inv.created_at?.split('T')[0],
    due_date: (inv.paid_at || new Date().toISOString()).split('T')[0],
    amount: total,
    description: 'Payment for completed subcontractor work.',
    notes: inv.notes,
    items: (inv.items || []).map((item, idx) => ({
      description: item.description,
      amount: Number(item.unit_price) * Number(item.quantity || 1),
      sort_order: item.sort_order ?? idx,
    })),
  });

  const handleMarkPaid = async () => {
    setSaving(true);
    try {
      const paidAt = new Date().toISOString();
      const { error } = await supabase.from('subcontractor_invoices').update({ status: 'paid', paid_at: paidAt }).eq('id', id);
      if (error) throw error;
      const updated = { ...invoice, status: 'paid', paid_at: paidAt };
      setInvoice(updated);
      let pdfBlob = null;
      try { pdfBlob = await generateSubcontractorPOPDF(buildPDFArgs(updated), { output: 'blob' }); } catch {}
      if (invoice.profile?.email) {
        try {
          const attachments = pdfBlob ? [await blobToEmailAttachment(pdfBlob, `${invoice.invoice_number}-receipt.pdf`)] : [];
          await sendEmail('receipt_sent', invoice.profile.email, {
            invoiceNumber: invoice.invoice_number,
            billTo: invoice.profile.name || invoice.profile.email,
            total: total.toFixed(2),
            paidDate: new Date(paidAt).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }),
          }, attachments);
        } catch (emailErr) {
          alert(`Marked paid, but email failed: ${emailErr.message || 'unknown error'}`);
        }
      }
    } catch (err) {
      alert(`Failed to mark as paid: ${err.message}`);
    }
    setSaving(false);
  };

  const handleReceipt = async () => {
    setGenerating(true);
    try {
      await generateSubcontractorPOPDF(buildPDFArgs(invoice));
    } catch (err) {
      alert(err.message);
    }
    setGenerating(false);
  };

  const handleDelete = async () => {
    if (!window.confirm(`Delete invoice ${invoice.invoice_number}? This cannot be undone.`)) return;
    setSaving(true);
    const { error } = await supabase.from('subcontractor_invoices').delete().eq('id', id);
    if (error) { alert('Failed to delete: ' + error.message); setSaving(false); return; }
    navigate('/invoices', { state: { tab: 'sub-invoices' } });
  };

  if (loading) return <Layout><p style={{ padding: 24, color: 'var(--text-muted)' }}>Loading...</p></Layout>;
  if (!invoice) return <Layout><p style={{ padding: 24 }}>Invoice not found.</p></Layout>;

  const sortedItems = [...(invoice.items || [])].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));

  return (
    <Layout>
      <button className="back-link" onClick={() => navigate('/invoices', { state: { tab: 'sub-invoices' } })}>
        ← Back to Subcontractor Invoices
      </button>

      <div className="page-header">
        <div>
          <div className="page-title">{invoice.invoice_number}</div>
          <div className="page-subtitle">
            {invoice.profile?.name || 'External'} · {invoice.profile?.email || '—'}
          </div>
        </div>
        <span className={`badge badge-${statusColor[invoice.status] || 'not_started'}`} style={{ fontSize: 13, padding: '6px 14px', textTransform: 'capitalize' }}>
          {invoice.status}
        </span>
      </div>

      <div className="grid-2" style={{ marginBottom: 24 }}>
        <div className="card">
          <div className="card-title">Invoice Info</div>
          <div className="detail-grid" style={{ marginBottom: 0 }}>
            <div className="detail-item"><label>Invoice #</label><p style={{ fontWeight: 700 }}>{invoice.invoice_number}</p></div>
            <div className="detail-item"><label>Status</label><p style={{ textTransform: 'capitalize' }}>{invoice.status}</p></div>
            <div className="detail-item"><label>Submitted</label><p>{invoice.submitted_at ? new Date(invoice.submitted_at).toLocaleDateString() : '—'}</p></div>
            {invoice.paid_at && (
              <div className="detail-item"><label>Paid On</label><p style={{ color: 'var(--success)', fontWeight: 600 }}>{new Date(invoice.paid_at).toLocaleDateString()}</p></div>
            )}
          </div>
        </div>
        <div className="card">
          <div className="card-title">Summary</div>
          <div className="detail-grid" style={{ marginBottom: 0 }}>
            <div className="detail-item"><label>Line Items</label><p>{sortedItems.length}</p></div>
            <div className="detail-item"><label>Total</label><p style={{ fontWeight: 700, fontSize: 18 }}>${total.toFixed(2)}</p></div>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 24 }}>
        <div className="card-title">Line Items</div>
        {sortedItems.length === 0 ? (
          <p style={{ color: 'var(--text-muted)', fontSize: 13 }}>No line items.</p>
        ) : (
          <div className="table-wrapper" style={{ border: 'none' }}>
            <table>
              <thead>
                <tr>
                  <th>Description</th>
                  <th style={{ textAlign: 'right' }}>Qty</th>
                  <th style={{ textAlign: 'right' }}>Unit Price</th>
                  <th style={{ textAlign: 'right' }}>Amount</th>
                </tr>
              </thead>
              <tbody>
                {sortedItems.map(item => (
                  <tr key={item.id}>
                    <td>{item.description}</td>
                    <td style={{ textAlign: 'right' }}>{item.quantity}</td>
                    <td style={{ textAlign: 'right' }}>${Number(item.unit_price).toFixed(2)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 700 }}>${(Number(item.unit_price) * Number(item.quantity || 1)).toFixed(2)}</td>
                  </tr>
                ))}
                <tr>
                  <td colSpan={3} style={{ textAlign: 'right', fontWeight: 700, borderTop: '1px solid var(--border)', paddingTop: 10 }}>Total</td>
                  <td style={{ textAlign: 'right', fontWeight: 700, fontSize: 16, borderTop: '1px solid var(--border)', paddingTop: 10 }}>${total.toFixed(2)}</td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
        {invoice.notes && (
          <div style={{ marginTop: 16, padding: '12px 14px', background: 'var(--bg)', borderRadius: 8, border: '1px solid var(--border)' }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Notes</div>
            <p style={{ fontSize: 13, color: 'var(--text-secondary)', whiteSpace: 'pre-wrap', margin: 0 }}>{invoice.notes}</p>
          </div>
        )}
      </div>

      <div className="card">
        <div className="card-title">Actions</div>
        <div className="action-buttons">
          {invoice.status === 'submitted' && (
            <button className="btn btn-success" onClick={handleMarkPaid} disabled={saving}>
              {saving ? 'Processing…' : 'Mark as Paid'}
            </button>
          )}
          {invoice.status === 'paid' && (
            <button className="btn btn-outline" onClick={handleReceipt} disabled={generating}>
              {generating ? 'Generating…' : 'Download Receipt'}
            </button>
          )}
          <button className="btn btn-danger" onClick={handleDelete} disabled={saving}>
            Delete Invoice
          </button>
        </div>
      </div>
    </Layout>
  );
}
