'use client';
import React, { useState, useEffect, useCallback, Suspense } from 'react';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter, useSearchParams } from 'next/navigation';

function fmt(cents: number) { return '$' + (cents / 100).toLocaleString('en-US', { minimumFractionDigits: 2 }); }

const STATUS_COLORS: Record<string, string> = {
  paid: 'bg-green-400/10 text-green-400',
  pending: 'bg-yellow-400/10 text-yellow-400',
  overdue: 'bg-red-400/10 text-red-400',
  cancelled: 'bg-[#FFFFFF] text-[#555]',
};

function InvoicesContent() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const sp = useSearchParams();
  const [invoices, setInvoices] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);
  const [filterStatus, setFilterStatus] = useState(sp.get('status') ?? '');
  const [markPaidId, setMarkPaidId] = useState<string | null>(null);
  const [payForm, setPayForm] = useState({ method: 'check', paid_date: new Date().toISOString().split('T')[0], wire_reference: '' });
  const [saving, setSaving] = useState(false);
  const [payErrors, setPayErrors] = useState<Record<string, string>>({});
  const [successMsg, setSuccessMsg] = useState('');

  useEffect(() => { if (!loading && !user) router.push('/login?next=' + encodeURIComponent(window.location.pathname)); }, [user, loading, router]);

  const load = useCallback(async () => {
    setLoadingData(true);
    const params = new URLSearchParams();
    if (filterStatus) params.set('status', filterStatus);
    const r = await fetch(`/api/accounting/invoices?${params}`);
    const d = await r.json();
    setInvoices(d.invoices ?? []);
    setLoadingData(false);
  }, [filterStatus]);

  useEffect(() => { if (user) load(); }, [user, load]);

  function validatePayForm() {
    const errs: Record<string, string> = {};
    if (!payForm.paid_date) errs.paid_date = 'Paid date is required.';
    if (payForm.method === 'wire' && !payForm.wire_reference.trim()) errs.wire_reference = 'Wire reference is required for wire payments.';
    return errs;
  }

  function handlePayChange(key: string, value: string) {
    setPayForm(p => ({ ...p, [key]: value }));
    if (payErrors[key]) setPayErrors(p => { const n = { ...p }; delete n[key]; return n; });
  }

  async function handleMarkPaid(e: React.FormEvent) {
    e.preventDefault();
    if (!markPaidId) return;
    const errs = validatePayForm();
    if (Object.keys(errs).length > 0) { setPayErrors(errs); return; }
    setSaving(true);
    try {
      const res = await fetch(`/api/accounting/invoices/${markPaidId}/mark-paid`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payForm),
      });
      if (!res.ok) throw new Error('Failed to mark invoice as paid');
      const inv = invoices.find(i => i.id === markPaidId);
      setMarkPaidId(null);
      setPayErrors({});
      setPayForm({ method: 'check', paid_date: new Date().toISOString().split('T')[0], wire_reference: '' });
      setSuccessMsg(`Invoice ${inv?.invoice_number ?? ''} marked as paid.`);
      setTimeout(() => setSuccessMsg(''), 4000);
      load();
    } catch {
      setPayErrors({ _form: 'Something went wrong. Please try again.' });
    } finally {
      setSaving(false);
    }
  }

  function handleCloseModal() {
    setMarkPaidId(null);
    setPayErrors({});
    setPayForm({ method: 'check', paid_date: new Date().toISOString().split('T')[0], wire_reference: '' });
  }

  if (loading) return <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center"><div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" /></div>;
  if (!user) return null;

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-white p-6">
      <div className="max-w-7xl mx-auto space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">Invoices</h1>
            <Link href="/admin/accounting" className="text-xs text-[#555] hover:text-[#888]">← Accounting</Link>
          </div>
          <Link href="/admin/accounting/orders" className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500">+ New Invoice (via Order)</Link>
        </div>

        {/* Success Toast */}
        {successMsg && (
          <div className="flex items-center gap-2 px-4 py-2.5 bg-green-500/10 border border-green-500/30 rounded-lg text-green-400 text-xs">
            <svg className="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
            {successMsg}
          </div>
        )}

        {/* Filters */}
        <div className="flex gap-2 flex-wrap">
          {['','pending','paid','overdue','cancelled'].map(s => (
            <button key={s} onClick={() => setFilterStatus(s)} className={`px-3 py-1 rounded text-xs capitalize ${filterStatus === s ? 'bg-[#1D4ED8] text-white' : 'bg-[#111] border border-[#DCE6F2] text-[#888] hover:text-white'}`}>{s || 'All'}</button>
          ))}
        </div>

        {/* Mark Paid Modal */}
        {markPaidId && (
          <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
            <form onSubmit={handleMarkPaid} noValidate className="bg-[#111] border border-[#DCE6F2] rounded-lg p-5 w-80 space-y-3">
              <h3 className="text-sm font-semibold">Mark Invoice as Paid</h3>

              {payErrors._form && (
                <div className="flex items-center gap-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded text-red-400 text-xs">
                  <svg className="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                  {payErrors._form}
                </div>
              )}

              <div>
                <label className="text-xs text-[#888] block mb-1">Payment Method</label>
                <select value={payForm.method} onChange={e => handlePayChange('method', e.target.value)} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none">
                  {['stripe','wire','check','other'].map(m => <option key={m} value={m}>{m}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Paid Date <span className="text-red-400">*</span></label>
                <input type="date" value={payForm.paid_date} onChange={e => handlePayChange('paid_date', e.target.value)} className={`w-full px-2 py-1.5 bg-[#0a0a0a] border rounded text-xs text-white focus:outline-none ${payErrors.paid_date ? 'border-red-500/60' : 'border-[#DCE6F2]'}`} />
                {payErrors.paid_date && <p className="mt-1 text-xs text-red-400">{payErrors.paid_date}</p>}
              </div>
              {payForm.method === 'wire' && (
                <div>
                  <label className="text-xs text-[#888] block mb-1">Wire Reference <span className="text-red-400">*</span></label>
                  <input value={payForm.wire_reference} onChange={e => handlePayChange('wire_reference', e.target.value)} className={`w-full px-2 py-1.5 bg-[#0a0a0a] border rounded text-xs text-white focus:outline-none ${payErrors.wire_reference ? 'border-red-500/60' : 'border-[#DCE6F2]'}`} />
                  {payErrors.wire_reference && <p className="mt-1 text-xs text-red-400">{payErrors.wire_reference}</p>}
                </div>
              )}
              <div className="flex gap-2">
                <button type="submit" disabled={saving} className="px-3 py-1.5 bg-green-600 rounded text-xs font-medium hover:bg-green-500 disabled:opacity-50">{saving ? 'Saving…' : 'Mark Paid'}</button>
                <button type="button" onClick={handleCloseModal} className="px-3 py-1.5 bg-[#FFFFFF] border border-[#DCE6F2] rounded text-xs text-[#888] hover:text-white">Cancel</button>
              </div>
            </form>
          </div>
        )}

        {/* Table */}
        <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#FFFFFF]">
                {['Invoice#','Client','Site','Order#','Amount','Status','Due Date','Salesperson',''].map(h => (
                  <th key={h} className="px-3 py-2 text-left text-xs text-[#555] font-medium whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loadingData ? (
                <tr><td colSpan={9} className="px-4 py-8 text-center text-[#555] text-xs">Loading…</td></tr>
              ) : invoices.length === 0 ? (
                <tr><td colSpan={9} className="px-4 py-8 text-center text-[#555] text-xs">No invoices found</td></tr>
              ) : invoices.map((inv: any) => (
                <tr key={inv.id} className="border-b border-[#FFFFFF] hover:bg-[#FFFFFF]">
                  <td className="px-3 py-2 text-[#1D4ED8] font-mono text-xs">{inv.invoice_number}</td>
                  <td className="px-3 py-2 text-white text-xs">{inv.rmp_clients?.company_name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#888] text-xs capitalize">{inv.site}</td>
                  <td className="px-3 py-2 text-[#888] text-xs font-mono">{inv.rmp_orders?.internal_order_number ?? '—'}</td>
                  <td className="px-3 py-2 text-green-400 text-xs">{inv.amount_cents ? fmt(inv.amount_cents) : '—'}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${STATUS_COLORS[inv.status] ?? 'bg-[#FFFFFF] text-[#555]'}`}>{inv.status}</span>
                  </td>
                  <td className="px-3 py-2 text-[#888] text-xs">{inv.due_date ?? '—'}</td>
                  <td className="px-3 py-2 text-[#ccc] text-xs">{inv.rmp_sales_staff?.full_name ?? '—'}</td>
                  <td className="px-3 py-2">
                    {inv.status !== 'paid' && inv.status !== 'cancelled' && (
                      <button onClick={() => setMarkPaidId(inv.id)} className="text-xs text-green-400 hover:underline mr-2">Mark Paid</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default function InvoicesPage() {
  return (
    <Suspense fallback={<div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center"><div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" /></div>}>
      <InvoicesContent />
    </Suspense>
  );
}
