import StatisticsCard from '@/components/statistics-card';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { RotateCcw, ShoppingBag, ShoppingCart, Star, Tag, TrendingUp, Users } from 'lucide-react';
import {
    Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Legend,
    Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
} from 'recharts';

interface StatItem {
    key: string;
    title: string;
    value: string;
    subtitle: string;
    subtitleColor: 'green' | 'red' | 'gray';
}

interface EcommerceDashboardData {
    stats: StatItem[];
    revenueTrend: { month: string; revenue: number; orders: number }[];
    ordersByStatus: { status: string; label: string; count: number }[];
    topProducts: { name: string; unitsSold: number; revenue: number }[];
    recentOrders: { orderNumber: string; customer: string; date: string; total: number; status: string }[];
}

const STAT_ICONS: Record<string, React.ElementType> = {
    revenue:       TrendingUp,
    orders:        ShoppingCart,
    customers:     Users,
    avg_order:     Tag,
    return_rate:   RotateCcw,
    active_coupons: ShoppingBag,
    top_products:  Star,
    new_customers: Users,
};

const ORDER_STATUS_COLORS: Record<string, string> = {
    delivered:          'bg-green-100 text-green-800',
    completed:          'bg-teal-100 text-teal-800',
    processing:         'bg-blue-100 text-blue-800',
    shipped:            'bg-purple-100 text-purple-800',
    pending:            'bg-yellow-100 text-yellow-800',
    cancelled:          'bg-red-100 text-red-800',
    refunded:           'bg-orange-100 text-orange-800',
    partially_refunded: 'bg-amber-100 text-amber-800',
    confirmed:          'bg-indigo-100 text-indigo-800',
};

// ─── Static demo supplement data ─────────────────────────────────────────────

const customerGrowth = [
    { month: 'Jan', newCustomers: 142, returningCustomers: 320 },
    { month: 'Feb', newCustomers: 168, returningCustomers: 355 },
    { month: 'Mar', newCustomers: 195, returningCustomers: 390 },
    { month: 'Apr', newCustomers: 210, returningCustomers: 425 },
    { month: 'May', newCustomers: 185, returningCustomers: 410 },
    { month: 'Jun', newCustomers: 240, returningCustomers: 470 },
    { month: 'Jul', newCustomers: 228, returningCustomers: 460 },
];

const salesByCategory = [
    { category: 'Electronics', sales: 184000 },
    { category: 'Fashion',     sales: 142000 },
    { category: 'Home & Living', sales: 98000 },
    { category: 'Sports',      sales: 76000 },
    { category: 'Books',       sales: 42000 },
    { category: 'Beauty',      sales: 58000 },
];

const CATEGORY_COLORS = ['#6366f1', '#ec4899', '#f59e0b', '#10b981', '#3b82f6', '#8b5cf6'];

const weeklyConversion = [
    { day: 'Mon', visits: 1240, conversions: 62 },
    { day: 'Tue', visits: 1480, conversions: 88 },
    { day: 'Wed', visits: 1120, conversions: 56 },
    { day: 'Thu', visits: 1680, conversions: 101 },
    { day: 'Fri', visits: 1960, conversions: 137 },
    { day: 'Sat', visits: 2240, conversions: 168 },
    { day: 'Sun', visits: 1820, conversions: 127 },
];

const topCustomers = [
    { name: 'Rahman Enterprise', orders: 28, spent: '৳4,82,000', tier: 'Gold' },
    { name: 'Nadia Akter',       orders: 22, spent: '৳3,16,000', tier: 'Gold' },
    { name: 'City Mart BD',      orders: 19, spent: '৳2,74,000', tier: 'Silver' },
    { name: 'Karim Traders',     orders: 15, spent: '৳1,98,000', tier: 'Silver' },
    { name: 'Sumaiya Begum',     orders: 12, spent: '৳1,42,000', tier: 'Bronze' },
];

const tierColors: Record<string, string> = {
    Gold:   'bg-yellow-100 text-yellow-800',
    Silver: 'bg-slate-100 text-slate-700',
    Bronze: 'bg-orange-100 text-orange-700',
};

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

export default function EcommerceCentralDashboard({ data }: { data: EcommerceDashboardData }) {
    const stats          = data?.stats          ?? [];
    const revenueTrend   = data?.revenueTrend   ?? [];
    const ordersByStatus = data?.ordersByStatus ?? [];
    const topProducts    = data?.topProducts    ?? [];
    const recentOrders   = data?.recentOrders   ?? [];

    return (
        <div className="space-y-6">
            {/* KPI row 1 — from backend */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                {stats.map((s, i) => (
                    <StatisticsCard
                        key={i}
                        title={s.title}
                        value={s.value}
                        subtitle={s.subtitle}
                        subtitleColor={s.subtitleColor}
                        icon={STAT_ICONS[s.key]}
                    />
                ))}
            </div>

            {/* KPI row 2 — supplemental metrics */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                {[
                    { label: 'Return Rate',      value: '3.2%',  color: 'text-red-600',    bg: 'bg-red-50',    icon: RotateCcw   },
                    { label: 'Cart Abandonment', value: '68.4%', color: 'text-orange-600', bg: 'bg-orange-50', icon: ShoppingBag },
                    { label: 'Active Coupons',   value: '14',    color: 'text-indigo-600', bg: 'bg-indigo-50', icon: Tag         },
                    { label: 'Product Rating',   value: '4.6★',  color: 'text-yellow-600', bg: 'bg-yellow-50', icon: Star        },
                ].map((m) => (
                    <Card key={m.label} className="border-gray-100 shadow-sm">
                        <CardContent className="flex items-center gap-3 p-4">
                            <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${m.bg}`}>
                                <m.icon className={`h-5 w-5 ${m.color}`} />
                            </div>
                            <div>
                                <p className="text-xs text-gray-500">{m.label}</p>
                                <p className={`text-lg font-bold ${m.color}`}>{m.value}</p>
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {/* Revenue trend chart */}
            <Card className="border-gray-100 shadow-sm">
                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                    <CardTitle className="text-base font-semibold text-gray-800">Revenue & Orders Trend</CardTitle>
                    <CardDescription>Monthly performance for the last 6 months</CardDescription>
                </CardHeader>
                <CardContent className="pt-4">
                    <div className="h-64">
                        <ResponsiveContainer width="100%" height="100%">
                            <AreaChart data={revenueTrend}>
                                <defs>
                                    <linearGradient id="ecom-rev" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#4F46E5" stopOpacity={0.2} />
                                        <stop offset="95%" stopColor="#4F46E5" 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} />
                                <Tooltip />
                                <Legend />
                                <Area type="monotone" dataKey="revenue" stroke="#4F46E5" fill="url(#ecom-rev)" strokeWidth={2} name="Revenue" />
                                <Area type="monotone" dataKey="orders"  stroke="#EC4899" fill="transparent" strokeWidth={2} name="Orders" />
                            </AreaChart>
                        </ResponsiveContainer>
                    </div>
                </CardContent>
            </Card>

            {/* Sales by Category + Customer Growth */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-7">
                <Card className="col-span-1 border-gray-100 shadow-sm lg:col-span-4">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-gray-800">Sales by Category</CardTitle>
                        <CardDescription>Revenue breakdown by product category</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-56">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={salesByCategory} layout="vertical">
                                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" horizontal={false} />
                                    <XAxis type="number" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                                    <YAxis type="category" dataKey="category" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} width={92} />
                                    <Tooltip formatter={(v: number) => `৳${v.toLocaleString()}`} />
                                    <Bar dataKey="sales" name="Sales" radius={[0, 4, 4, 0]} barSize={18}>
                                        {salesByCategory.map((_, i) => (
                                            <Cell key={i} fill={CATEGORY_COLORS[i % CATEGORY_COLORS.length]} />
                                        ))}
                                    </Bar>
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                <Card className="col-span-1 border-gray-100 shadow-sm lg:col-span-3">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-gray-800">Customer Growth</CardTitle>
                        <CardDescription>New vs returning customers per month</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-56">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={customerGrowth}>
                                    <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="newCustomers"       name="New"       fill="#6366f1" radius={[3, 3, 0, 0]} barSize={14} />
                                    <Bar dataKey="returningCustomers" name="Returning" fill="#10b981" radius={[3, 3, 0, 0]} barSize={14} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Weekly visits & conversions */}
            <Card className="border-gray-100 shadow-sm">
                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                    <CardTitle className="text-base font-semibold text-gray-800">Weekly Visits & Conversions</CardTitle>
                    <CardDescription>Store visits vs completed orders this week</CardDescription>
                </CardHeader>
                <CardContent className="pt-4">
                    <div className="h-52">
                        <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={weeklyConversion}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                <XAxis dataKey="day" 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="visits"      name="Visits"      stroke="#6366f1" strokeWidth={2} dot={{ r: 3 }} />
                                <Line yAxisId="right" type="monotone" dataKey="conversions" name="Conversions" stroke="#ec4899" strokeWidth={2} dot={{ r: 3 }} />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>
                </CardContent>
            </Card>

            {/* Top products + Orders by status */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
                <Card className="border-gray-100 shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-gray-800">Top Selling Products</CardTitle>
                    </CardHeader>
                    <CardContent className="p-0">
                        <table className="w-full text-sm">
                            <thead>
                                <tr className="border-b border-[#e3e3e3] bg-[#fafafa] text-left text-xs tracking-wide text-gray-500 uppercase">
                                    <th className="px-4 py-2">Product</th>
                                    <th className="px-4 py-2">Units</th>
                                    <th className="px-4 py-2">Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                {topProducts.length === 0 ? (
                                    <tr><td colSpan={3} className="px-4 py-6 text-center text-xs text-gray-400">No product data yet</td></tr>
                                ) : (
                                    topProducts.map((p) => (
                                        <tr key={p.name} className="border-b border-[#efefef] text-gray-800">
                                            <td className="px-4 py-2.5 text-xs">{p.name}</td>
                                            <td className="px-4 py-2.5 text-xs">{p.unitsSold.toLocaleString()}</td>
                                            <td className="px-4 py-2.5 text-xs font-medium">{p.revenue.toLocaleString()}</td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>

                <Card className="border-gray-100 shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-gray-800">Orders by Status</CardTitle>
                    </CardHeader>
                    <CardContent className="p-4">
                        {ordersByStatus.filter((s) => s.count > 0).length === 0 ? (
                            <p className="py-4 text-center text-xs text-gray-400">No orders yet</p>
                        ) : (
                            <div className="space-y-2">
                                {ordersByStatus.filter((s) => s.count > 0).map((s) => (
                                    <div key={s.status} className="flex items-center justify-between">
                                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${ORDER_STATUS_COLORS[s.status] ?? 'bg-gray-100 text-gray-700'}`}>
                                            {s.label}
                                        </span>
                                        <span className="text-xs font-semibold text-gray-800">{s.count}</span>
                                    </div>
                                ))}
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Top customers */}
            <Card className="border-gray-100 shadow-sm">
                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                    <CardTitle className="text-base font-semibold text-gray-800">Top Customers</CardTitle>
                    <CardDescription>Highest-value buyers by total spend</CardDescription>
                </CardHeader>
                <CardContent className="p-0">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-[#e3e3e3] bg-[#fafafa] text-left text-xs tracking-wide text-gray-500 uppercase">
                                <th className="px-4 py-2">Customer</th>
                                <th className="px-4 py-2">Orders</th>
                                <th className="px-4 py-2">Total Spent</th>
                                <th className="px-4 py-2">Tier</th>
                            </tr>
                        </thead>
                        <tbody>
                            {topCustomers.map((c) => (
                                <tr key={c.name} className="border-b border-[#efefef] text-gray-800">
                                    <td className="px-4 py-2.5 text-xs font-medium">{c.name}</td>
                                    <td className="px-4 py-2.5 text-xs">{c.orders}</td>
                                    <td className="px-4 py-2.5 text-xs font-semibold">{c.spent}</td>
                                    <td className="px-4 py-2.5">
                                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${tierColors[c.tier]}`}>{c.tier}</span>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </CardContent>
            </Card>

            {/* Recent orders */}
            <Card className="border-gray-100 shadow-sm">
                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                    <CardTitle className="text-base font-semibold text-gray-800">Recent Orders</CardTitle>
                </CardHeader>
                <CardContent className="p-0">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-[#e3e3e3] bg-[#fafafa] text-left text-xs tracking-wide text-gray-500 uppercase">
                                <th className="px-4 py-2">Order</th>
                                <th className="px-4 py-2">Customer</th>
                                <th className="px-4 py-2">Date</th>
                                <th className="px-4 py-2">Total</th>
                                <th className="px-4 py-2">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {recentOrders.length === 0 ? (
                                <tr><td colSpan={5} className="px-4 py-6 text-center text-xs text-gray-400">No orders yet</td></tr>
                            ) : (
                                recentOrders.map((o, i) => (
                                    <tr key={i} className="border-b border-[#efefef] text-gray-800">
                                        <td className="px-4 py-2.5 font-mono text-xs">{o.orderNumber}</td>
                                        <td className="px-4 py-2.5 text-xs">{o.customer}</td>
                                        <td className="px-4 py-2.5 text-xs text-gray-400">{o.date}</td>
                                        <td className="px-4 py-2.5 text-xs font-medium">{o.total.toLocaleString()}</td>
                                        <td className="px-4 py-2.5">
                                            <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${ORDER_STATUS_COLORS[o.status] ?? 'bg-gray-100 text-gray-700'}`}>
                                                {o.status}
                                            </span>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </CardContent>
            </Card>
        </div>
    );
}
