import React, { useState, useEffect, useMemo } from 'react';
import {
  Buildings, Plus, PencilSimple, X, Download, MagnifyingGlass,
  Briefcase, CurrencyDollar, ChartLineUp, Warning, ArrowDown,
  ArrowUp, Tag, MapPin, Calendar, Receipt, Trash,
} from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';

const BRAND = '#5D4037';
const fmt = n => n >= 1_000_000 ? `₦${(n/1_000_000).toFixed(1)}M` : n >= 1_000 ? `₦${(n/1_000).toFixed(0)}K` : `₦${Number(n||0).toLocaleString()}`;

const CATEGORIES = [
  { value:'real_estate', label:'Real Estate',  color:'#5D4037' },
  { value:'equipment',   label:'Equipment',    color:'#10b981' },
  { value:'vehicle',     label:'Vehicle',      color:'#f59e0b' },
  { value:'furniture',   label:'Furniture',    color:'#8b5cf6' },
  { value:'technology',  label:'Technology',   color:'#06b6d4' },
  { value:'inventory',   label:'Inventory',    color:'#ec4899' },
  { value:'investment',  label:'Investment',   color:'#14b8a6' },
  { value:'intangible',  label:'Intangible',   color:'#a78bfa' },
  { value:'other',       label:'Other',        color:'#6b7280' },
];

const STATUS = {
  active:      'bg-green-100 text-green-700',
  maintenance: 'bg-amber-100 text-amber-700',
  sold:        'bg-primary-100 text-primary-700',
  disposed:    'bg-red-100 text-red-700',
  retired:     'bg-gray-100 text-gray-500',
};

const catColor = v => CATEGORIES.find(c=>c.value===v)?.color ?? '#6b7280';
const catLabel = v => CATEGORIES.find(c=>c.value===v)?.label ?? v;

const EMPTY = { name:'', category:'equipment', purchase_value:'', current_value:'', purchase_date:'', vendor_name:'', location:'', notes:'', status:'active' };

const Card = ({ children, className='' }) => (
  <div className={`bg-white rounded-2xl border border-gray-100 shadow-sm ${className}`}>{children}</div>
);

const Inp = ({ label, ...props }) => (
  <div>
    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
    <input {...props} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-primary-400 bg-white"/>
  </div>
);

export default function Assets() {
  const [assets,     setAssets]     = useState([]);
  const [loading,    setLoading]    = useState(true);
  const [saving,     setSaving]     = useState(false);
  const [showModal,  setShowModal]  = useState(false);
  const [editing,    setEditing]    = useState(null);
  const [form,       setForm]       = useState(EMPTY);
  const [receipt,    setReceipt]    = useState(null);
  const [search,     setSearch]     = useState('');
  const [catFilter,  setCatFilter]  = useState('');
  const [statFilter, setStatFilter] = useState('');

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

  const load = async () => {
    try { setAssets((await axios.get('/api/company-assets')).data.data || []); }
    catch { toast.error('Failed to load assets'); }
    finally { setLoading(false); }
  };

  const openAdd  = () => { setForm(EMPTY); setEditing(null); setReceipt(null); setShowModal(true); };
  const openEdit = a  => { setForm({ ...a, purchase_date: a.purchase_date?.slice(0,10)||'' }); setEditing(a); setReceipt(null); setShowModal(true); };

  const submit = async (e) => {
    e.preventDefault(); setSaving(true);
    const fd = new FormData();
    Object.entries(form).forEach(([k,v]) => { if (v !== '' && v !== null && v !== undefined) fd.append(k, v); });
    if (receipt) fd.append('receipt', receipt);
    try {
      if (editing) await axios.post(`/api/company-assets/${editing.id}?_method=PUT`, fd, { headers:{'Content-Type':'multipart/form-data'} });
      else         await axios.post('/api/company-assets', fd, { headers:{'Content-Type':'multipart/form-data'} });
      toast.success(editing ? 'Asset updated' : 'Asset added');
      setShowModal(false); load();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const del = async (a) => {
    if (!confirm(`Delete "${a.name}"?`)) return;
    try { await axios.delete(`/api/company-assets/${a.id}`); toast.success('Deleted'); load(); }
    catch { toast.error('Failed to delete'); }
  };

  const filtered = useMemo(() => {
    let list = assets;
    if (catFilter)  list = list.filter(a => a.category === catFilter);
    if (statFilter) list = list.filter(a => a.status   === statFilter);
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(a => (a.name||'').toLowerCase().includes(q) || (a.vendor_name||'').toLowerCase().includes(q) || (a.location||'').toLowerCase().includes(q));
    }
    return list;
  }, [assets, catFilter, statFilter, search]);

  const active   = assets.filter(a => a.status === 'active');
  const totalPV  = active.reduce((s,a) => s + Number(a.purchase_value||0), 0);
  const totalCV  = active.reduce((s,a) => s + Number(a.current_value||a.purchase_value||0), 0);
  const valRatio = totalPV > 0 ? Math.round(((totalCV - totalPV) / totalPV) * 100) : 0;

  const byCat = CATEGORIES.map(c => ({
    ...c,
    count: active.filter(a=>a.category===c.value).length,
    value: active.filter(a=>a.category===c.value).reduce((s,a)=>s+Number(a.current_value||a.purchase_value||0),0),
  })).filter(c => c.count > 0);

  if (loading) return (
    <div className="flex items-center justify-center min-h-screen bg-gray-50">
      <div className="w-12 h-12 rounded-full border-4 border-t-transparent animate-spin" style={{borderColor:`${BRAND}33`,borderTopColor:BRAND}}/>
    </div>
  );

  return (
    <div className="min-h-screen p-6" style={{background:'linear-gradient(135deg,#EFEBE9 0%,#EFEBE9 50%,#F8FAFC 100%)'}}>

      {/* 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">
            <Buildings size={28} weight="duotone" style={{color:BRAND}}/>
            Company Assets
          </h1>
          <p className="text-gray-500 text-sm mt-1">Track, manage and value all company assets</p>
        </div>
        <button onClick={openAdd}
          className="flex items-center gap-2 px-4 py-2 text-white rounded-xl text-sm font-semibold shadow-lg transition-all hover:shadow-xl"
          style={{background:BRAND}}>
          <Plus size={18} weight="bold"/> Add Asset
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        {[
          { icon:Briefcase,     label:'Active Assets',    value: active.length,     color:'#5D4037', suffix:'' },
          { icon:CurrencyDollar,label:'Purchase Value',   value: fmt(totalPV),       color:'#10b981', suffix:'' },
          { icon:ChartLineUp,   label:'Current Value',    value: fmt(totalCV),       color:'#8b5cf6', suffix:'' },
          { icon: valRatio > 0 ? ArrowUp : (valRatio < 0 ? ArrowDown : ChartLineUp), label:'Valuation', value: (valRatio > 0 ? '+' : '') + valRatio, color: valRatio > 0 ? '#10b981' : (valRatio < 0 ? '#ef4444' : '#6b7280'), suffix:'%' },
        ].map((k,i) => (
          <Card key={i} className="p-4 flex items-center gap-3">
            <div className="w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0" style={{background:k.color+'18'}}>
              <k.icon size={22} weight="duotone" style={{color:k.color}}/>
            </div>
            <div>
              <p className="text-xl font-black text-gray-900">{k.value}{k.suffix}</p>
              <p className="text-xs text-gray-500 font-medium uppercase tracking-wide">{k.label}</p>
            </div>
          </Card>
        ))}
      </div>

      {/* Category breakdown */}
      {byCat.length > 0 && (
        <Card className="p-5 mb-6">
          <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-3">Asset Categories</p>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
            {byCat.map(c => (
              <button key={c.value} onClick={()=>setCatFilter(catFilter===c.value?'':c.value)}
                className={`rounded-xl p-3 text-left border-2 transition-all ${catFilter===c.value?'border-current shadow':'border-transparent bg-gray-50 hover:border-gray-200'}`}
                style={catFilter===c.value?{borderColor:c.color,background:c.color+'0f'}:{}}>
                <div className="flex items-center gap-2 mb-1">
                  <span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{background:c.color}}/>
                  <span className="text-xs font-semibold text-gray-700">{c.label}</span>
                </div>
                <p className="text-sm font-black" style={{color:c.color}}>{fmt(c.value)}</p>
                <p className="text-xs text-gray-500">{c.count} item{c.count!==1?'s':''}</p>
              </button>
            ))}
          </div>
        </Card>
      )}

      {/* Filters + Table */}
      <Card>
        {/* Toolbar */}
        <div className="flex flex-wrap items-center gap-3 p-4 border-b border-gray-100">
          <div className="flex-1 min-w-[200px] relative">
            <MagnifyingGlass size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"/>
            <input value={search} onChange={e=>setSearch(e.target.value)}
              placeholder="Search assets…"
              className="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-primary-400"/>
          </div>
          <select value={catFilter} onChange={e=>setCatFilter(e.target.value)}
            className="px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white outline-none focus:ring-2 focus:ring-primary-400">
            <option value="">All Categories</option>
            {CATEGORIES.map(c=><option key={c.value} value={c.value}>{c.label}</option>)}
          </select>
          <select value={statFilter} onChange={e=>setStatFilter(e.target.value)}
            className="px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white outline-none focus:ring-2 focus:ring-primary-400">
            <option value="">All Statuses</option>
            <option value="active">Active</option>
            <option value="maintenance">Maintenance</option>
            <option value="sold">Sold</option>
            <option value="disposed">Disposed</option>
            <option value="retired">Retired</option>
          </select>
          {(search||catFilter||statFilter) && (
            <button onClick={()=>{setSearch('');setCatFilter('');setStatFilter('');}}
              className="px-3 py-2 text-xs text-gray-500 hover:text-red-500 border border-gray-200 rounded-xl">
              Clear
            </button>
          )}
          <span className="text-xs text-gray-400 ml-auto">{filtered.length} of {assets.length} assets</span>
        </div>

        {/* Table */}
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                {['Asset','Category','Purchase Value','Current Value','Valuation','Date','Status','Actions'].map(h=>(
                  <th key={h} className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {filtered.length === 0 && (
                <tr><td colSpan={8} className="px-4 py-12 text-center text-gray-400">
                  {assets.length === 0 ? 'No assets yet. Click "Add Asset" to get started.' : 'No assets match your filters.'}
                </td></tr>
              )}
              {filtered.map(a => {
                const pv   = Number(a.purchase_value||0);
                const cv   = Number(a.current_value||pv);
                const chg  = pv > 0 ? Math.round(((cv - pv) / pv) * 100) : 0;
                const isGain = chg > 0;
                const isLoss = chg < 0;
                return (
                  <tr key={a.id} className="hover:bg-primary-50/40 transition-colors">
                    <td className="px-4 py-3">
                      <div className="font-semibold text-gray-900">{a.name}</div>
                      <div className="flex items-center gap-1 mt-0.5">
                        {a.asset_number && <span className="text-xs text-gray-400 font-mono">{a.asset_number}</span>}
                        {a.vendor_name  && <span className="text-xs text-gray-400">· {a.vendor_name}</span>}
                      </div>
                      {a.location && <div className="flex items-center gap-1 text-xs text-gray-400 mt-0.5"><MapPin size={10}/>{a.location}</div>}
                    </td>
                    <td className="px-4 py-3">
                      <span className="flex items-center gap-1.5">
                        <span className="w-2 h-2 rounded-full" style={{background:catColor(a.category)}}/>
                        <span className="text-gray-700">{catLabel(a.category)}</span>
                      </span>
                    </td>
                    <td className="px-4 py-3 font-semibold text-gray-800">{fmt(pv)}</td>
                    <td className="px-4 py-3 font-bold" style={{color:BRAND}}>{fmt(cv)}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1.5">
                        <div className="flex-1 h-1.5 bg-gray-100 rounded-full overflow-hidden w-16">
                          <div className="h-full rounded-full" style={{width:`${Math.min(Math.abs(chg),100)}%`,background: isGain?'#10b981':isLoss?'#ef4444':'#9ca3af'}}/>
                        </div>
                        <span className={`text-xs font-semibold ${isGain?'text-green-600':isLoss?'text-red-500':'text-gray-500'}`}>{chg > 0 ? '+' : ''}{chg}%</span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-gray-500 whitespace-nowrap">
                      {a.purchase_date ? new Date(a.purchase_date).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'}) : '—'}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${STATUS[a.status]||'bg-gray-100 text-gray-600'}`}>
                        {a.status}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1 justify-end">
                        <button onClick={()=>openEdit(a)}
                          className="p-1.5 rounded-lg hover:bg-primary-100 text-primary-600 transition-colors" title="Edit">
                          <PencilSimple size={15}/>
                        </button>
                        {a.receipt_path && (
                          <a href={`/storage/${a.receipt_path}`} target="_blank" rel="noreferrer"
                            className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-500 transition-colors" title="Receipt">
                            <Download size={15}/>
                          </a>
                        )}
                        <button onClick={()=>del(a)}
                          className="p-1.5 rounded-lg hover:bg-red-100 text-red-400 transition-colors" title="Delete">
                          <Trash size={15}/>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
            {filtered.length > 0 && (
              <tfoot className="bg-gray-50 border-t border-gray-200">
                <tr>
                  <td colSpan={2} className="px-4 py-2 text-xs font-bold text-gray-500">Totals ({filtered.length} items)</td>
                  <td className="px-4 py-2 text-xs font-bold text-gray-700">{fmt(filtered.reduce((s,a)=>s+Number(a.purchase_value||0),0))}</td>
                  <td className="px-4 py-2 text-xs font-bold" style={{color:BRAND}}>{fmt(filtered.reduce((s,a)=>s+Number(a.current_value||a.purchase_value||0),0))}</td>
                  <td colSpan={4}/>
                </tr>
              </tfoot>
            )}
          </table>
        </div>
      </Card>

      {/* Add / Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 overflow-y-auto" onClick={()=>setShowModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg my-4" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between px-5 py-4 rounded-t-2xl" style={{background:BRAND}}>
              <div>
                <h3 className="font-bold text-white">{editing?'Edit':'Add'} Asset</h3>
                <p className="text-primary-200 text-xs">{editing?`#${editing.asset_number}`:'Fill in asset details below'}</p>
              </div>
              <button onClick={()=>setShowModal(false)} className="text-white/70 hover:text-white"><X size={20}/></button>
            </div>
            <form onSubmit={submit} className="p-5 space-y-3">
              <Inp label="Asset Name *" required value={form.name} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="e.g. Dell Laptop, Toyota Hilux"/>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Category *</label>
                <select required 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 outline-none focus:ring-2 focus:ring-primary-400 bg-white">
                  {CATEGORIES.map(c=><option key={c.value} value={c.value}>{c.label}</option>)}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <Inp label="Purchase Value (₦) *" type="number" required min="0" step="0.01" value={form.purchase_value} onChange={e=>setForm(p=>({...p,purchase_value:e.target.value}))}/>
                <Inp label="Current Value (₦)" type="number" min="0" step="0.01" value={form.current_value} onChange={e=>setForm(p=>({...p,current_value:e.target.value}))} placeholder="Defaults to purchase"/>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <Inp label="Purchase Date" type="date" value={form.purchase_date} onChange={e=>setForm(p=>({...p,purchase_date:e.target.value}))}/>
                <Inp label="Vendor / Supplier" value={form.vendor_name} onChange={e=>setForm(p=>({...p,vendor_name:e.target.value}))} placeholder="e.g. Jumia, AutoShop"/>
              </div>
              <Inp label="Location" value={form.location} onChange={e=>setForm(p=>({...p,location:e.target.value}))} placeholder="e.g. Head Office, Warehouse B"/>
              {editing && (
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Status</label>
                  <select value={form.status} onChange={e=>setForm(p=>({...p,status:e.target.value}))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-primary-400 bg-white">
                    <option value="active">Active</option>
                    <option value="maintenance">Under Maintenance</option>
                    <option value="sold">Sold</option>
                    <option value="disposed">Disposed</option>
                    <option value="retired">Retired</option>
                  </select>
                </div>
              )}
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Notes</label>
                <textarea value={form.notes} onChange={e=>setForm(p=>({...p,notes:e.target.value}))} rows={2}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-primary-400 bg-white" placeholder="Optional notes about this asset"/>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Attach Receipt <span className="font-normal text-gray-400">(PDF/JPG/PNG, max 2MB)</span></label>
                <input type="file" accept=".pdf,.jpg,.jpeg,.png" onChange={e=>setReceipt(e.target.files[0])}
                  className="w-full text-sm border border-gray-200 rounded-xl px-3 py-2 file:mr-3 file:py-1 file:px-3 file:rounded-lg file:border-0 file:bg-primary-50 file:text-primary-700 file:text-xs file:font-semibold"/>
              </div>
              <div className="flex gap-2 pt-1">
                <button type="button" onClick={()=>setShowModal(false)}
                  className="flex-1 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={saving}
                  className="flex-1 px-4 py-2 text-white rounded-xl text-sm font-semibold transition-all" style={{background:BRAND}}>
                  {saving ? 'Saving…' : editing ? 'Update Asset' : 'Add Asset'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
