import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    CurrencyDollar, TrendUp, TrendDown, Wallet, Receipt,
    Users, Buildings, ChartLine, ChartPieSlice, ArrowUp, ArrowDown,
    CalendarBlank, Bank, Briefcase, ShieldCheck, Warning, CheckCircle,
    ChartBar, Lightning, ArrowSquareOut
} from '@phosphor-icons/react';
import toast from 'react-hot-toast';
import {
    AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
    LineChart, Line, RadarChart, Radar, PolarGrid, PolarAngleAxis,
    XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend
} from 'recharts';
import axios from 'axios';

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

const fmt = (n) => {
    if (n >= 1_000_000) return `₦${(n/1_000_000).toFixed(1)}M`;
    if (n >= 1_000)    return `₦${(n/1_000).toFixed(0)}K`;
    return `₦${Number(n).toLocaleString()}`;
};

const GlassCard = ({ children, className = '', onClick, ...rest }) => (
    <div className={`rounded-2xl border border-white border-opacity-30 shadow-xl ${className}`}
         style={{ background: 'rgba(255,255,255,0.85)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)' }}
         onClick={onClick} {...rest}>
        {children}
    </div>
);

const KPICard = ({ icon: Icon, label, value, change, iconBg, suffix = '', onClick, hint }) => {
    const up = change >= 0;
    return (
        <GlassCard className={`p-5 ${onClick ? 'cursor-pointer hover:shadow-2xl transition-shadow' : ''}`} onClick={onClick}>
            <div className="flex items-start justify-between mb-3">
                <div className="w-11 h-11 rounded-xl flex items-center justify-center" style={{ background: iconBg + '22' }}>
                    <Icon size={22} weight="duotone" style={{ color: iconBg }} />
                </div>
                {change !== undefined && (
                    <span className={`flex items-center gap-1 text-xs font-semibold px-2 py-1 rounded-full ${up ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}`}>
                        {up ? <ArrowUp size={10} weight="bold" /> : <ArrowDown size={10} weight="bold" />}
                        {Math.abs(change).toFixed(1)}%
                    </span>
                )}
            </div>
            <p className="text-2xl font-black text-gray-900 tracking-tight">{value}{suffix}</p>
            <p className="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wider">{label}</p>
            {hint && <p className="text-xs text-primary-500 mt-1 flex items-center gap-1"><ArrowSquareOut size={10}/>{hint}</p>}
        </GlassCard>
    );
};

const fmtDT = (d) => d ? new Date(d).toLocaleString('en-GB', { day:'2-digit', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' }) : '—';
const FIELD_LABELS = {};

export default function CompanyDashboard() {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(true);
    const [data, setData] = useState(null);
    const [range, setRange] = useState('90');
    useEffect(() => { fetchData(); }, [range]);

    const fetchData = async () => {
        try {
            setLoading(true);
            const res = await axios.get(`/api/dashboard/company?range=${range}`);
            setData(res.data);
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };


    const s = data?.stats || {};
    const revenueData = data?.revenueData || [];
    const expenseData = data?.expenseData || [];
    const assetData   = data?.assetData   || [];
    const deptData    = data?.deptData    || [];
    const payrollData = data?.payrollData || [];

    const healthColor = (status) => ({ excellent:'#10b981', good:'#5D4037', fair:'#f59e0b', poor:'#f97316', critical:'#dc2626' }[status] || '#6b7280');

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center" style={{ background:'linear-gradient(135deg,#EFEBE9 0%,#EFEBE9 100%)' }}>
                <div className="text-center">
                    <div className="w-16 h-16 rounded-full border-4 border-t-transparent mx-auto animate-spin" style={{ borderColor:`${BRAND}33`, borderTopColor: BRAND }} />
                    <p className="mt-4 text-sm text-gray-500 font-medium">Loading financial data…</p>
                </div>
            </div>
        );
    }

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

            {/* ── Header ─────────────────────────────────────────── */}
            <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
                        <ChartLine size={28} weight="duotone" style={{ color: BRAND }} />
                        {s.companyName || 'Company'} — Financial Overview
                    </h1>
                    <p className="text-gray-500 text-sm mt-1">Live analytics · Updated just now</p>
                </div>
                <div className="flex items-center gap-3">
                    <select value={range} onChange={e => setRange(e.target.value)}
                        className="px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white shadow-sm focus:ring-2 focus:border-transparent"
                        style={{ '--tw-ring-color': BRAND }}>
                        <option value="30">Last 30 days</option>
                        <option value="90">Last 90 days</option>
                        <option value="180">Last 6 months</option>
                        <option value="365">Last year</option>
                    </select>
                    <button onClick={fetchData}
                        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 }}>
                        <CalendarBlank size={16} weight="bold" /> Refresh
                    </button>
                </div>
            </div>

            {/* ── KPI Cards ──────────────────────────────────────── */}
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
                <KPICard icon={CurrencyDollar} label="Revenue"     value={fmt(s.totalRevenue || 0)}  change={s.revenueChange}   iconBg={BRAND} />
                <KPICard icon={TrendUp}        label="Net Profit"   value={fmt(s.netProfit || 0)}     change={s.profitChange}    iconBg="#10b981" />
                <KPICard icon={Receipt}        label="Expenses"     value={fmt(s.totalExpenses || 0)} change={s.expensesChange}  iconBg="#ef4444"   onClick={()=>navigate('/expenses')} hint="Go to Expenses" />
                <KPICard icon={Wallet}         label="Cash Balance" value={fmt(s.cashBalance || 0)}   change={s.cashChange}      iconBg="#f59e0b" />
                <KPICard icon={Briefcase}      label="Total Assets" value={fmt(s.totalAssets || 0)}   change={s.assetsChange}    iconBg="#8b5cf6"   onClick={()=>navigate('/assets')}   hint="Go to Assets" />
                <KPICard icon={Users}          label="Employees"    value={s.activeEmployees || 0}    change={s.employeesChange} iconBg="#06b6d4"   onClick={()=>navigate('/employees')} hint="View all" />
            </div>

            {/* ── Row 2: Revenue Trend + Expense Pie ─────────────── */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">
                <GlassCard className="lg:col-span-2 p-5">
                    <div className="flex items-center gap-2 mb-4">
                        <ChartLine size={20} weight="duotone" style={{ color: BRAND }} />
                        <h3 className="font-bold text-gray-800">Revenue vs Expenses — 6-Month Trend</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={260}>
                        <AreaChart data={revenueData} margin={{ top:5, right:10, left:0, bottom:0 }}>
                            <defs>
                                <linearGradient id="gradRev" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor={BRAND} stopOpacity={0.18}/>
                                    <stop offset="95%" stopColor={BRAND} stopOpacity={0}/>
                                </linearGradient>
                                <linearGradient id="gradExp" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="#ef4444" stopOpacity={0.15}/>
                                    <stop offset="95%" stopColor="#ef4444" stopOpacity={0}/>
                                </linearGradient>
                                <linearGradient id="gradPro" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="#10b981" stopOpacity={0.15}/>
                                    <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                                </linearGradient>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" stroke="#EFEBE9" />
                            <XAxis dataKey="month" tick={{ fontSize:11, fill:'#9ca3af' }} axisLine={false} tickLine={false} />
                            <YAxis tickFormatter={v=>`₦${(v/1000).toFixed(0)}K`} tick={{ fontSize:10, fill:'#9ca3af' }} axisLine={false} tickLine={false} />
                            <Tooltip formatter={(v,n)=>[`₦${Number(v).toLocaleString()}`,n]} contentStyle={{ borderRadius:12, border:'none', boxShadow:'0 8px 32px rgba(25,25,230,0.1)' }} />
                            <Legend />
                            <Area type="monotone" dataKey="revenue"  name="Revenue"  stroke={BRAND}    fill="url(#gradRev)" strokeWidth={2.5} dot={false} />
                            <Area type="monotone" dataKey="expenses" name="Expenses" stroke="#ef4444"  fill="url(#gradExp)" strokeWidth={2} dot={false} />
                            <Area type="monotone" dataKey="profit"   name="Profit"   stroke="#10b981"  fill="url(#gradPro)" strokeWidth={2} dot={false} strokeDasharray="5 3" />
                        </AreaChart>
                    </ResponsiveContainer>
                </GlassCard>

                <GlassCard className="p-5">
                    <div className="flex items-center gap-2 mb-4">
                        <ChartPieSlice size={20} weight="duotone" style={{ color:'#8b5cf6' }} />
                        <h3 className="font-bold text-gray-800">Expense Breakdown</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={180}>
                        <PieChart>
                            <Pie data={expenseData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={3} dataKey="value" nameKey="name">
                                {expenseData.map((e,i) => <Cell key={i} fill={e.color || COLORS[i % COLORS.length]} />)}
                            </Pie>
                            <Tooltip formatter={(v,n)=>[`₦${Number(v).toLocaleString()}`,n]} contentStyle={{ borderRadius:10, border:'none' }} />
                        </PieChart>
                    </ResponsiveContainer>
                    <div className="space-y-1 mt-2">
                        {expenseData.slice(0,5).map((e,i) => (
                            <div key={i} className="flex items-center justify-between text-xs">
                                <span className="flex items-center gap-1.5">
                                    <span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ background: e.color || COLORS[i%COLORS.length] }} />
                                    <span className="text-gray-600">{e.name}</span>
                                </span>
                                <span className="font-semibold text-gray-800">₦{Number(e.value).toLocaleString()}</span>
                            </div>
                        ))}
                    </div>
                </GlassCard>
            </div>

            {/* ── Row 3: Asset Allocation + Dept Headcount ─────── */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mb-5">
                <GlassCard className="p-5">
                    <div className="flex items-center gap-2 mb-4">
                        <Briefcase size={20} weight="duotone" style={{ color:'#10b981' }} />
                        <h3 className="font-bold text-gray-800">Asset Allocation vs Target</h3>
                    </div>
                    <div className="space-y-3">
                        {assetData.map((a, i) => {
                            const pct = Math.min(Math.round((a.current / (a.target || 1)) * 100), 100);
                            return (
                                <div key={i}>
                                    <div className="flex justify-between text-xs mb-1">
                                        <span className="text-gray-600 font-medium">{a.category}</span>
                                        <span className="text-gray-800 font-bold">{fmt(a.current)} <span className="text-gray-400 font-normal">/ {fmt(a.target)}</span></span>
                                    </div>
                                    <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                                        <div className="h-full rounded-full transition-all duration-700"
                                             style={{ width:`${pct}%`, background: pct >= 90 ? '#10b981' : pct >= 70 ? BRAND : '#f59e0b' }} />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </GlassCard>

                <GlassCard className="p-5">
                    <div className="flex items-center gap-2 mb-4">
                        <Users size={20} weight="duotone" style={{ color:'#06b6d4' }} />
                        <h3 className="font-bold text-gray-800">Headcount by Department</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={220}>
                        <BarChart data={deptData} layout="vertical" margin={{ left:10, right:20 }}>
                            <CartesianGrid strokeDasharray="3 3" stroke="#EFEBE9" horizontal={false} />
                            <XAxis type="number" tick={{ fontSize:10, fill:'#9ca3af' }} axisLine={false} tickLine={false} />
                            <YAxis type="category" dataKey="name" tick={{ fontSize:10, fill:'#6b7280' }} axisLine={false} tickLine={false} width={100} />
                            <Tooltip contentStyle={{ borderRadius:10, border:'none' }} />
                            <Bar dataKey="count" name="Employees" fill={BRAND} radius={[0,6,6,0]}>
                                {deptData.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                            </Bar>
                        </BarChart>
                    </ResponsiveContainer>
                </GlassCard>
            </div>

            {/* ── Row 4: Payroll Trend + Financial Health ─────────── */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">
                <GlassCard className="lg:col-span-2 p-5">
                    <div className="flex items-center gap-2 mb-4">
                        <ChartBar size={20} weight="duotone" style={{ color:'#f59e0b' }} />
                        <h3 className="font-bold text-gray-800">Monthly Payroll Cost</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={200}>
                        <BarChart data={payrollData} margin={{ top:5, right:10, left:0, bottom:0 }}>
                            <CartesianGrid strokeDasharray="3 3" stroke="#EFEBE9" />
                            <XAxis dataKey="month" tick={{ fontSize:11, fill:'#9ca3af' }} axisLine={false} tickLine={false} />
                            <YAxis tickFormatter={v=>`₦${(v/1000).toFixed(0)}K`} tick={{ fontSize:10, fill:'#9ca3af' }} axisLine={false} tickLine={false} />
                            <Tooltip formatter={(v)=>[`₦${Number(v).toLocaleString()}`,'Payroll']} contentStyle={{ borderRadius:12, border:'none' }} />
                            <Bar dataKey="amount" name="Payroll" fill="#f59e0b" radius={[6,6,0,0]} />
                        </BarChart>
                    </ResponsiveContainer>
                </GlassCard>

                <GlassCard className="p-5">
                    <div className="flex items-center gap-2 mb-4">
                        <Lightning size={20} weight="duotone" style={{ color: BRAND }} />
                        <h3 className="font-bold text-gray-800">Financial Health</h3>
                    </div>
                    <div className="space-y-4">
                        {[
                            { label: 'Liquidity Ratio',    value: (s.liquidityRatio||1.5).toFixed(2), suffix:'x', good: s.liquidityRatio >= 1.5, pct: Math.min(((s.liquidityRatio||1.5)/3)*100,100), color:'#10b981' },
                            { label: 'Profit Margin',      value: (s.profitMargin||23).toFixed(1),    suffix:'%', good: s.profitMargin >= 15,    pct: Math.min(s.profitMargin||23,100),              color: BRAND },
                            { label: 'Debt-to-Equity',     value: (s.debtToEquity||0.45).toFixed(2), suffix:'x', good: s.debtToEquity <= 0.5,   pct: Math.min(((1-(s.debtToEquity||0.45))*100),100),color:'#8b5cf6' },
                            { label: 'Revenue Growth',     value: Math.abs(s.revenueChange||12).toFixed(1), suffix:'%', good: (s.revenueChange||0)>=0, pct: Math.min(Math.abs(s.revenueChange||12)*3,100), color:'#f59e0b' },
                            { label: 'Runway (days)',      value: s.runwayDays||90,                   suffix:'d', good: (s.runwayDays||90)>=60,  pct: Math.min(((s.runwayDays||90)/365)*100,100),    color:'#06b6d4' },
                        ].map((item, i) => (
                            <div key={i}>
                                <div className="flex justify-between text-xs mb-1">
                                    <span className="text-gray-600">{item.label}</span>
                                    <span className="font-black" style={{ color: item.good ? item.color : '#ef4444' }}>
                                        {item.value}{item.suffix}
                                    </span>
                                </div>
                                <div className="h-1.5 bg-gray-100 rounded-full">
                                    <div className="h-full rounded-full" style={{ width:`${item.pct}%`, background: item.color }} />
                                </div>
                            </div>
                        ))}
                        <div className="mt-3 pt-3 border-t border-gray-100 flex items-center gap-2">
                            <div className="w-3 h-3 rounded-full" style={{ background: healthColor(s.healthStatus || 'good') }} />
                            <span className="text-xs font-semibold capitalize text-gray-700">
                                Health: {s.healthStatus || 'Good'}
                            </span>
                        </div>
                    </div>
                </GlassCard>
            </div>

            {/* ── Row 5: Summary Stats ─────────────────────────── */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {[
                    { label:'Total Liabilities', value: fmt(s.totalLiabilities||0), color:'#ef4444', icon: Warning },
                    { label:'Credit Score',       value: s.creditScore||750,         color: BRAND,    icon: ShieldCheck },
                    { label:'Departments',        value: s.departments||0,           color:'#8b5cf6', icon: Buildings },
                    { label:'Avg Salary (₦)',     value: fmt(s.avgSalary||120000),   color:'#10b981', icon: Briefcase },
                ].map((item, i) => (
                    <GlassCard key={i} className="p-4 flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: item.color + '18' }}>
                            <item.icon size={20} weight="duotone" style={{ color: item.color }} />
                        </div>
                        <div>
                            <p className="text-base font-black text-gray-900">{item.value}</p>
                            <p className="text-xs text-gray-500">{item.label}</p>
                        </div>
                    </GlassCard>
                ))}
            </div>
        </div>
    );
}
