import React, { useEffect, useState } from 'react';
import { Wallet, TrendUp, TrendDown, ArrowsLeftRight, CurrencyDollar,
  Buildings, ChartLineUp, ArrowRight, Spinner } from '@phosphor-icons/react';
import { AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import axios from 'axios';
import { Link } from 'react-router-dom';

const BRAND  = '#5D4037';
const COLORS = ['#5D4037','#6D4C41','#A1887F','#10b981','#f59e0b','#ec4899'];

const fmt  = v => `₦${Number(v||0).toLocaleString()}`;
const fmtM = v => { const n = Number(v||0); return n >= 1e6 ? `₦${(n/1e6).toFixed(2)}M` : n >= 1e3 ? `₦${(n/1e3).toFixed(0)}K` : `₦${n.toLocaleString()}`; };

export default function Treasury() {
  const [data, setData]     = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get('/api/treasury')
      .then(r => setData(r.data))
      .catch(() => setData(null))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return (
    <div className="flex items-center justify-center h-64">
      <div className="flex flex-col items-center gap-3">
        <div className="w-12 h-12 rounded-full border-4 border-t-transparent animate-spin" style={{ borderColor:`${BRAND}33`, borderTopColor:BRAND }} />
        <p className="text-sm text-gray-500">Loading treasury data…</p>
      </div>
    </div>
  );

  const k    = data?.kpis   || {};
  const flow = data?.cash_flow || [];
  const alloc= data?.allocation || [];
  const cos  = data?.companies  || [];
  const txs  = data?.recent_tx  || [];

  const healthColor = { excellent:'#16a34a', good:'#5D4037', fair:'#f59e0b', poor:'#ef4444', critical:'#dc2626' };

  return (
    <div className="space-y-6 fade-in">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-extrabold text-gray-900 flex items-center gap-3">
            <Wallet size={30} weight="duotone" style={{ color: BRAND }} />
            Treasury & Cash Management
          </h1>
          <p className="text-sm text-gray-500 mt-0.5">
            Group-wide financial position across {data?.company_count || 0} companies
          </p>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
          <span className="text-xs text-gray-500 font-medium">Live data</span>
        </div>
      </div>

      {/* KPI Row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label:'Total Group Assets', value:fmtM(k.total_assets),  icon:TrendUp,        color:BRAND },
          { label:'Total Liabilities',  value:fmtM(k.total_liab),    icon:TrendDown,      color:'#dc2626' },
          { label:'Net Position',       value:fmtM(k.net_position),   icon:ChartLineUp,    color:'#16a34a' },
          { label:'Cash Available',     value:fmtM(k.total_cash),     icon:CurrencyDollar, color:'#d97706' },
        ].map((ki,i) => (
          <div key={i} className="kpi-card">
            <div className="flex items-start justify-between mb-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: ki.color+'18' }}>
                <ki.icon size={22} weight="duotone" style={{ color: ki.color }} />
              </div>
            </div>
            <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">{ki.label}</p>
            <p className="text-2xl font-extrabold text-gray-900">{ki.value}</p>
          </div>
        ))}
      </div>

      {/* Revenue & Expenses summary */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="kpi-card border-l-4" style={{ borderLeftColor: BRAND }}>
          <p className="text-xs text-gray-400 uppercase font-semibold mb-1">Total Group Revenue</p>
          <p className="text-2xl font-extrabold text-gray-900">{fmtM(k.total_revenue)}</p>
        </div>
        <div className="kpi-card border-l-4 border-l-red-400">
          <p className="text-xs text-gray-400 uppercase font-semibold mb-1">Total Group Expenses</p>
          <p className="text-2xl font-extrabold text-gray-900">{fmtM(k.total_expenses)}</p>
        </div>
        <div className="kpi-card border-l-4 border-l-green-500">
          <p className="text-xs text-gray-400 uppercase font-semibold mb-1">Net Group Profit</p>
          <p className={`text-2xl font-extrabold ${(k.net_profit||0) >= 0 ? 'text-green-700' : 'text-red-600'}`}>{fmtM(k.net_profit)}</p>
        </div>
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Cash Flow */}
        <div className="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="font-bold text-gray-900 flex items-center gap-2">
              <ArrowsLeftRight size={20} weight="duotone" style={{ color: BRAND }} />
              Cash Inflow vs Outflow
            </h3>
            <span className="text-xs bg-primary-50 text-primary-600 px-3 py-1 rounded-full font-semibold">Last 6 months</span>
          </div>
          {flow.length === 0 ? (
            <div className="flex items-center justify-center h-48 text-gray-400 text-sm">No cash flow data yet</div>
          ) : (
            <ResponsiveContainer width="100%" height={260}>
              <AreaChart data={flow}>
                <defs>
                  <linearGradient id="inGrad"  x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor={BRAND}     stopOpacity={0.25} />
                    <stop offset="95%" stopColor={BRAND}     stopOpacity={0} />
                  </linearGradient>
                  <linearGradient id="outGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor="#dc2626" stopOpacity={0.15} />
                    <stop offset="95%" stopColor="#dc2626" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="month" style={{ fontSize:12 }} stroke="#9ca3af" />
                <YAxis style={{ fontSize:12 }} stroke="#9ca3af" tickFormatter={v=>`₦${(v/1000).toFixed(0)}K`} />
                <Tooltip formatter={v=>`₦${Number(v).toLocaleString()}`} contentStyle={{ borderRadius:'12px', fontSize:12 }} />
                <Area type="monotone" dataKey="inflow"  name="Inflow"  stroke={BRAND}   strokeWidth={2.5} fill="url(#inGrad)" />
                <Area type="monotone" dataKey="outflow" name="Outflow" stroke="#dc2626" strokeWidth={2}   fill="url(#outGrad)" />
              </AreaChart>
            </ResponsiveContainer>
          )}
        </div>

        {/* Expense Allocation */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-bold text-gray-900 mb-4">Expense Allocation</h3>
          {alloc.length === 0 ? (
            <div className="flex items-center justify-center h-40 text-gray-400 text-sm">No category data</div>
          ) : (
            <>
              <ResponsiveContainer width="100%" height={180}>
                <PieChart>
                  <Pie data={alloc} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={3} dataKey="value">
                    {alloc.map((_,i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Tooltip formatter={(v,n,p) => [`${v}% (${fmt(p.payload.amount)})`, p.payload.name]} contentStyle={{ borderRadius:'10px', fontSize:12 }} />
                </PieChart>
              </ResponsiveContainer>
              <div className="mt-2 space-y-1">
                {alloc.map((d,i) => (
                  <div key={i} className="flex items-center justify-between text-xs">
                    <div className="flex items-center gap-2">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ background: COLORS[i % COLORS.length] }} />
                      <span className="text-gray-600">{d.name}</span>
                    </div>
                    <span className="font-bold text-gray-900">{d.value}%</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </div>

      {/* Company Breakdown */}
      {cos.length > 0 && (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-5">
            <h3 className="font-bold text-gray-900 flex items-center gap-2">
              <Buildings size={20} weight="duotone" style={{ color: BRAND }} />
              Company Financial Breakdown
            </h3>
            <Link to="/companies" className="text-xs bg-primary-50 text-primary-600 px-3 py-1 rounded-full font-semibold hover:bg-primary-100">
              Manage
            </Link>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-100">
                  {['Company','Revenue','Expenses','Net Profit','Cash','Assets','Health'].map(h => (
                    <th key={h} className="text-left py-2 px-3 text-gray-400 font-semibold text-xs uppercase">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {cos.map(c => {
                  const net = (c.revenue||0) - (c.expenses||0);
                  const hc  = healthColor[c.status] || '#6b7280';
                  return (
                    <tr key={c.id} className="border-b border-gray-50 hover:bg-primary-50/30 transition-colors">
                      <td className="py-3 px-3">
                        <Link to={`/companies/${c.id}`} className="font-semibold text-gray-900 hover:text-primary-600">{c.name}</Link>
                      </td>
                      <td className="py-3 px-3 font-semibold text-gray-800">{c.revenue > 0 ? fmt(c.revenue) : '—'}</td>
                      <td className="py-3 px-3 text-red-600">{c.expenses > 0 ? fmt(c.expenses) : '—'}</td>
                      <td className={`py-3 px-3 font-bold ${net >= 0 ? 'text-green-600' : 'text-red-600'}`}>{fmt(net)}</td>
                      <td className="py-3 px-3 text-gray-700">{c.cash > 0 ? fmt(c.cash) : '—'}</td>
                      <td className="py-3 px-3 text-gray-700">{c.assets > 0 ? fmt(c.assets) : '—'}</td>
                      <td className="py-3 px-3">
                        <span className="text-xs font-semibold capitalize" style={{ color: hc }}>{c.status}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Recent Transactions */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <h3 className="font-bold text-gray-900 mb-4">Recent Treasury Transactions</h3>
        {txs.length === 0 ? (
          <p className="text-sm text-gray-400 py-4 text-center">No transactions recorded yet</p>
        ) : (
          <div className="space-y-2">
            {txs.map(tx => (
              <div key={tx.id} className="flex items-center gap-4 p-3 rounded-xl hover:bg-gray-50 transition-colors">
                <div className={`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 ${tx.type==='credit' ? 'bg-green-50' : 'bg-red-50'}`}>
                  {tx.type==='credit'
                    ? <TrendUp  size={18} className="text-green-600" weight="duotone" />
                    : <TrendDown size={18} className="text-red-500" weight="duotone" />}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-gray-900 truncate">{tx.desc}</p>
                  <p className="text-xs text-gray-400">{tx.date}</p>
                </div>
                <div className="text-right">
                  <p className={`font-bold text-sm ${tx.type==='credit' ? 'text-green-600' : 'text-red-600'}`}>
                    {tx.type==='credit' ? '+' : ''}{fmt(Math.abs(tx.amount))}
                  </p>
                  <span className={`text-xs font-medium capitalize ${tx.status==='completed' ? 'text-green-600' : 'text-amber-600'}`}>
                    {tx.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
