import StatisticsCard from '@/components/statistics-card';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { CheckCircle2, Clock, Percent, Target, TrendingUp, Users, XCircle } from 'lucide-react';
import {
    Bar, BarChart, CartesianGrid, Cell, Legend, Line, LineChart,
    Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis,
} from 'recharts';

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

interface SalesDashboardData {
    stats: StatItem[];
    monthlyPipeline: { month: string; won: number; lost: number; pipeline: number }[];
    conversionTrend: { week: string; rate: number }[];
    pipelineFunnel: { name: string; value: number }[];
    recentDeals: { name: string; value: string; stage: string; rep: string; daysOpen: number }[];
}

const STAT_ICONS: Record<string, React.ElementType> = {
    pipeline: TrendingUp,
    won:      CheckCircle2,
    lost:     XCircle,
    contacts: Users,
};

const FUNNEL_COLORS = ['#0ea5e9', '#38bdf8', '#7dd3fc', '#bae6fd', '#e0f2fe'];

const SOURCE_COLORS = ['#6366f1', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'];

const stageColors: Record<string, string> = {
    Delivered:  'bg-green-100 text-green-800',
    Completed:  'bg-teal-100 text-teal-800',
    Cancelled:  'bg-red-100 text-red-800',
    Processing: 'bg-blue-100 text-blue-800',
    Shipped:    'bg-purple-100 text-purple-800',
    Pending:    'bg-yellow-100 text-yellow-800',
    Confirmed:  'bg-indigo-100 text-indigo-800',
};

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

const repPerformance = [
    { name: 'Arif Rahman',  won: 18, lost: 4,  pipeline: 12, revenue: '৳2,84,000' },
    { name: 'Suma Khatun',  won: 15, lost: 6,  pipeline: 9,  revenue: '৳2,31,000' },
    { name: 'Kamal Hossain', won: 12, lost: 8,  pipeline: 14, revenue: '৳1,96,000' },
    { name: 'Nadia Islam',  won: 10, lost: 3,  pipeline: 8,  revenue: '৳1,72,000' },
    { name: 'Rahim Uddin',  won: 8,  lost: 5,  pipeline: 11, revenue: '৳1,24,000' },
];

const leadSources = [
    { name: 'Website',   value: 38 },
    { name: 'Referral',  value: 24 },
    { name: 'Cold Call', value: 18 },
    { name: 'Social',    value: 13 },
    { name: 'Events',    value: 7 },
];

const salesByRep = [
    { rep: 'Arif',  won: 18, lost: 4 },
    { rep: 'Suma',  won: 15, lost: 6 },
    { rep: 'Kamal', won: 12, lost: 8 },
    { rep: 'Nadia', won: 10, lost: 3 },
    { rep: 'Rahim', won: 8,  lost: 5 },
];

const revenueForecast = [
    { month: 'Aug', actual: null, forecast: 860000 },
    { month: 'Sep', actual: null, forecast: 920000 },
    { month: 'Oct', actual: null, forecast: 980000 },
    { month: 'Nov', actual: null, forecast: 1050000 },
    { month: 'Dec', actual: null, forecast: 1180000 },
];

const combinedTrend = [
    { month: 'Jan', actual: 520000, forecast: 520000 },
    { month: 'Feb', actual: 490000, forecast: 510000 },
    { month: 'Mar', actual: 680000, forecast: 640000 },
    { month: 'Apr', actual: 740000, forecast: 720000 },
    { month: 'May', actual: 620000, forecast: 650000 },
    { month: 'Jun', actual: 810000, forecast: 780000 },
    { month: 'Jul', actual: 775000, forecast: 800000 },
    ...revenueForecast,
];

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

export default function SalesCentralDashboard({ data }: { data: SalesDashboardData }) {
    const stats           = data?.stats           ?? [];
    const monthlyPipeline = data?.monthlyPipeline ?? [];
    const conversionTrend = data?.conversionTrend ?? [];
    const pipelineFunnel  = data?.pipelineFunnel  ?? [];
    const recentDeals     = data?.recentDeals     ?? [];

    const maxFunnelValue = pipelineFunnel[0]?.value ?? 1;

    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 */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                {[
                    { label: 'Active Leads',    value: '184',   color: 'text-sky-600',    bg: 'bg-sky-50',    icon: Target      },
                    { label: 'Avg Deal Size',   value: '৳1.8L', color: 'text-violet-600', bg: 'bg-violet-50', icon: TrendingUp  },
                    { label: 'Win Rate',        value: '62.4%', color: 'text-green-600',  bg: 'bg-green-50',  icon: Percent     },
                    { label: 'Avg Sales Cycle', value: '18 d',  color: 'text-orange-600', bg: 'bg-orange-50', icon: Clock       },
                ].map((m) => (
                    <Card key={m.label} className="border-[#d8d8d8] 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-[#6d7175]">{m.label}</p>
                                <p className={`text-lg font-bold ${m.color}`}>{m.value}</p>
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {/* Pipeline Performance + Conversion Trend */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-7">
                <Card className="col-span-1 border-[#d8d8d8] shadow-sm lg:col-span-4">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Pipeline Performance</CardTitle>
                        <CardDescription>Won vs Lost vs Active pipeline by month</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={monthlyPipeline}>
                                    <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="won"      name="Won"      fill="#22c55e" radius={[3, 3, 0, 0]} />
                                    <Bar dataKey="lost"     name="Lost"     fill="#ef4444" radius={[3, 3, 0, 0]} />
                                    <Bar dataKey="pipeline" name="Pipeline" fill="#0ea5e9" radius={[3, 3, 0, 0]} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                <Card className="col-span-1 border-[#d8d8d8] shadow-sm lg:col-span-3">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Conversion Rate Trend</CardTitle>
                        <CardDescription>Weekly deal conversion % over 8 weeks</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <LineChart data={conversionTrend}>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                    <XAxis dataKey="week" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} tickFormatter={(v) => `${v}%`} domain={[0, 100]} />
                                    <Tooltip formatter={(v) => `${v}%`} />
                                    <Line type="monotone" dataKey="rate" stroke="#0ea5e9" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} name="Conv. Rate" />
                                </LineChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Sales by Rep + Lead Sources */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-7">
                <Card className="col-span-1 border-[#d8d8d8] shadow-sm lg:col-span-4">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Sales by Rep</CardTitle>
                        <CardDescription>Deals won vs lost per sales representative</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-52">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={salesByRep}>
                                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
                                    <XAxis dataKey="rep" tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#6d7175' }} axisLine={false} tickLine={false} />
                                    <Tooltip />
                                    <Legend />
                                    <Bar dataKey="won"  name="Won"  fill="#22c55e" radius={[3, 3, 0, 0]} barSize={18} />
                                    <Bar dataKey="lost" name="Lost" fill="#ef4444" radius={[3, 3, 0, 0]} barSize={18} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                <Card className="col-span-1 border-[#d8d8d8] shadow-sm lg:col-span-3">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Lead Sources</CardTitle>
                        <CardDescription>Where incoming leads originate</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-52">
                            <ResponsiveContainer width="100%" height="100%">
                                <PieChart>
                                    <Pie data={leadSources} cx="50%" cy="50%" innerRadius={48} outerRadius={78} dataKey="value" label={({ name, value }) => `${value}%`}>
                                        {leadSources.map((_, i) => (
                                            <Cell key={i} fill={SOURCE_COLORS[i % SOURCE_COLORS.length]} />
                                        ))}
                                    </Pie>
                                    <Tooltip formatter={(v) => `${v}%`} />
                                    <Legend />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Revenue Forecast */}
            <Card className="border-[#d8d8d8] shadow-sm">
                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                    <CardTitle className="text-base font-semibold text-[#202223]">Revenue Forecast</CardTitle>
                    <CardDescription>Actual revenue vs projected through year-end (৳)</CardDescription>
                </CardHeader>
                <CardContent className="pt-4">
                    <div className="h-52">
                        <ResponsiveContainer width="100%" height="100%">
                            <LineChart data={combinedTrend}>
                                <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 ? `৳${v.toLocaleString()}` : '—'} />
                                <Legend />
                                <Line type="monotone" dataKey="actual"   name="Actual"   stroke="#22c55e" strokeWidth={2} dot={{ r: 3 }} connectNulls={false} />
                                <Line type="monotone" dataKey="forecast" name="Forecast"  stroke="#0ea5e9" strokeWidth={2} dot={{ r: 3 }} strokeDasharray="5 4" />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>
                </CardContent>
            </Card>

            {/* Pipeline Funnel + Recent Deals */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
                <Card className="border-[#d8d8d8] shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Pipeline Funnel</CardTitle>
                        <CardDescription>Orders by stage</CardDescription>
                    </CardHeader>
                    <CardContent className="p-4">
                        {pipelineFunnel.length === 0 ? (
                            <p className="py-4 text-center text-xs text-gray-400">No pipeline data yet</p>
                        ) : (
                            <div className="space-y-2">
                                {pipelineFunnel.map((stage, i) => {
                                    const pct = maxFunnelValue > 0 ? Math.round((stage.value / maxFunnelValue) * 100) : 0;
                                    return (
                                        <div key={stage.name}>
                                            <div className="mb-1 flex items-center justify-between text-xs">
                                                <span className="font-medium text-[#202223]">{stage.name}</span>
                                                <span className="text-[#6d7175]">{stage.value} orders</span>
                                            </div>
                                            <div className="h-6 overflow-hidden rounded bg-[#f1f5f9]">
                                                <div
                                                    className="flex h-full items-center justify-end px-2 text-xs font-semibold text-white transition-all"
                                                    style={{ width: `${Math.max(pct, 5)}%`, backgroundColor: FUNNEL_COLORS[i % FUNNEL_COLORS.length] }}
                                                >
                                                    {pct}%
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </CardContent>
                </Card>

                <Card className="border-[#d8d8d8] shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Recent Deals</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-[#6d7175] uppercase">
                                    <th className="px-4 py-2">Deal</th>
                                    <th className="px-4 py-2">Value</th>
                                    <th className="px-4 py-2">Stage</th>
                                    <th className="px-4 py-2"><Clock className="h-3 w-3" /></th>
                                </tr>
                            </thead>
                            <tbody>
                                {recentDeals.length === 0 ? (
                                    <tr><td colSpan={4} className="px-4 py-6 text-center text-xs text-gray-400">No deals yet</td></tr>
                                ) : (
                                    recentDeals.map((d, i) => (
                                        <tr key={i} className="border-b border-[#efefef] text-[#202223]">
                                            <td className="px-4 py-2.5">
                                                <p className="text-xs font-medium">{d.name}</p>
                                                <p className="text-xs text-[#6d7175]">{d.rep}</p>
                                            </td>
                                            <td className="px-4 py-2.5 text-xs font-semibold">{d.value}</td>
                                            <td className="px-4 py-2.5">
                                                <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${stageColors[d.stage] ?? 'bg-gray-100 text-gray-700'}`}>{d.stage}</span>
                                            </td>
                                            <td className="px-4 py-2.5 text-xs text-[#6d7175]">{d.daysOpen === 0 ? 'Closed' : `${d.daysOpen}d`}</td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>
            </div>

            {/* Rep Performance table */}
            <Card className="border-[#d8d8d8] shadow-sm">
                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                    <CardTitle className="text-base font-semibold text-[#202223]">Rep Performance</CardTitle>
                    <CardDescription>Deals won, lost, and revenue per sales representative</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-[#6d7175] uppercase">
                                <th className="px-4 py-2">Rep</th>
                                <th className="px-4 py-2">Won</th>
                                <th className="px-4 py-2">Lost</th>
                                <th className="px-4 py-2">Pipeline</th>
                                <th className="px-4 py-2">Revenue</th>
                            </tr>
                        </thead>
                        <tbody>
                            {repPerformance.map((r) => (
                                <tr key={r.name} className="border-b border-[#efefef] text-[#202223]">
                                    <td className="px-4 py-2.5 text-xs font-medium">{r.name}</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">{r.won}</span></td>
                                    <td className="px-4 py-2.5"><span className="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-800">{r.lost}</span></td>
                                    <td className="px-4 py-2.5"><span className="rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800">{r.pipeline}</span></td>
                                    <td className="px-4 py-2.5 text-xs font-semibold">{r.revenue}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </CardContent>
            </Card>
        </div>
    );
}
