import { Head, Link } from '@inertiajs/react';
import { AlertTriangle, DollarSign, Package, ShoppingCart, TrendingUp, Users } from 'lucide-react';
import {
    Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Legend,
    Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
} from 'recharts';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import AdminLayout from '@/layouts/admin-layout';
import { type Order } from '@/types';

interface Stats {
    todayOrders: number; todayRevenue: number;
    monthOrders: number; monthRevenue: number;
    pendingOrders: number; totalProducts: number;
    lowStockProducts: number; totalCustomers: number;
}
interface DailyStat { date: string; orders: number; revenue: number; }
interface StatusDist { name: string; value: number; }
interface TopProduct { name: string; sold: number; revenue: number; }

const STATUS_COLORS: Record<string, string> = {
    new: '#3b82f6', pending: '#f59e0b', confirmed: '#6366f1',
    packed: '#a855f7', shipped: '#f97316', delivered: '#22c55e',
    cancelled: '#ef4444', returned: '#94a3b8',
};
const PIE_COLORS = ['#6366f1','#22c55e','#f59e0b','#ef4444','#3b82f6','#a855f7','#f97316','#94a3b8'];

const ORDER_STATUS_CLS: Record<string, string> = {
    new: 'bg-blue-100 text-blue-800',
    pending: 'bg-yellow-100 text-yellow-800',
    confirmed: 'bg-indigo-100 text-indigo-800',
    packed: 'bg-purple-100 text-purple-800',
    shipped: 'bg-orange-100 text-orange-800',
    delivered: 'bg-green-100 text-green-800',
    cancelled: 'bg-red-100 text-red-800',
    returned: 'bg-slate-100 text-slate-800',
};

function StatCard({ label, value, sub, icon: Icon, cls }: { label: string; value: string|number; sub?: string; icon: React.ElementType; cls: string }) {
    return (
        <Card>
            <CardContent className="flex items-center gap-4 p-5">
                <div className={`flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl ${cls}`}>
                    <Icon size={20} className="text-white" />
                </div>
                <div className="min-w-0">
                    <p className="text-xs text-slate-500 dark:text-slate-400">{label}</p>
                    <p className="text-xl font-bold text-slate-800 dark:text-white truncate">{value}</p>
                    {sub && <p className="text-xs text-slate-400">{sub}</p>}
                </div>
            </CardContent>
        </Card>
    );
}

const fmt = (v: number) => `৳${v.toLocaleString()}`;

export default function AdminDashboard({ stats, recentOrders, dailyStats, statusDist, topProducts }: {
    stats: Stats; recentOrders: Order[];
    dailyStats: DailyStat[]; statusDist: StatusDist[]; topProducts: TopProduct[];
}) {
    return (
        <AdminLayout title="Dashboard">
            <Head title="Dashboard" />

            {/* Stats */}
            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                <StatCard label="Today Orders" value={stats.todayOrders} icon={ShoppingCart} cls="bg-blue-500" />
                <StatCard label="Today Revenue" value={fmt(stats.todayRevenue)} icon={DollarSign} cls="bg-green-500" />
                <StatCard label="Pending Orders" value={stats.pendingOrders} sub="Need action" icon={AlertTriangle} cls="bg-yellow-500" />
                <StatCard label="Month Revenue" value={fmt(stats.monthRevenue)} sub={`${stats.monthOrders} orders`} icon={TrendingUp} cls="bg-indigo-500" />
                <StatCard label="Customers" value={stats.totalCustomers} icon={Users} cls="bg-purple-500" />
                <StatCard label="Products" value={stats.totalProducts} icon={Package} cls="bg-cyan-500" />
                <StatCard label="Low Stock" value={stats.lowStockProducts} sub="Below alert" icon={AlertTriangle} cls="bg-red-500" />
            </div>

            {/* Row 1: Area chart + Pie */}
            <div className="mt-6 grid gap-6 lg:grid-cols-3">
                <Card className="lg:col-span-2">
                    <CardHeader><CardTitle className="text-sm">Revenue — Last 7 Days</CardTitle></CardHeader>
                    <CardContent>
                        <ResponsiveContainer width="100%" height={220}>
                            <AreaChart data={dailyStats} margin={{ top:4, right:4, left:-10, bottom:0 }}>
                                <defs>
                                    <linearGradient id="grad" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#6366f1" stopOpacity={0.35}/>
                                        <stop offset="95%" stopColor="#6366f1" stopOpacity={0}/>
                                    </linearGradient>
                                </defs>
                                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                                <XAxis dataKey="date" tick={{ fontSize:11 }} stroke="#94a3b8" />
                                <YAxis tick={{ fontSize:11 }} stroke="#94a3b8" tickFormatter={(v)=>`৳${(v/1000).toFixed(0)}k`} />
                                <Tooltip formatter={(v:number)=>[`৳${v.toLocaleString()}`,'Revenue']} contentStyle={{ borderRadius:8, border:'none', boxShadow:'0 4px 20px rgba(0,0,0,.1)' }} />
                                <Area type="monotone" dataKey="revenue" stroke="#6366f1" strokeWidth={2} fill="url(#grad)" />
                            </AreaChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader><CardTitle className="text-sm">Order Status</CardTitle></CardHeader>
                    <CardContent>
                        {statusDist.length > 0 ? (
                            <ResponsiveContainer width="100%" height={220}>
                                <PieChart>
                                    <Pie data={statusDist} cx="50%" cy="50%" innerRadius={55} outerRadius={85} paddingAngle={3} dataKey="value">
                                        {statusDist.map((e,i)=>(
                                            <Cell key={e.name} fill={STATUS_COLORS[e.name]??PIE_COLORS[i%PIE_COLORS.length]} />
                                        ))}
                                    </Pie>
                                    <Tooltip contentStyle={{ borderRadius:8, border:'none', boxShadow:'0 4px 20px rgba(0,0,0,.1)' }} />
                                    <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize:11 }} />
                                </PieChart>
                            </ResponsiveContainer>
                        ) : (
                            <div className="flex h-52 items-center justify-center text-sm text-slate-400">No orders yet</div>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Row 2: Bar chart + Top products */}
            <div className="mt-6 grid gap-6 lg:grid-cols-2">
                <Card>
                    <CardHeader><CardTitle className="text-sm">Daily Orders — Last 7 Days</CardTitle></CardHeader>
                    <CardContent>
                        <ResponsiveContainer width="100%" height={200}>
                            <BarChart data={dailyStats} margin={{ top:4, right:4, left:-20, bottom:0 }}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                                <XAxis dataKey="date" tick={{ fontSize:11 }} stroke="#94a3b8" />
                                <YAxis tick={{ fontSize:11 }} stroke="#94a3b8" allowDecimals={false} />
                                <Tooltip formatter={(v:number)=>[v,'Orders']} contentStyle={{ borderRadius:8, border:'none', boxShadow:'0 4px 20px rgba(0,0,0,.1)' }} />
                                <Bar dataKey="orders" fill="#6366f1" radius={[4,4,0,0]} />
                            </BarChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader><CardTitle className="text-sm">Top Selling Products</CardTitle></CardHeader>
                    <CardContent className="p-0">
                        {topProducts.length > 0 ? (
                            <div className="divide-y">
                                {topProducts.map((p,i)=>(
                                    <div key={i} className="flex items-center gap-3 px-4 py-3">
                                        <span className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full bg-indigo-100 text-xs font-bold text-indigo-700">{i+1}</span>
                                        <div className="flex-1 min-w-0">
                                            <p className="truncate text-sm font-medium">{p.name}</p>
                                            <p className="text-xs text-slate-400">{p.sold} units</p>
                                        </div>
                                        <span className="text-sm font-semibold text-indigo-600 flex-shrink-0">৳{Number(p.revenue).toLocaleString()}</span>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className="flex h-40 items-center justify-center text-sm text-slate-400">No sales yet</div>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Recent orders */}
            <Card className="mt-6">
                <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle className="text-sm">Recent Orders</CardTitle>
                    <Link href="/admin/orders" className="text-xs text-indigo-500 hover:underline">View all →</Link>
                </CardHeader>
                <CardContent className="p-0">
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                            <thead className="border-b bg-slate-50 text-xs uppercase text-slate-500">
                                <tr>
                                    <th className="px-4 py-3 text-left">Invoice</th>
                                    <th className="px-4 py-3 text-left">Customer</th>
                                    <th className="px-4 py-3 text-right">Amount</th>
                                    <th className="px-4 py-3 text-center">Status</th>
                                    <th className="px-4 py-3 text-left">Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {recentOrders.map((o)=>(
                                    <tr key={o.id} className="hover:bg-slate-50">
                                        <td className="px-4 py-3">
                                            <Link href={`/admin/orders/${o.id}`} className="font-mono text-xs text-indigo-600 hover:underline">{o.invoice_no}</Link>
                                        </td>
                                        <td className="px-4 py-3">
                                            <div className="font-medium">{o.customer_name}</div>
                                            <div className="text-xs text-slate-400">{o.customer_phone}</div>
                                        </td>
                                        <td className="px-4 py-3 text-right font-semibold">৳{Number(o.total_amount).toLocaleString()}</td>
                                        <td className="px-4 py-3 text-center">
                                            <span className={`rounded-full px-2 py-0.5 text-xs font-medium capitalize ${ORDER_STATUS_CLS[o.order_status]??''}`}>{o.order_status}</span>
                                        </td>
                                        <td className="px-4 py-3 text-xs text-slate-500">{new Date(o.created_at).toLocaleDateString('en-BD')}</td>
                                    </tr>
                                ))}
                                {!recentOrders.length && <tr><td colSpan={5} className="py-10 text-center text-slate-400">No orders yet</td></tr>}
                            </tbody>
                        </table>
                    </div>
                </CardContent>
            </Card>
        </AdminLayout>
    );
}
