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

const statusBadge = s => {
  const map = { confirmed:'badge-success', pending:'badge-warning', failed:'badge-danger', refunded:'badge-gray' };
  return <span className={map[s]||'badge-gray'}>{s}</span>;
};

const init = { invoice_id:'', payment_date:'', amount:'', payment_method:'cash', reference_number:'', notes:'' };

export default function Payments() {
  const [payments, setPayments] = useState([]);
  const [invoices, setInvoices] = 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 load = async () => {
    setLoading(true);
    const [p,i] = await Promise.all([api.get('/api/payments'),api.get('/api/invoices')]);
    setPayments(p.data); setInvoices(i.data.filter(x=>x.status!=='paid'&&x.status!=='cancelled')); setLoading(false);
  };
  useEffect(()=>{load();},[]);

  const openAdd = () => { setForm({...init, payment_date: new Date().toISOString().slice(0,10)}); setModalOpen(true); };

  const handleSubmit = async e => {
    e.preventDefault();
    await api.post('/api/payments', form);
    setModalOpen(false); load();
  };

  const methods = ['cash','bank_transfer','card','mobile_money','cheque'];

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Payments</h1>
        <button className="btn-primary" onClick={openAdd}>+ Record Payment</button>
      </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">Date</th>
                <th className="table-header text-left">Amount</th>
                <th className="table-header text-left">Method</th>
                <th className="table-header text-left">Reference</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {payments.map(p=>{
                  const inv = p.invoice_id;
                  return (
                    <tr key={p.id||p._id} className="table-row">
                      <td className="table-cell font-semibold">{inv?.invoice_number||'—'}</td>
                      <td className="table-cell">{inv?.customer_id?.name||inv?.customer_name||'—'}</td>
                      <td className="table-cell">{p.payment_date?.slice(0,10)}</td>
                      <td className="table-cell font-semibold">KES {Number(p.amount).toLocaleString()}</td>
                      <td className="table-cell capitalize">{p.payment_method?.replace('_',' ')}</td>
                      <td className="table-cell">{p.reference_number||'—'}</td>
                      <td className="table-cell">{statusBadge(p.status)}</td>
                      <td className="table-cell">
                        <button onClick={()=>{setSelectedId(p.id||p._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </td>
                    </tr>
                  );
                })}
                {!payments.length && <tr><td colSpan={8} className="text-center py-10 text-gray-400">No payments recorded</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title="Record Payment" size="md">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Invoice</label>
            <select className="input-field" value={form.invoice_id} onChange={e=>setForm({...form,invoice_id:e.target.value})} required>
              <option value="">-- Select Invoice --</option>
              {invoices.map(i=><option key={i.id||i._id} value={i.id||i._id}>{i.invoice_number} — {i.customer_name||i.customer_id?.name} (KES {Number(i.total_amount).toLocaleString()})</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Payment Date</label>
            <input type="date" className="input-field" value={form.payment_date} onChange={e=>setForm({...form,payment_date:e.target.value})} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Amount (KES)</label>
            <input type="number" step="0.01" className="input-field" value={form.amount} onChange={e=>setForm({...form,amount:e.target.value})} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
            <select className="input-field" value={form.payment_method} onChange={e=>setForm({...form,payment_method:e.target.value})}>
              {methods.map(x=><option key={x}>{x}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Reference Number</label>
            <input className="input-field" value={form.reference_number} onChange={e=>setForm({...form,reference_number:e.target.value})} />
          </div>
          <div>
            <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="flex gap-3 justify-end pt-2">
            <button type="button" className="btn-secondary" onClick={()=>setModalOpen(false)}>Cancel</button>
            <button type="submit" className="btn-primary">Record Payment</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/payments/${selectedId}`);load();}} />
    </div>
  );
}
