'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  PieChart,
  Pie,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Legend,
} from 'recharts';
import {
  BarChart3,
  TrendingUp,
  Shield,
  CreditCard,
  AlertTriangle,
  ShieldCheck,
  MapPin,
  Activity,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useAppStore } from '@/store/app-store';
import type { AnalyticsData } from '@/types';

// ─── Helpers ────────────────────────────────────────────────────────────────

function formatBDT(amount: number): string {
  if (amount >= 10000000) return `৳${(amount / 10000000).toFixed(1)}Cr`;
  if (amount >= 100000) return `৳${(amount / 100000).toFixed(1)}L`;
  if (amount >= 1000) return `৳${(amount / 1000).toFixed(1)}K`;
  return `৳${amount.toLocaleString('en-BD')}`;
}

// ─── Chart Colors ───────────────────────────────────────────────────────────

const CHART_COLORS = {
  emerald: '#10b981',
  teal: '#14b8a6',
  cyan: '#06b6d4',
  green: '#22c55e',
  yellow: '#eab308',
  orange: '#f97316',
  red: '#ef4444',
  rose: '#f43f5e',
};

const RISK_COLORS = {
  low: '#10b981',
  medium: '#eab308',
  high: '#f97316',
  critical: '#ef4444',
};

const CATEGORY_COLORS = [
  '#10b981',
  '#14b8a6',
  '#06b6d4',
  '#22c55e',
  '#8b5cf6',
  '#f59e0b',
  '#ef4444',
  '#ec4899',
  '#6366f1',
  '#84cc16',
];

// ─── Custom Tooltip ─────────────────────────────────────────────────────────

function CustomTooltip({ active, payload, label }: { active?: boolean; payload?: Array<{ name: string; value: number; color?: string }>; label?: string }) {
  if (!active || !payload || !payload.length) return null;
  return (
    <div className="rounded-lg border bg-background/95 backdrop-blur-sm p-3 shadow-xl text-sm">
      <p className="font-medium mb-1">{label}</p>
      {payload.map((entry, index) => (
        <div key={index} className="flex items-center gap-2">
          <div className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: entry.color }} />
          <span className="text-muted-foreground">{entry.name}:</span>
          <span className="font-semibold">
            {entry.name.toLowerCase().includes('amount') ? formatBDT(entry.value) : entry.value.toLocaleString()}
          </span>
        </div>
      ))}
    </div>
  );
}

// ─── Animation Variants ─────────────────────────────────────────────────────

const containerVariants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.08 } },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.4, ease: 'easeOut' } },
};

// ─── Skeleton Loader ────────────────────────────────────────────────────────

function ChartSkeleton() {
  return (
    <div className="space-y-4 p-4">
      <Skeleton className="h-5 w-32" />
      <Skeleton className="h-[280px] w-full rounded-xl" />
    </div>
  );
}

// ─── Main Component ─────────────────────────────────────────────────────────

export function AnalyticsPage() {
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetch('/api/analytics')
      .then((res) => res.json())
      .then((data) => {
        if (data.success) setAnalytics(data.data);
      })
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, []);

  // Prepare chart data
  const categoryData = (analytics?.topCategories || []).map((cat) => ({
    name: cat.name,
    count: cat.count,
  }));

  const dailyTrendData = (analytics?.dailyTrends || []).map((day) => ({
    date: new Date(day.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }),
    count: day.count,
    amount: day.amount,
  }));

  const riskData = analytics
    ? [
        { name: 'Low', value: analytics.riskDistribution.low, color: RISK_COLORS.low },
        { name: 'Medium', value: analytics.riskDistribution.medium, color: RISK_COLORS.medium },
        { name: 'High', value: analytics.riskDistribution.high, color: RISK_COLORS.high },
        { name: 'Critical', value: analytics.riskDistribution.critical, color: RISK_COLORS.critical },
      ]
    : [];

  const districtData = (analytics?.topDistricts || []).map((d) => ({
    district: d.district,
    count: d.count,
  }));

  const amountTrendData = (analytics?.dailyTrends || []).map((day) => ({
    date: new Date(day.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }),
    amount: day.amount,
  }));

  const totalRiskCount = riskData.reduce((sum, d) => sum + d.value, 0);

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
      <motion.div variants={containerVariants} initial="hidden" animate="visible">
        {/* ─── Header ────────────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mb-8">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 rounded-xl bg-emerald-500/10">
              <BarChart3 className="h-6 w-6 text-emerald-500" />
            </div>
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold">Analytics Dashboard</h1>
              <p className="text-muted-foreground text-sm sm:text-base">
                Insights into scam patterns and trends in Bangladesh
              </p>
            </div>
          </div>
        </motion.div>

        {/* ─── Stats Overview ─────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mb-8">
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
            {[
              {
                icon: Shield,
                label: 'Total Reports',
                value: analytics?.totalReports ?? 0,
                color: 'text-emerald-500',
                bgIcon: 'bg-emerald-500/10',
              },
              {
                icon: CreditCard,
                label: 'Total Amount Lost',
                value: null,
                display: analytics ? formatBDT(analytics.totalAmount) : '৳0',
                color: 'text-red-500',
                bgIcon: 'bg-red-500/10',
              },
              {
                icon: ShieldCheck,
                label: 'Verified Reports',
                value: analytics?.verifiedReports ?? 0,
                color: 'text-teal-500',
                bgIcon: 'bg-teal-500/10',
              },
              {
                icon: AlertTriangle,
                label: 'Critical Entities',
                value: analytics?.criticalEntities ?? 0,
                color: 'text-orange-500',
                bgIcon: 'bg-orange-500/10',
              },
            ].map((stat, idx) => (
              <motion.div
                key={stat.label}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 + idx * 0.08, duration: 0.4 }}
              >
                <Card className="glass border-0 shadow-lg hover:shadow-xl transition-shadow">
                  <CardContent className="p-4 sm:p-6 flex items-center gap-3 sm:gap-4">
                    <div className={`${stat.bgIcon} p-2.5 sm:p-3 rounded-xl`}>
                      <stat.icon className={`h-5 w-5 sm:h-6 sm:w-6 ${stat.color}`} />
                    </div>
                    <div className="min-w-0">
                      <div className="text-xl sm:text-2xl font-bold truncate">
                        {isLoading ? (
                          <Skeleton className="h-7 w-16" />
                        ) : (
                          stat.display || (stat.value ?? 0).toLocaleString()
                        )}
                      </div>
                      <p className="text-xs sm:text-sm text-muted-foreground">{stat.label}</p>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            ))}
          </div>
        </motion.div>

        {/* ─── Charts Grid ────────────────────────────────────────────────── */}
        <div className="grid lg:grid-cols-2 gap-4 sm:gap-6">
          {/* ── Category Distribution Chart ── */}
          <motion.div variants={itemVariants}>
            <Card className="glass border-0 shadow-lg h-full">
              <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <BarChart3 className="h-5 w-5 text-emerald-500" />
                  Top Categories
                </CardTitle>
                <CardDescription>Reports by scam category</CardDescription>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <ChartSkeleton />
                ) : (
                  <ResponsiveContainer width="100%" height={300}>
                    <BarChart data={categoryData} margin={{ top: 5, right: 10, left: -10, bottom: 5 }}>
                      <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.3} />
                      <XAxis
                        dataKey="name"
                        tick={{ fontSize: 12 }}
                        tickLine={false}
                        axisLine={false}
                        interval={0}
                        angle={-30}
                        textAnchor="end"
                        height={60}
                      />
                      <YAxis tick={{ fontSize: 12 }} tickLine={false} axisLine={false} />
                      <Tooltip content={<CustomTooltip />} />
                      <Bar dataKey="count" name="Reports" radius={[6, 6, 0, 0]} maxBarSize={50}>
                        {categoryData.map((_, index) => (
                          <Cell key={index} fill={CATEGORY_COLORS[index % CATEGORY_COLORS.length]} />
                        ))}
                      </Bar>
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </CardContent>
            </Card>
          </motion.div>

          {/* ── Risk Distribution Pie Chart ── */}
          <motion.div variants={itemVariants}>
            <Card className="glass border-0 shadow-lg h-full">
              <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <AlertTriangle className="h-5 w-5 text-orange-500" />
                  Risk Distribution
                </CardTitle>
                <CardDescription>Reports by risk level</CardDescription>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <ChartSkeleton />
                ) : totalRiskCount === 0 ? (
                  <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                    No risk data available
                  </div>
                ) : (
                  <ResponsiveContainer width="100%" height={300}>
                    <PieChart>
                      <Pie
                        data={riskData}
                        cx="50%"
                        cy="50%"
                        innerRadius={70}
                        outerRadius={110}
                        paddingAngle={3}
                        dataKey="value"
                        nameKey="name"
                        label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                        labelLine={false}
                      >
                        {riskData.map((entry, index) => (
                          <Cell key={index} fill={entry.color} strokeWidth={2} />
                        ))}
                      </Pie>
                      <Tooltip
                        content={({ active, payload }) => {
                          if (!active || !payload?.length) return null;
                          const data = payload[0];
                          return (
                            <div className="rounded-lg border bg-background/95 backdrop-blur-sm p-3 shadow-xl text-sm">
                              <p className="font-medium">{data.name}</p>
                              <p className="text-muted-foreground">
                                {data.value?.toLocaleString()} reports ({totalRiskCount > 0 ? ((Number(data.value) / totalRiskCount) * 100).toFixed(1) : 0}%)
                              </p>
                            </div>
                          );
                        }}
                      />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                )}
              </CardContent>
            </Card>
          </motion.div>

          {/* ── Daily Trend Line Chart ── */}
          <motion.div variants={itemVariants}>
            <Card className="glass border-0 shadow-lg h-full">
              <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <TrendingUp className="h-5 w-5 text-teal-500" />
                  Daily Report Trend
                </CardTitle>
                <CardDescription>Report count over time</CardDescription>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <ChartSkeleton />
                ) : (
                  <ResponsiveContainer width="100%" height={300}>
                    <LineChart data={dailyTrendData} margin={{ top: 5, right: 10, left: -10, bottom: 5 }}>
                      <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.3} />
                      <XAxis
                        dataKey="date"
                        tick={{ fontSize: 11 }}
                        tickLine={false}
                        axisLine={false}
                        interval="preserveStartEnd"
                      />
                      <YAxis tick={{ fontSize: 12 }} tickLine={false} axisLine={false} />
                      <Tooltip content={<CustomTooltip />} />
                      <Line
                        type="monotone"
                        dataKey="count"
                        name="Reports"
                        stroke={CHART_COLORS.emerald}
                        strokeWidth={2.5}
                        dot={{ fill: CHART_COLORS.emerald, r: 3 }}
                        activeDot={{ r: 5, fill: CHART_COLORS.emerald }}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                )}
              </CardContent>
            </Card>
          </motion.div>

          {/* ── Amount Lost Area Chart ── */}
          <motion.div variants={itemVariants}>
            <Card className="glass border-0 shadow-lg h-full">
              <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <CreditCard className="h-5 w-5 text-red-500" />
                  Amount Lost Trend
                </CardTitle>
                <CardDescription>Financial losses over time</CardDescription>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <ChartSkeleton />
                ) : (
                  <ResponsiveContainer width="100%" height={300}>
                    <AreaChart data={amountTrendData} margin={{ top: 5, right: 10, left: -10, bottom: 5 }}>
                      <defs>
                        <linearGradient id="amountGradient" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor={CHART_COLORS.red} stopOpacity={0.3} />
                          <stop offset="95%" stopColor={CHART_COLORS.red} stopOpacity={0.02} />
                        </linearGradient>
                      </defs>
                      <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.3} />
                      <XAxis
                        dataKey="date"
                        tick={{ fontSize: 11 }}
                        tickLine={false}
                        axisLine={false}
                        interval="preserveStartEnd"
                      />
                      <YAxis tick={{ fontSize: 12 }} tickLine={false} axisLine={false} />
                      <Tooltip content={<CustomTooltip />} />
                      <Area
                        type="monotone"
                        dataKey="amount"
                        name="Amount Lost"
                        stroke={CHART_COLORS.red}
                        strokeWidth={2.5}
                        fill="url(#amountGradient)"
                      />
                    </AreaChart>
                  </ResponsiveContainer>
                )}
              </CardContent>
            </Card>
          </motion.div>
        </div>

        {/* ─── Top Districts ──────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mt-4 sm:mt-6">
          <Card className="glass border-0 shadow-lg">
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-lg">
                <MapPin className="h-5 w-5 text-cyan-500" />
                Top Affected Districts
              </CardTitle>
              <CardDescription>Districts with most scam reports</CardDescription>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <div className="space-y-3">
                  {[1, 2, 3, 4, 5].map((i) => (
                    <div key={i} className="flex items-center gap-3">
                      <Skeleton className="h-4 w-24" />
                      <Skeleton className="h-4 flex-1" />
                      <Skeleton className="h-4 w-10" />
                    </div>
                  ))}
                </div>
              ) : districtData.length === 0 ? (
                <div className="py-12 text-center text-muted-foreground">
                  No district data available
                </div>
              ) : (
                <div className="space-y-3">
                  {districtData.map((d, idx) => {
                    const maxCount = districtData[0]?.count || 1;
                    const percentage = (d.count / maxCount) * 100;
                    return (
                      <motion.div
                        key={d.district}
                        initial={{ opacity: 0, x: -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: idx * 0.05, duration: 0.3 }}
                        className="flex items-center gap-3"
                      >
                        <span className="text-sm font-medium w-28 sm:w-36 truncate">
                          {d.district}
                        </span>
                        <div className="flex-1 h-7 bg-muted/50 rounded-full overflow-hidden relative">
                          <motion.div
                            initial={{ width: 0 }}
                            animate={{ width: `${percentage}%` }}
                            transition={{ delay: 0.3 + idx * 0.05, duration: 0.6, ease: 'easeOut' }}
                            className="h-full rounded-full bg-gradient-to-r from-emerald-500 to-teal-400"
                          />
                        </div>
                        <span className="text-sm font-semibold text-muted-foreground w-12 text-right">
                          {d.count}
                        </span>
                      </motion.div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </motion.div>
      </motion.div>
    </div>
  );
}
