'use client';

import { useState, useEffect, useCallback } from 'react';

interface Props {
  companyId?: string;
  selectedCompany: 'rmp' | 'jtr';
  companies: any[];
}

const STATUS_COLORS: Record<string, string> = {
  draft: 'bg-gray-700 text-gray-300',
  sent: 'bg-blue-900 text-blue-300',
  viewed: 'bg-purple-900 text-purple-300',
  paid: 'bg-green-900 text-green-300',
  overdue: 'bg-red-900 text-red-300',
  cancelled: 'bg-gray-800 text-gray-400',
};

function fmt(n: number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n);
}

export default function InvoicesTab({ companyId, selectedCompany, companies }: Props) {
  const [invoices, setInvoices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [clients, setClients] = useState<any[]>([]);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [newInvoice, setNewInvoice] = useState({
    client_id: '',
    issue_date: new Date().toISOString().split('T')[0],
    due_date: '',
    notes: '',
    internal_memo: '',
    payment_terms: 'Net 30',
  });
  const [lineItems, setLineItems] = useState([{ description: '', quantity: 1, rate: 0, amount: 0 }]);

  const loadInvoices = useCallback(() => {
    setLoading(true);
    const params = new URLSearchParams();
    if (companyId) params.set('companyId', companyId);
    if (statusFilter !== 'all') params.set('status', statusFilter);
    if (search) params.set('search', search);
    fetch(`/api/billing/invoices?${params}`)
      .then(r => r.json())
      .then(d => setInvoices(d.data || []))
      .finally(() => setLoading(false));
  }, [companyId, statusFilter, search]);

  useEffect(() => { loadInvoices(); }, [loadInvoices]);

  useEffect(() => {
    if (companyId) {
      fetch(`/api/billing/clients?companyId=${companyId}`)
        .then(r => r.json())
        .then(d => setClients(d.data || []));
    }
  }, [companyId]);

  const handleAction = async (action: string, inv: any) => {
    setActionLoading(`${action}-${inv.id}`);
    try {
      await fetch('/api/billing/invoices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, invoiceId: inv.id, company: selectedCompany }),
      });
      loadInvoices();
    } finally {
      setActionLoading(null);
    }
  };

  const handleDownloadPdf = async (inv: any) => {
    window.open(`/api/billing/invoices/pdf?id=${inv.id}&company=${selectedCompany}`, '_blank');
  };

  const calcLineItem = (idx: number, field: string, value: any) => {
    const updated = [...lineItems];
    updated[idx] = { ...updated[idx], [field]: value };
    if (field === 'quantity' || field === 'rate') {
      updated[idx].amount = Number(updated[idx].quantity) * Number(updated[idx].rate);
    }
    setLineItems(updated);
  };

  const total = lineItems.reduce((s, li) => s + Number(li.amount), 0);

  const handleCreateInvoice = async () => {
    const company = companies.find(c => c.llc_entity === selectedCompany.toUpperCase());
    const invoiceNumber = `${company?.invoice_prefix || 'INV-'}${Date.now().toString().slice(-6)}`;
    await fetch('/api/billing/invoices', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        invoice: {
          ...newInvoice,
          company_id: companyId,
          invoice_number: invoiceNumber,
          status: 'draft',
          subtotal: total,
          total,
          currency: 'USD',
          moonCompany: selectedCompany,
        },
        lineItems,
      }),
    });
    setShowCreate(false);
    loadInvoices();
  };

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3">
        <input
          type="text"
          placeholder="Search invoice # or client..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 placeholder-gray-500 w-64 focus:outline-none focus:border-blue-500"
        />
        <select
          value={statusFilter}
          onChange={e => setStatusFilter(e.target.value)}
          className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
        >
          {['all', 'draft', 'sent', 'viewed', 'paid', 'overdue', 'cancelled'].map(s => (
            <option key={s} value={s}>{s === 'all' ? 'All Statuses' : s.charAt(0).toUpperCase() + s.slice(1)}</option>
          ))}
        </select>
        <div className="ml-auto">
          <button
            onClick={() => setShowCreate(true)}
            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
          >
            + Create Invoice
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-800 text-gray-400 text-xs uppercase tracking-wide">
                <th className="text-left px-4 py-3">Invoice #</th>
                <th className="text-left px-4 py-3">Client</th>
                <th className="text-left px-4 py-3">Amount</th>
                <th className="text-left px-4 py-3">Issue Date</th>
                <th className="text-left px-4 py-3">Due Date</th>
                <th className="text-left px-4 py-3">Status</th>
                <th className="text-left px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="text-center py-12 text-gray-500">Loading...</td></tr>
              ) : invoices.length === 0 ? (
                <tr><td colSpan={7} className="text-center py-12 text-gray-500">No invoices found. Sync from MoonInvoice or create one.</td></tr>
              ) : invoices.map(inv => (
                <tr key={inv.id} className="border-b border-gray-800 hover:bg-gray-800/50 transition-colors">
                  <td className="px-4 py-3 font-mono text-blue-400">{inv.invoice_number}</td>
                  <td className="px-4 py-3 text-gray-200">{inv.billing_clients?.name || '—'}</td>
                  <td className="px-4 py-3 text-gray-200 font-medium">{fmt(inv.total || 0)}</td>
                  <td className="px-4 py-3 text-gray-400">{inv.issue_date || '—'}</td>
                  <td className="px-4 py-3 text-gray-400">{inv.due_date || '—'}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${STATUS_COLORS[inv.status] || 'bg-gray-700 text-gray-300'}`}>
                      {inv.status}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1 flex-wrap">
                      {inv.status === 'draft' && (
                        <button
                          onClick={() => handleAction('send', inv)}
                          disabled={!!actionLoading}
                          className="px-2 py-1 bg-blue-900/50 text-blue-300 rounded text-xs hover:bg-blue-900 transition-colors"
                        >
                          Send
                        </button>
                      )}
                      {['sent', 'viewed', 'overdue'].includes(inv.status) && (
                        <button
                          onClick={() => handleAction('record_payment', inv)}
                          disabled={!!actionLoading}
                          className="px-2 py-1 bg-green-900/50 text-green-300 rounded text-xs hover:bg-green-900 transition-colors"
                        >
                          Record Payment
                        </button>
                      )}
                      <button
                        onClick={() => handleDownloadPdf(inv)}
                        className="px-2 py-1 bg-gray-700 text-gray-300 rounded text-xs hover:bg-gray-600 transition-colors"
                      >
                        PDF
                      </button>
                      {inv.status !== 'cancelled' && (
                        <button
                          onClick={() => handleAction('cancel', inv)}
                          disabled={!!actionLoading}
                          className="px-2 py-1 bg-red-900/30 text-red-400 rounded text-xs hover:bg-red-900/60 transition-colors"
                        >
                          Cancel
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create Invoice Modal */}
      {showCreate && (
        <div className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4">
          <div className="bg-gray-900 border border-gray-700 rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b border-gray-800">
              <h2 className="text-lg font-semibold text-white">Create Invoice</h2>
              <button onClick={() => setShowCreate(false)} className="text-gray-400 hover:text-white">✕</button>
            </div>
            <div className="p-5 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Client</label>
                  <select
                    value={newInvoice.client_id}
                    onChange={e => setNewInvoice(p => ({ ...p, client_id: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                  >
                    <option value="">Select client...</option>
                    {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Payment Terms</label>
                  <select
                    value={newInvoice.payment_terms}
                    onChange={e => setNewInvoice(p => ({ ...p, payment_terms: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                  >
                    {['Net 15', 'Net 30', 'Net 45', 'Due on receipt'].map(t => <option key={t}>{t}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Issue Date</label>
                  <input type="date" value={newInvoice.issue_date}
                    onChange={e => setNewInvoice(p => ({ ...p, issue_date: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500" />
                </div>
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Due Date</label>
                  <input type="date" value={newInvoice.due_date}
                    onChange={e => setNewInvoice(p => ({ ...p, due_date: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500" />
                </div>
              </div>

              {/* Line Items */}
              <div>
                <label className="block text-xs text-gray-400 mb-2">Line Items</label>
                <div className="space-y-2">
                  {lineItems.map((li, idx) => (
                    <div key={idx} className="grid grid-cols-12 gap-2 items-center">
                      <input
                        placeholder="Description"
                        value={li.description}
                        onChange={e => calcLineItem(idx, 'description', e.target.value)}
                        className="col-span-5 bg-gray-800 border border-gray-700 rounded px-2 py-1.5 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                      />
                      <input
                        type="number" placeholder="Qty" value={li.quantity}
                        onChange={e => calcLineItem(idx, 'quantity', e.target.value)}
                        className="col-span-2 bg-gray-800 border border-gray-700 rounded px-2 py-1.5 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                      />
                      <input
                        type="number" placeholder="Rate" value={li.rate}
                        onChange={e => calcLineItem(idx, 'rate', e.target.value)}
                        className="col-span-2 bg-gray-800 border border-gray-700 rounded px-2 py-1.5 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                      />
                      <span className="col-span-2 text-sm text-gray-300 text-right">{fmt(li.amount)}</span>
                      <button onClick={() => setLineItems(items => items.filter((_, i) => i !== idx))}
                        className="col-span-1 text-red-400 hover:text-red-300 text-lg leading-none">×</button>
                    </div>
                  ))}
                </div>
                <button
                  onClick={() => setLineItems(items => [...items, { description: '', quantity: 1, rate: 0, amount: 0 }])}
                  className="mt-2 text-xs text-blue-400 hover:text-blue-300"
                >
                  + Add line item
                </button>
                <div className="text-right mt-2 text-sm font-semibold text-white">Total: {fmt(total)}</div>
              </div>

              <div>
                <label className="block text-xs text-gray-400 mb-1">Notes (visible to client)</label>
                <textarea value={newInvoice.notes}
                  onChange={e => setNewInvoice(p => ({ ...p, notes: e.target.value }))}
                  rows={2}
                  className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500" />
              </div>
              <div>
                <label className="block text-xs text-gray-400 mb-1">Internal Memo (not sent to client)</label>
                <textarea value={newInvoice.internal_memo}
                  onChange={e => setNewInvoice(p => ({ ...p, internal_memo: e.target.value }))}
                  rows={2}
                  className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500" />
              </div>
            </div>
            <div className="flex justify-end gap-3 p-5 border-t border-gray-800">
              <button onClick={() => setShowCreate(false)} className="px-4 py-2 text-sm text-gray-400 hover:text-white">Cancel</button>
              <button onClick={handleCreateInvoice} className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium">
                Create Invoice
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
