import React, { useEffect, useState, useCallback } from 'react';
import { Receipt, Plus, Clock, CheckCircle, FileText, Upload, X } from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';

const BRAND = '#5D4037';
const CATEGORIES = ['Salary','Operations','Technology','Marketing','Travel','HR','Legal','Finance','Maintenance','Rent/Utilities','Insurance','Supplies','Training','Other'];
const SS = { pending:'bg-yellow-50 text-yellow-700', approved:'bg-green-50 text-green-700', paid:'bg-primary-50 text-primary-700', rejected:'bg-red-50 text-red-700' };

export default function Expenses() {
  const [expenses, setExpenses] = useState([]);
  const [loading, setLoading]   = useState(true);
  const [saving, setSaving]     = useState(false);
  const [filter, setFilter]     = useState('all');
  const [showModal, setShowModal] = useState(false);
  const [receiptFile, setReceiptFile] = useState(null);
  const [form, setForm] = useState({
    title:'', amount:'', category:'Operations', expense_date: new Date().toISOString().split('T')[0],
    vendor_name:'', description:'', status:'submitted', bank_account_id:'',
  });
  const [categories, setCategories] = useState([]);
  const [bankAccounts, setBankAccounts] = useState([]);
  const [previewImage, setPreviewImage] = useState(null);
  const [rejectingExpense, setRejectingExpense] = useState(null);
  const [rejectReason, setRejectReason] = useState('');

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const [expensesRes, bankRes] = await Promise.all([
        axios.get('/api/expenses'),
        axios.get('/api/bank-accounts/list').catch(() => ({ data: { data: [] } })),
      ]);
      setExpenses(expensesRes.data?.data || expensesRes.data || []);
      setBankAccounts(bankRes.data?.data || []);
    } catch { setExpenses([]); }
    finally { setLoading(false); }
  }, []);

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

  const submitExpense = async (e) => {
    e.preventDefault(); setSaving(true);
    const fd = new FormData();
    Object.entries(form).forEach(([k,v]) => { if (v !== '') fd.append(k, v); });
    if (receiptFile) fd.append('receipt', receiptFile);
    try {
      await axios.post('/api/expenses', fd, { headers: { 'Content-Type':'multipart/form-data' } });
      toast.success('Expense recorded successfully');
      setShowModal(false);
      setForm({ title:'', amount:'', category:'Operations', expense_date: new Date().toISOString().split('T')[0], vendor_name:'', description:'', status:'submitted' });
      setReceiptFile(null);
      load();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed to save expense'); }
    finally { setSaving(false); }
  };

  const filtered = filter === 'all' ? expenses : expenses.filter(e => e.status === filter);
  const totalAmount    = expenses.reduce((s,e)=>s+(+e.amount||0),0);
  const approvedAmount = expenses.filter(e=>e.status==='approved').reduce((s,e)=>s+(+e.amount||0),0);
  const pendingAmount  = expenses.filter(e=>e.status==='submitted').reduce((s,e)=>s+(+e.amount||0),0);
  const paidAmount     = expenses.filter(e=>e.status==='paid').reduce((s,e)=>s+(+e.amount||0),0);
  const fmt = v => `₦${Number(v).toLocaleString()}`;

  const statusColor = (status) => {
    switch (status) {
        case 'approved': return 'bg-green-100 text-green-700';
        case 'rejected': return 'bg-red-100 text-red-700';
        case 'paid': return 'bg-primary-100 text-primary-700';
        default: return 'bg-yellow-100 text-yellow-700';
    }
  };

  const handleStatusChange = async (id, status, reason = '') => {
    try {
        await axios.patch(`/api/expenses/${id}/status`, { status, rejection_reason: reason });
        toast.success(`Expense ${status}`);
        load();
        if (status === 'rejected') {
            setRejectingExpense(null);
            setRejectReason('');
        }
    } catch (err) {
        toast.error(err.response?.data?.message || 'Failed to update status');
    }
  };

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center" style={{background:'linear-gradient(135deg,#EFEBE9 0%,#EFEBE9 100%)'}}>
      <div className="w-14 h-14 rounded-full border-4 border-t-transparent animate-spin" style={{borderColor:`${BRAND}22`,borderTopColor:BRAND}}/>
    </div>
  );

  return (
    <div className="p-4 md:p-6" style={{background:'linear-gradient(135deg,#EFEBE9 0%,#EFEBE9 100%)',minHeight:'100vh'}}>
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
            <Receipt size={28} weight="duotone" style={{color:BRAND}}/> Expenses Management
          </h1>
          <p className="text-gray-500 text-sm mt-1">Record and track company expenses with receipts</p>
        </div>
        <button onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2.5 text-white rounded-xl shadow font-semibold text-sm" style={{background:BRAND}}>
          <Plus size={18} weight="bold"/> New Expense
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        {[
          {label:'Total (All Time)',    value:fmt(totalAmount),    sub:`${expenses.length} records`,                                       bg:'#EFEBE9', c:BRAND,      i:Receipt},
          {label:'Approved Amount',     value:fmt(approvedAmount), sub:`${expenses.filter(e=>e.status==='approved').length} approved`,      bg:'#dcfce7', c:'#10b981',  i:CheckCircle},
          {label:'Pending Amount',      value:fmt(pendingAmount),  sub:`${expenses.filter(e=>e.status==='pending').length} awaiting`,       bg:'#fef3c7', c:'#f59e0b',  i:Clock},
          {label:'Paid Amount',         value:fmt(paidAmount),     sub:`${expenses.filter(e=>e.status==='paid').length} paid`,              bg:'#e0e7ff', c:'#6366f1',  i:FileText},
        ].map((k,i)=>(
          <div key={i} className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-medium text-gray-500">{k.label}</span>
              <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{background:k.bg}}>
                <k.i size={16} weight="duotone" style={{color:k.c}}/>
              </div>
            </div>
            <p className="text-xl font-black text-gray-900">{k.value}</p>
            <p className="text-xs text-gray-400 mt-0.5">{k.sub}</p>
          </div>
        ))}
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
        <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
          <h3 className="font-bold text-gray-900 flex items-center gap-2">
            <FileText size={18} weight="duotone" style={{color:BRAND}}/> Expense Records
          </h3>
          <div className="flex gap-1 flex-wrap">
            {['all','submitted','approved','paid','rejected'].map(s=>(
              <button key={s} onClick={()=>setFilter(s)}
                className={`px-3 py-1 rounded-lg text-xs font-semibold capitalize transition-all ${filter===s?'text-white shadow':'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                style={filter===s?{background:BRAND}:{}}>
                {s}
              </button>
            ))}
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead><tr className="border-b border-gray-100">
              {['#','Title / Vendor','Category','Amount','Status','Date','Receipt','Actions'].map(h=>(
                <th key={h} className="text-left py-2 px-3 text-gray-500 font-semibold text-xs uppercase">{h}</th>
              ))}
            </tr></thead>
            <tbody>
              {filtered.map(ex=>(
                <tr key={ex.id} className="border-b border-gray-50 hover:bg-gray-50">
                  <td className="py-3 px-3 font-mono text-xs text-gray-400">{ex.expense_number||`EXP-${ex.id}`}</td>
                  <td className="py-3 px-3">
                    <div className="font-semibold text-gray-900">{ex.title}</div>
                    <div className="text-xs text-gray-400">{ex.vendor_name||'—'}</div>
                  </td>
                  <td className="py-3 px-3">
                    <span className="px-2 py-0.5 rounded-md text-xs font-semibold" style={{background:'#EFEBE9',color:BRAND}}>
                      {ex.category?.name||ex.category||'General'}
                    </span>
                  </td>
                  <td className="py-3 px-3 text-right font-black text-gray-900">₦{(+ex.amount||0).toLocaleString()}</td>
                  <td className="py-3 px-3">
                    <span className={`px-2 py-0.5 rounded-md text-xs font-semibold capitalize ${SS[ex.status]||'bg-gray-50 text-gray-600'}`}>{ex.status}</span>
                  </td>
                  <td className="py-3 px-3 text-gray-500 text-xs">{ex.expense_date?new Date(ex.expense_date).toLocaleDateString():'—'}</td>
                  <td className="py-3 px-3">
                    {ex.receipt_path ? (
                      <a href={`/storage/${ex.receipt_path}`} target="_blank" rel="noreferrer"
                        className="text-xs text-primary-600 underline flex items-center gap-1">
                        <FileText size={12}/> View
                      </a>
                    ) : <span className="text-gray-300 text-xs">—</span>}
                  </td>
                  <td className="py-3 px-3">
                    {ex.status === 'submitted' && (
                      <div className="flex gap-2">
                        <button onClick={() => handleStatusChange(ex.id, 'approved')} className={`px-3 py-1 rounded-lg text-xs font-semibold capitalize transition-all ${statusColor('approved')}`}>Approve</button>
                        <button onClick={() => setRejectingExpense(ex.id)} className={`px-3 py-1 rounded-lg text-xs font-semibold capitalize transition-all ${statusColor('rejected')}`}>Reject</button>
                      </div>
                    )}
                    {ex.status === 'approved' && (
                      <button onClick={() => handleStatusChange(ex.id, 'paid')} className={`px-3 py-1 rounded-lg text-xs font-semibold capitalize transition-all ${statusColor('paid')}`}>Pay</button>
                    )}
                    {rejectingExpense === ex.id && (
                      <div className="flex gap-2">
                        <input type="text" value={rejectReason} onChange={e => setRejectReason(e.target.value)} className="px-3 py-1 rounded-lg text-xs font-semibold border border-gray-200" placeholder="Reason for rejection" />
                        <button onClick={() => handleStatusChange(ex.id, 'rejected', rejectReason)} className={`px-3 py-1 rounded-lg text-xs font-semibold capitalize transition-all ${statusColor('rejected')}`}>Reject</button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length===0&&(
            <div className="py-12 text-center text-gray-400">
              <Receipt size={40} weight="duotone" className="mx-auto mb-2 opacity-40"/>
              <p className="text-sm">No expenses found</p>
            </div>
          )}
        </div>
      </div>

      {/* New Expense Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setShowModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xl max-h-[90vh] overflow-y-auto" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 rounded-t-2xl" style={{background:BRAND}}>
              <h2 className="text-lg font-bold text-white flex items-center gap-2"><Receipt size={20}/> New Expense</h2>
              <button onClick={()=>setShowModal(false)} className="text-white/70 hover:text-white"><X size={20}/></button>
            </div>
            <form onSubmit={submitExpense} className="p-5 grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <label className="block text-xs font-semibold text-gray-600 mb-1">Expense Title *</label>
                <input required value={form.title} onChange={e=>setForm(p=>({...p,title:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                  placeholder="e.g. Office Supplies"/>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Amount (NGN) *</label>
                <input type="number" min="0.01" step="0.01" required value={form.amount} onChange={e=>setForm(p=>({...p,amount:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none" placeholder="50000"/>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Category</label>
                <select value={form.category} onChange={e=>setForm(p=>({...p,category:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white">
                  {CATEGORIES.map(c=><option key={c}>{c}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Bank Account</label>
                <select value={form.bank_account_id} onChange={e=>setForm(p=>({...p,bank_account_id:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white">
                  <option value="">Select bank account</option>
                  {bankAccounts.map(ba=>(
                    <option key={ba.id} value={ba.id}>
                      {ba.account_name} - {ba.bank_name} ({ba.account_number})
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Expense Date</label>
                <input type="date" value={form.expense_date} onChange={e=>setForm(p=>({...p,expense_date:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none"/>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Vendor / Supplier</label>
                <input value={form.vendor_name} onChange={e=>setForm(p=>({...p,vendor_name:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none" placeholder="Vendor name"/>
              </div>
              <div className="md:col-span-2">
                <label className="block text-xs font-semibold text-gray-600 mb-1">Description</label>
                <textarea rows={2} value={form.description} onChange={e=>setForm(p=>({...p,description:e.target.value}))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                  placeholder="Additional details…"/>
              </div>
              <div className="md:col-span-2">
                <label className="block text-xs font-semibold text-gray-600 mb-1">Receipt / Invoice (optional)</label>
                <div className="border-2 border-dashed border-gray-200 rounded-xl p-4 text-center hover:border-primary-400 transition-colors">
                  <input type="file" accept=".pdf,.jpg,.jpeg,.png" id="exp-receipt" className="hidden"
                    onChange={e=>setReceiptFile(e.target.files[0])}/>
                  <label htmlFor="exp-receipt" className="cursor-pointer">
                    <Upload size={22} className="mx-auto text-gray-400 mb-1"/>
                    <p className="text-sm text-gray-600">{receiptFile ? receiptFile.name : 'Click to upload receipt or invoice'}</p>
                    <p className="text-xs text-gray-400 mt-0.5">PDF, JPG, PNG · max 5 MB</p>
                  </label>
                </div>
              </div>
              <div className="md:col-span-2 flex justify-end gap-2 pt-2">
                <button type="button" onClick={()=>setShowModal(false)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:BRAND}}>
                  {saving ? 'Saving…' : 'Save Expense'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
