import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import StatisticCardLarge from '@/components/dashboard/StatisticCardLarge';
import {
    AlertTriangle, BarChart3, Briefcase, Building2, DollarSign,
    Package, ShoppingBag, ShoppingCart, Truck, UserCheck, Users, Warehouse,
} from 'lucide-react';
import type { ElementType } from 'react';
import {
    Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, ComposedChart,
    Legend, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
} from 'recharts';

// ─── Icon mapping (iconKey string → Lucide component) ────────────────────────

const ICON_MAP: Record<string, ElementType> = {
    'dollar-sign':   DollarSign,
    'shopping-bag':  ShoppingBag,
    'bar-chart-3':   BarChart3,
    'shopping-cart': ShoppingCart,
    'package':       Package,
    'alert-triangle':AlertTriangle,
    'truck':         Truck,
    'user-check':    UserCheck,
    'users':         Users,
    'briefcase':     Briefcase,
    'building-2':    Building2,
    'warehouse':     Warehouse,
};

// ─── Types ───────────────────────────────────────────────────────────────────

interface StatKpi {
    iconKey: string;
    iconBg?: string;
    iconColor?: string;
    title: string;
    value: string;
    change?: string;
    changeType?: 'up' | 'down' | 'neutral' | 'none';
}

interface ErpDashboardData {
    statsRow1: StatKpi[];
    statsRow2: StatKpi[];
    statsRow3: StatKpi[];
    purchaseVsSales: { month: string; sales: number; purchase: number }[];
    stockMovement: { month: string; inflow: number; outflow: number }[];
    revenueExpense: { month: string; revenue: number; expense: number; profit: number }[];
    lowStockItems: { name: string; sku: string; stock: number; reorderLevel: number }[];
    recentPurchases: { id: string; date: string; supplier: string; amount: string; status: string }[];
}

// ─── Static supplemental data (HR / task modules not yet implemented) ────────

const employeeByDept = [
    { name: 'Operations', value: 42 },
    { name: 'Sales', value: 28 },
    { name: 'Finance', value: 18 },
    { name: 'HR', value: 12 },
    { name: 'IT', value: 16 },
    { name: 'Marketing', value: 14 },
];

const DEPT_COLORS = ['#6366f1', '#10b981', '#f59e0b', '#ef4444', '#3b82f6', '#ec4899'];

const userGrowth = [
    { month: 'Jan', employees: 118, contacts: 840 },
    { month: 'Feb', employees: 121, contacts: 910 },
    { month: 'Mar', employees: 124, contacts: 980 },
    { month: 'Apr', employees: 126, contacts: 1050 },
    { month: 'May', employees: 128, contacts: 1140 },
    { month: 'Jun', employees: 128, contacts: 1230 },
    { month: 'Jul', employees: 130, contacts: 1310 },
];

const recentEmployees = [
    { name: 'Ayesha Akter', role: 'Sales Executive', dept: 'Sales', joined: 'Jul 20', status: 'Active' },
    { name: 'Rafiqul Islam', role: 'Accountant', dept: 'Finance', joined: 'Jul 18', status: 'Active' },
    { name: 'Suma Begum', role: 'HR Officer', dept: 'HR', joined: 'Jul 15', status: 'Active' },
    { name: 'Karim Mia', role: 'Warehouse Lead', dept: 'Operations', joined: 'Jul 12', status: 'Active' },
];

const taskSummary = [
    { label: 'Open', count: 38, color: 'bg-blue-100 text-blue-800' },
    { label: 'In Progress', count: 24, color: 'bg-yellow-100 text-yellow-800' },
    { label: 'Completed', count: 91, color: 'bg-green-100 text-green-800' },
    { label: 'Overdue', count: 7, color: 'bg-red-100 text-red-800' },
];

const statusColors: Record<string, string> = {
    Received: 'bg-green-100 text-green-800',
    Ordered: 'bg-blue-100 text-blue-800',
    Pending: 'bg-yellow-100 text-yellow-800',
    Cancelled: 'bg-red-100 text-red-800',
};

// ─── KPI row helper ───────────────────────────────────────────────────────────

function KpiRow({ stats }: { stats: StatKpi[] }) {
    return (
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
            {stats.map((s, i) => (
                <StatisticCardLarge
                    key={i}
                    title={s.title}
                    value={s.value}
                    change={s.change}
                    changeType={s.changeType ?? 'none'}
                    icon={ICON_MAP[s.iconKey] ?? Package}
                    iconBg={s.iconBg}
                    iconColor={s.iconColor}
                />
            ))}
        </div>
    );
}

// ─── Component ────────────────────────────────────────────────────────────────

export default function ErpCentralDashboard({ data = {} as ErpDashboardData }: { data?: ErpDashboardData }) {
    const {
        statsRow1       = [],
        statsRow2       = [],
        statsRow3       = [],
        purchaseVsSales = [],
        stockMovement   = [],
        revenueExpense  = [],
        lowStockItems   = [],
        recentPurchases = [],
    } = data;

    return (
        <div className="space-y-6">
            {/* KPI row 1 — Sales & Purchases (date-filtered) */}
            <KpiRow stats={statsRow1} />

            {/* KPI row 2 — Products, stock, contacts */}
            <KpiRow stats={statsRow2} />

            {/* KPI row 3 — Users, contacts, branches, stock */}
            <KpiRow stats={statsRow3} />

            {/* Charts row 1 — Purchase vs Sales + Stock Movement */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-7">
                <Card className="col-span-1 border-input lg:col-span-4">
                    <CardHeader className="border-b border-input pb-3">
                        <CardTitle className="text-base font-semibold text-foreground">Purchase vs Sales</CardTitle>
                        <CardDescription className="text-sm text-gray-500">Monthly purchase cost vs sales revenue</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <ComposedChart data={purchaseVsSales}>
                                    <defs>
                                        <linearGradient id="erp-sales" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="5%" stopColor="#10B981" stopOpacity={0.2} />
                                            <stop offset="95%" stopColor="#10B981" stopOpacity={0} />
                                        </linearGradient>
                                    </defs>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                    <XAxis dataKey="month" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                                    <Tooltip formatter={(v: number) => v.toLocaleString()} />
                                    <Legend />
                                    <Bar dataKey="purchase" name="Purchase" fill="#6366f1" radius={[4, 4, 0, 0]} barSize={20} />
                                    <Area type="monotone" dataKey="sales" name="Sales" stroke="#10B981" fill="url(#erp-sales)" strokeWidth={2} />
                                </ComposedChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                <Card className="col-span-1 border-input lg:col-span-3">
                    <CardHeader className="border-b border-input pb-3">
                        <CardTitle className="text-base font-semibold text-foreground">Stock Movement</CardTitle>
                        <CardDescription className="text-sm text-gray-500">Monthly inflow vs outflow (units)</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={stockMovement}>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                    <XAxis dataKey="month" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <Tooltip />
                                    <Legend />
                                    <Bar dataKey="inflow" name="Inflow" fill="#3B82F6" radius={[4, 4, 0, 0]} barSize={18} />
                                    <Bar dataKey="outflow" name="Outflow" fill="#EF4444" radius={[4, 4, 0, 0]} barSize={18} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Charts row 2 — Revenue/Expense/Profit + Employee Distribution (static) */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-7">
                <Card className="col-span-1 lg:col-span-4">
                    <CardHeader className="border-b border-input pb-3">
                        <CardTitle className="text-base font-semibold text-foreground">Revenue · Expense · Profit</CardTitle>
                        <CardDescription className="text-sm text-gray-500">Monthly financial overview</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <AreaChart data={revenueExpense}>
                                    <defs>
                                        <linearGradient id="erp-rev" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="5%" stopColor="#6366f1" stopOpacity={0.15} />
                                            <stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
                                        </linearGradient>
                                        <linearGradient id="erp-profit" x1="0" y1="0" x2="0" y2="1">
                                            <stop offset="5%" stopColor="#10b981" stopOpacity={0.2} />
                                            <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
                                        </linearGradient>
                                    </defs>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                    <XAxis dataKey="month" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                                    <Tooltip formatter={(v: number) => v.toLocaleString()} />
                                    <Legend />
                                    <Area type="monotone" dataKey="revenue" name="Revenue" stroke="#6366f1" fill="url(#erp-rev)" strokeWidth={2} />
                                    <Area type="monotone" dataKey="profit" name="Profit" stroke="#10b981" fill="url(#erp-profit)" strokeWidth={2} />
                                    <Line type="monotone" dataKey="expense" name="Expense" stroke="#ef4444" strokeWidth={2} dot={false} />
                                </AreaChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                <Card className="col-span-1 lg:col-span-3">
                    <CardHeader className="border-b border-input pb-3">
                        <CardTitle className="text-base font-semibold text-foreground">Employees by Department</CardTitle>
                        <CardDescription className="text-sm text-gray-500">Headcount distribution</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <PieChart>
                                    <Pie data={employeeByDept} cx="50%" cy="50%" innerRadius={52} outerRadius={85} dataKey="value" label={({ value }) => `${value}`}>
                                        {employeeByDept.map((_, i) => (
                                            <Cell key={i} fill={DEPT_COLORS[i % DEPT_COLORS.length]} />
                                        ))}
                                    </Pie>
                                    <Tooltip formatter={(v, name) => [v, name]} />
                                    <Legend />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Charts row 3 — Employee & Contact growth (static) */}
            <Card>
                <CardHeader className="border-b border-input pb-3">
                    <CardTitle className="text-base font-semibold text-foreground">Employee & Contact Growth</CardTitle>
                    <CardDescription className="text-sm text-gray-500">Monthly headcount and CRM contact count</CardDescription>
                </CardHeader>
                <CardContent className="pt-4">
                    <div className="h-52">
                        <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={userGrowth}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                <XAxis dataKey="month" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                <YAxis yAxisId="left" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                <Tooltip />
                                <Legend />
                                <Line yAxisId="left" type="monotone" dataKey="employees" name="Employees" stroke="#6366f1" strokeWidth={2} dot={{ r: 3 }} />
                                <Line yAxisId="right" type="monotone" dataKey="contacts" name="Contacts" stroke="#10b981" strokeWidth={2} dot={{ r: 3 }} />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>
                </CardContent>
            </Card>

            {/* Task summary badges (static) */}
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
                {taskSummary.map((t) => (
                    <Card key={t.label}>
                        <CardContent className="flex items-center justify-between p-4">
                            <span className="text-sm font-medium text-gray-600">{t.label}</span>
                            <span className={`rounded-full px-2.5 py-0.5 text-sm font-semibold ${t.color}`}>{t.count}</span>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {/* Tables row — Low stock + Recent POs */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
                <Card>
                    <CardHeader className="border-b border-input pb-3">
                        <div className="flex items-center gap-2">
                            <AlertTriangle className="h-4 w-4 text-red-500" />
                            <CardTitle className="text-base font-semibold text-foreground">Low Stock Alerts</CardTitle>
                        </div>
                        <CardDescription className="text-sm text-gray-500">Items below reorder threshold</CardDescription>
                    </CardHeader>
                    <CardContent className="p-0">
                        <table className="w-full text-sm">
                            <thead>
                                <tr className="border-b border-input text-left text-xs tracking-wide text-gray-500 uppercase">
                                    <th className="px-4 py-2">Item</th>
                                    <th className="px-4 py-2">Stock</th>
                                    <th className="px-4 py-2">Reorder At</th>
                                </tr>
                            </thead>
                            <tbody>
                                {lowStockItems.length === 0 ? (
                                    <tr><td colSpan={3} className="px-4 py-4 text-center text-xs text-gray-400">No low stock items</td></tr>
                                ) : lowStockItems.map((item, i) => (
                                    <tr key={i} className="border-b border-input">
                                        <td className="px-4 py-2.5">
                                            <p className="line-clamp-1 text-xs font-medium text-foreground">{item.name}</p>
                                            <p className="text-xs text-gray-400">{item.sku}</p>
                                        </td>
                                        <td className="px-4 py-2.5">
                                            <span className="inline-flex min-w-8 justify-center rounded border border-red-200 bg-red-50 px-1.5 py-0.5 text-xs font-semibold text-red-700">
                                                {item.stock}
                                            </span>
                                        </td>
                                        <td className="px-4 py-2.5 text-xs text-gray-500">{item.reorderLevel}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="border-b border-input pb-3">
                        <CardTitle className="text-base font-semibold text-foreground">Recent Purchase Orders</CardTitle>
                        <CardDescription className="text-sm text-gray-500">Latest supplier orders in selected range</CardDescription>
                    </CardHeader>
                    <CardContent className="p-0">
                        <table className="w-full text-sm">
                            <thead>
                                <tr className="border-b border-input text-left text-xs tracking-wide text-gray-500 uppercase">
                                    <th className="px-4 py-2">PO #</th>
                                    <th className="px-4 py-2">Supplier</th>
                                    <th className="px-4 py-2">Amount</th>
                                    <th className="px-4 py-2">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                {recentPurchases.length === 0 ? (
                                    <tr><td colSpan={4} className="px-4 py-4 text-center text-xs text-gray-400">No purchase orders in range</td></tr>
                                ) : recentPurchases.map((po, i) => (
                                    <tr key={i} className="border-b border-input text-foreground">
                                        <td className="px-4 py-2.5">
                                            <p className="font-mono text-xs font-medium">{po.id}</p>
                                            <p className="text-xs text-gray-400">{po.date}</p>
                                        </td>
                                        <td className="px-4 py-2.5 text-xs text-foreground">{po.supplier}</td>
                                        <td className="px-4 py-2.5 text-xs font-semibold">{po.amount}</td>
                                        <td className="px-4 py-2.5">
                                            <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${statusColors[po.status] ?? 'bg-gray-100 text-gray-700'}`}>{po.status}</span>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>
            </div>

            {/* Recent employees table (static) */}
            <Card>
                <CardHeader className="border-b border-input pb-3">
                    <CardTitle className="text-base font-semibold text-foreground">Recently Joined Employees</CardTitle>
                    <CardDescription className="text-sm text-gray-500">New hires this month</CardDescription>
                </CardHeader>
                <CardContent className="p-0">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-input text-left text-xs tracking-wide text-gray-500 uppercase">
                                <th className="px-4 py-2">Name</th>
                                <th className="px-4 py-2">Role</th>
                                <th className="px-4 py-2">Department</th>
                                <th className="px-4 py-2">Joined</th>
                                <th className="px-4 py-2">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {recentEmployees.map((e) => (
                                <tr key={e.name} className="border-b border-input text-foreground">
                                    <td className="px-4 py-2.5 text-xs font-medium">{e.name}</td>
                                    <td className="px-4 py-2.5 text-xs text-gray-600">{e.role}</td>
                                    <td className="px-4 py-2.5 text-xs text-gray-600">{e.dept}</td>
                                    <td className="px-4 py-2.5 text-xs text-gray-400">{e.joined}</td>
                                    <td className="px-4 py-2.5">
                                        <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800">{e.status}</span>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </CardContent>
            </Card>
        </div>
    );
}
