import React, { useEffect, useState } from 'react';
import api from '../hooks/api';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';
import StatCard from '../components/StatCard';

const statusBadge = s => {
  const map = { draft:'badge-gray', sent:'badge-info', paid:'badge-success', overdue:'badge-danger', cancelled:'badge-gray' };
  return <span className={map[s]||'badge-gray'}>{s}</span>;
};

const init = { invoice_number:'', customer_id:'', trip_id:'', issue_date:'', due_date:'', subtotal:'', tax_rate:16, tax_amount:'', discount:'', total_amount:'', notes:'' };

export default function Invoices() {
  const [invoices, setInvoices] = useState([]);
  const [stats, setStats] = useState({});
  const [customers, setCustomers] = useState([]);
  const [trips, setTrips] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [form, setForm] = useState(init);
  const [editing, setEditing] = useState(false);

  const load = async () => {
    setLoading(true);
    const [i,s,c,t] = await Promise.all([api.get('/api/invoices'),api.get('/api/invoices/stats'),api.get('/api/customers'),api.get('/api/trips')]);
    setInvoices(i.data); setStats(s.data); setCustomers(c.data); setTrips(t.data); setLoading(false);
  };
  useEffect(()=>{load();},[]);

  const calcTotal = (subtotal, tax_rate, discount) => {
    const sub = parseFloat(subtotal)||0;
    const tax = (sub * (parseFloat(tax_rate)||0)) / 100;
    const disc = parseFloat(discount)||0;
    return (sub + tax - disc).toFixed(2);
  };

  const openAdd = () => {
    const num = `INV-${Date.now().toString().slice(-6)}`;
    const today = new Date().toISOString().slice(0,10);
    const due = new Date(Date.now()+30*86400000).toISOString().slice(0,10);
    setForm({...init, invoice_number:num, issue_date:today, due_date:due}); setEditing(false); setModalOpen(true);
  };
  const openEdit = i => { setForm({...i, customer_id:i.customer_id?._id||i.customer_id, trip_id:i.trip_id?._id||i.trip_id||'', issue_date:i.issue_date?.slice(0,10), due_date:i.due_date?.slice(0,10)}); setEditing(true); setSelectedId(i.id||i._id); setModalOpen(true); };

  const handleSubmit = async e => {
    e.preventDefault();
    const tax_amount = ((parseFloat(form.subtotal)||0) * (parseFloat(form.tax_rate)||0)) / 100;
    const total_amount = form.total_amount || calcTotal(form.subtotal, form.tax_rate, form.discount);
    const payload = {...form, tax_amount, total_amount};
    if (editing) await api.put(`/api/invoices/${selectedId}`, payload);
    else await api.post('/api/invoices', payload);
    setModalOpen(false); load();
  };

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Invoices</h1>
        <button className="btn-primary" onClick={openAdd}>+ Create Invoice</button>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard label="Total Invoices" value={stats.total} icon="📄" color="blue" />
        <StatCard label="Paid" value={stats.paid} icon="✅" color="green" />
        <StatCard label="Overdue" value={stats.overdue} icon="⚠️" color="red" />
        <StatCard label="Revenue" value={`KES ${Number(stats.paid_amount||0).toLocaleString()}`} icon="💰" color="purple" />
      </div>
      <div className="card">
        <div className="overflow-x-auto">
          {loading ? <div className="text-center py-10"><div className="animate-spin inline-block rounded-full h-8 w-8 border-b-2 border-blue-600"></div></div> : (
            <table className="w-full">
              <thead><tr>
                <th className="table-header text-left">Invoice #</th>
                <th className="table-header text-left">Customer</th>
                <th className="table-header text-left">Issue Date</th>
                <th className="table-header text-left">Due Date</th>
                <th className="table-header text-left">Amount</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {invoices.map(i=>(
                  <tr key={i.id||i._id} className="table-row">
                    <td className="table-cell font-semibold">{i.invoice_number}</td>
                    <td className="table-cell">{i.customer_name||i.customer_id?.name}</td>
                    <td className="table-cell">{i.issue_date?.slice(0,10)}</td>
                    <td className="table-cell">{i.due_date?.slice(0,10)}</td>
                    <td className="table-cell font-semibold">KES {Number(i.total_amount).toLocaleString()}</td>
                    <td className="table-cell">{statusBadge(i.status)}</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={()=>openEdit(i)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={()=>{setSelectedId(i.id||i._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!invoices.length && <tr><td colSpan={7} className="text-center py-10 text-gray-400">No invoices found</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title={editing?'Edit Invoice':'Create Invoice'} size="lg">
        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Invoice Number</label>
            <input className="input-field" value={form.invoice_number} onChange={e=>setForm({...form,invoice_number:e.target.value})} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Customer</label>
            <select className="input-field" value={form.customer_id} onChange={e=>setForm({...form,customer_id:e.target.value})} required>
              <option value="">-- Select --</option>
              {customers.map(c=><option key={c.id||c._id} value={c.id||c._id}>{c.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Trip (optional)</label>
            <select className="input-field" value={form.trip_id||''} onChange={e=>setForm({...form,trip_id:e.target.value})}>
              <option value="">-- None --</option>
              {trips.map(t=><option key={t.id||t._id} value={t.id||t._id}>{t.trip_code}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Issue Date</label>
            <input type="date" className="input-field" value={form.issue_date||''} onChange={e=>setForm({...form,issue_date:e.target.value})} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Due Date</label>
            <input type="date" className="input-field" value={form.due_date||''} onChange={e=>setForm({...form,due_date:e.target.value})} required />
          </div>
          {[['subtotal','Subtotal (KES)'],['tax_rate','Tax Rate (%)'],['discount','Discount (KES)']].map(([k,l])=>(
            <div key={k}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <input type="number" step="0.01" className="input-field" value={form[k]||''} onChange={e=>{
                const upd={...form,[k]:e.target.value};
                upd.total_amount = calcTotal(upd.subtotal, upd.tax_rate, upd.discount);
                setForm(upd);
              }} />
            </div>
          ))}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Total Amount (KES)</label>
            <input type="number" step="0.01" className="input-field bg-gray-50" value={form.total_amount||''} onChange={e=>setForm({...form,total_amount:e.target.value})} />
          </div>
          {editing && <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select className="input-field" value={form.status||'draft'} onChange={e=>setForm({...form,status:e.target.value})}>
              {['draft','sent','paid','overdue','cancelled'].map(x=><option key={x}>{x}</option>)}
            </select>
          </div>}
          <div className="col-span-2">
            <label className="block text-sm font-medium text-gray-700 mb-1">Notes</label>
            <textarea className="input-field" rows={2} value={form.notes||''} onChange={e=>setForm({...form,notes:e.target.value})} />
          </div>
          <div className="col-span-2 flex gap-3 justify-end mt-2">
            <button type="button" className="btn-secondary" onClick={()=>setModalOpen(false)}>Cancel</button>
            <button type="submit" className="btn-primary">{editing?'Update':'Create Invoice'}</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/invoices/${selectedId}`);load();}} />
    </div>
  );
}
