"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import {
  BarChart3, TrendingUp, Eye, GitCompare, Zap,
  Award, ChevronLeft, ChevronRight, RefreshCw,
  Calendar, Car, Users, ArrowUpRight, ArrowDownRight, Minus,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { fetchLatestReport, fetchReportByWeek, fetchReportsList } from "@/lib/api";
import { resolveCarHeroImage } from "@/lib/carImage";
import type { WeeklyReport, WeeklyReportSummary, ReportCar, ReportBrand, ReportEV } from "@/lib/types";

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

function fmtINR(n?: number): string {
  if (!n) return "—";
  if (n >= 10_000_000) return `₹${(n / 10_000_000).toFixed(1)} Cr`;
  if (n >= 100_000)    return `₹${(n / 100_000).toFixed(1)} L`;
  return `₹${n.toLocaleString("en-IN")}`;
}

function fmtWeek(weekStr: string): string {
  // "2026-W23" → "Jun 2 – Jun 8, 2026"
  try {
    const [yr, wk] = weekStr.split("-W").map(Number);
    const monday = new Date(Date.UTC(yr, 0, 1 + (wk - 1) * 7));
    monday.setUTCDate(monday.getUTCDate() - monday.getUTCDay() + 1);
    const sunday = new Date(monday);
    sunday.setUTCDate(monday.getUTCDate() + 6);
    const fmt = (d: Date) =>
      d.toLocaleDateString("en-IN", { month: "short", day: "numeric", timeZone: "UTC" });
    return `${fmt(monday)} – ${fmt(sunday)}, ${yr}`;
  } catch {
    return weekStr;
  }
}

const MEDAL = ["🥇", "🥈", "🥉"];
const FUEL_COLOR: Record<string, string> = {
  Petrol: "bg-orange-100 text-orange-700",
  Diesel: "bg-blue-100 text-blue-700",
  Electric: "bg-emerald-100 text-emerald-700",
  CNG: "bg-green-100 text-green-700",
  Hybrid: "bg-teal-100 text-teal-700",
};

// ── Small shared components ────────────────────────────────────────────────────

function CarThumb({ car }: { car: ReportCar }) {
  const heroSrc = resolveCarHeroImage({ imageUrl: car.imageUrl });
  if (!heroSrc) {
    return (
      <div className="w-14 h-10 rounded-lg bg-gray-100 flex items-center justify-center shrink-0">
        <Car className="w-5 h-5 text-gray-300" />
      </div>
    );
  }
  return (
    <div className="w-14 h-10 rounded-lg overflow-hidden bg-gray-100 shrink-0">
      <Image
        src={heroSrc} alt={car.name}
        width={56} height={40}
        className="w-full h-full object-cover"
        unoptimized
      />
    </div>
  );
}

function RankBadge({ rank }: { rank: number }) {
  if (rank <= 3) {
    return <span className="text-xl w-7 text-center">{MEDAL[rank - 1]}</span>;
  }
  return (
    <span className="w-7 text-center text-sm font-bold text-gray-400">
      #{rank}
    </span>
  );
}

function StatChip({ icon: Icon, value, label, color }: {
  icon: React.ElementType; value: string | number; label: string; color: string;
}) {
  return (
    <div className={cn("flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-xs font-semibold", color)}>
      <Icon className="w-3 h-3" />
      <span>{value.toLocaleString()}</span>
      <span className="font-normal opacity-70">{label}</span>
    </div>
  );
}

// ── Section: Popular Cars ──────────────────────────────────────────────────────

function PopularCarsSection({ cars }: { cars: ReportCar[] }) {
  if (!cars.length) return <EmptySection msg="No car data yet this week." />;
  return (
    <div className="space-y-1">
      {cars.map((car, i) => (
        <motion.div
          key={car.carId}
          initial={{ opacity: 0, x: -10 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: i * 0.04 }}
        >
          <Link
            href={`/cars/${car.slug || car.carId}`}
            className="flex flex-col gap-2 p-3 rounded-2xl hover:bg-gray-50 transition-colors group sm:flex-row sm:items-center sm:gap-3"
          >
            <div className="flex items-center gap-3 min-w-0 flex-1">
              <RankBadge rank={i + 1} />
              <CarThumb car={car} />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-gray-900 truncate group-hover:text-blue-600 transition-colors">
                  {car.brand} {car.name}
                </p>
                <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                  {car.fuelType && (
                    <span className={cn("text-[10px] font-semibold px-2 py-0.5 rounded-full", FUEL_COLOR[car.fuelType] ?? "bg-gray-100 text-gray-600")}>
                      {car.fuelType}
                    </span>
                  )}
                  {car.priceMin ? (
                    <span className="text-xs text-gray-400">{fmtINR(car.priceMin)}</span>
                  ) : null}
                </div>
              </div>
            </div>
            <div className="flex gap-3 shrink-0 self-end pl-10 sm:pl-0 sm:self-auto">
              <div className="text-right">
                <p className="text-xs sm:text-sm font-bold text-blue-600 tabular-nums">{car.viewCount.toLocaleString()}</p>
                <p className="text-[10px] text-gray-400">views</p>
              </div>
              <div className="text-right">
                <p className="text-xs sm:text-sm font-bold text-violet-600 tabular-nums">{car.compareCount.toLocaleString()}</p>
                <p className="text-[10px] text-gray-400">compares</p>
              </div>
            </div>
          </Link>
          {i < cars.length - 1 && <div className="mx-3 h-px bg-gray-100" />}
        </motion.div>
      ))}
    </div>
  );
}

// ── Section: Popular Brands ────────────────────────────────────────────────────

function BrandInitial({ brand }: { brand: string }) {
  const colors = [
    "bg-blue-100 text-blue-700", "bg-violet-100 text-violet-700",
    "bg-emerald-100 text-emerald-700", "bg-amber-100 text-amber-700",
    "bg-rose-100 text-rose-700", "bg-cyan-100 text-cyan-700",
  ];
  const idx = brand.charCodeAt(0) % colors.length;
  return (
    <div className={cn("w-10 h-10 rounded-xl flex items-center justify-center text-lg font-black shrink-0", colors[idx])}>
      {brand[0]}
    </div>
  );
}

function PopularBrandsSection({ brands }: { brands: ReportBrand[] }) {
  if (!brands.length) return <EmptySection msg="No brand data yet this week." />;
  return (
    <div className="space-y-1">
      {brands.map((b, i) => (
        <motion.div
          key={b.brand}
          initial={{ opacity: 0, x: -10 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: i * 0.04 }}
        >
          <Link
            href={`/brands/${b.brand.toLowerCase().replace(/\s+/g, "-")}`}
            className="flex flex-col gap-2 p-3 rounded-2xl hover:bg-gray-50 transition-colors group sm:flex-row sm:items-center sm:gap-3"
          >
            <div className="flex items-center gap-3 min-w-0 flex-1">
              <RankBadge rank={i + 1} />
              <BrandInitial brand={b.brand} />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-gray-900 truncate group-hover:text-blue-600 transition-colors">
                  {b.brand}
                </p>
                {b.topCar?.name && (
                  <p className="text-xs text-gray-400 truncate mt-0.5">
                    Top: {b.topCar.brand} {b.topCar.name}
                  </p>
                )}
              </div>
            </div>
            <div className="flex gap-3 shrink-0 self-end pl-10 sm:pl-0 sm:self-auto">
              <div className="text-right">
                <p className="text-xs sm:text-sm font-bold text-blue-600 tabular-nums">{b.viewCount.toLocaleString()}</p>
                <p className="text-[10px] text-gray-400">views</p>
              </div>
              <div className="text-right">
                <p className="text-xs sm:text-sm font-bold text-violet-600 tabular-nums">{b.compareCount.toLocaleString()}</p>
                <p className="text-[10px] text-gray-400">compares</p>
              </div>
            </div>
          </Link>
          {i < brands.length - 1 && <div className="mx-3 h-px bg-gray-100" />}
        </motion.div>
      ))}
    </div>
  );
}

// ── Section: Fastest Growing EVs ───────────────────────────────────────────────

function GrowthBadge({ pct }: { pct: number }) {
  if (pct > 5) {
    return (
      <div className="flex items-center gap-1 px-2 py-1 rounded-lg bg-emerald-50 border border-emerald-200">
        <ArrowUpRight className="w-3.5 h-3.5 text-emerald-600" />
        <span className="text-xs font-bold text-emerald-700">+{pct.toFixed(0)}%</span>
      </div>
    );
  }
  if (pct < -5) {
    return (
      <div className="flex items-center gap-1 px-2 py-1 rounded-lg bg-red-50 border border-red-200">
        <ArrowDownRight className="w-3.5 h-3.5 text-red-500" />
        <span className="text-xs font-bold text-red-600">{pct.toFixed(0)}%</span>
      </div>
    );
  }
  return (
    <div className="flex items-center gap-1 px-2 py-1 rounded-lg bg-gray-50 border border-gray-200">
      <Minus className="w-3.5 h-3.5 text-gray-400" />
      <span className="text-xs font-bold text-gray-500">Stable</span>
    </div>
  );
}

function FastestEvSection({ evs }: { evs: ReportEV[] }) {
  if (!evs.length) return <EmptySection msg="No EV data yet this week." />;
  return (
    <div className="space-y-1">
      {evs.map((car, i) => (
        <motion.div
          key={car.carId}
          initial={{ opacity: 0, x: -10 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: i * 0.04 }}
        >
          <Link
            href={`/cars/${car.slug || car.carId}`}
            className="flex flex-col gap-2 p-3 rounded-2xl hover:bg-gray-50 transition-colors group sm:flex-row sm:items-center sm:gap-3"
          >
            <div className="flex items-center gap-3 min-w-0 flex-1">
              <RankBadge rank={i + 1} />
              <CarThumb car={car} />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-gray-900 truncate group-hover:text-blue-600 transition-colors">
                  {car.brand} {car.name}
                </p>
                <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                  <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700">
                    ⚡ Electric
                  </span>
                  {car.priceMin ? (
                    <span className="text-xs text-gray-400">{fmtINR(car.priceMin)}</span>
                  ) : null}
                </div>
              </div>
            </div>
            <div className="flex flex-col items-end gap-1 shrink-0 self-end pl-10 sm:pl-0 sm:self-auto">
              <GrowthBadge pct={car.growthPct} />
              <p className="text-[10px] text-gray-400 tabular-nums">
                {car.viewCount.toLocaleString()} views this week
              </p>
            </div>
          </Link>
          {i < evs.length - 1 && <div className="mx-3 h-px bg-gray-100" />}
        </motion.div>
      ))}
    </div>
  );
}

// ── Section: Most Viewed / Most Compared (shared) ─────────────────────────────

function ViewedComparedSection({
  cars,
  metricKey,
  metricLabel,
  metricColor,
}: {
  cars:        ReportCar[];
  metricKey:   "viewCount" | "compareCount";
  metricLabel: string;
  metricColor: string;
}) {
  if (!cars.length) return <EmptySection msg="No data yet this week." />;
  const max = Math.max(...cars.map((c) => c[metricKey])) || 1;
  return (
    <div className="space-y-1">
      {cars.map((car, i) => {
        const val = car[metricKey];
        const pct = (val / max) * 100;
        return (
          <motion.div
            key={car.carId}
            initial={{ opacity: 0, x: -10 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: i * 0.04 }}
          >
            <Link
              href={`/cars/${car.slug || car.carId}`}
              className="flex flex-col gap-2 p-3 rounded-2xl hover:bg-gray-50 transition-colors group sm:flex-row sm:items-center sm:gap-3"
            >
              <div className="flex items-center gap-3 min-w-0 flex-1">
                <RankBadge rank={i + 1} />
                <CarThumb car={car} />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-bold text-gray-900 truncate group-hover:text-blue-600 transition-colors">
                    {car.brand} {car.name}
                  </p>
                  {/* Horizontal fill bar */}
                  <div className="mt-1.5 w-full h-1.5 rounded-full bg-gray-100 overflow-hidden">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${pct}%` }}
                      transition={{ duration: 0.5, delay: i * 0.06 }}
                      className={cn("h-full rounded-full", metricColor)}
                    />
                  </div>
                </div>
              </div>
              <div className="text-right shrink-0 self-end pl-10 sm:pl-0 sm:ml-3 sm:self-auto">
                <p className={cn("text-sm sm:text-base font-black tabular-nums", metricColor.replace("bg-", "text-").replace("-500", "-600"))}>
                  {val.toLocaleString()}
                </p>
                <p className="text-[10px] text-gray-400">{metricLabel}</p>
              </div>
            </Link>
            {i < cars.length - 1 && <div className="mx-3 h-px bg-gray-100" />}
          </motion.div>
        );
      })}
    </div>
  );
}

// ── Empty state ────────────────────────────────────────────────────────────────

function EmptySection({ msg }: { msg: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-12 text-gray-400 gap-2">
      <BarChart3 className="w-8 h-8" />
      <p className="text-sm">{msg}</p>
    </div>
  );
}

// ── Tab config ─────────────────────────────────────────────────────────────────

const TABS = [
  { id: "popular",   label: "Popular Cars",      icon: Award,      color: "text-blue-600",   count: (r: WeeklyReport) => r.popularCars.length       },
  { id: "brands",    label: "Popular Brands",    icon: Users,      color: "text-violet-600", count: (r: WeeklyReport) => r.popularBrands.length     },
  { id: "evs",       label: "Fastest EVs",       icon: Zap,        color: "text-emerald-600",count: (r: WeeklyReport) => r.fastestGrowingEvs.length },
  { id: "viewed",    label: "Most Viewed",        icon: Eye,        color: "text-amber-600",  count: (r: WeeklyReport) => r.mostViewedCars.length    },
  { id: "compared",  label: "Most Compared",     icon: GitCompare, color: "text-rose-600",   count: (r: WeeklyReport) => r.mostComparedCars.length  },
] as const;

type TabId = typeof TABS[number]["id"];

// ── Main page ──────────────────────────────────────────────────────────────────

export default function ReportsPage() {
  const [report,   setReport]   = useState<WeeklyReport | null>(null);
  const [history,  setHistory]  = useState<WeeklyReportSummary[]>([]);
  const [loading,  setLoading]  = useState(true);
  const [tab,      setTab]      = useState<TabId>("popular");
  const [weekIdx,  setWeekIdx]  = useState(0);   // 0 = latest

  const loadReport = useCallback(async (week?: string) => {
    setLoading(true);
    const data = week
      ? await fetchReportByWeek(week)
      : await fetchLatestReport();
    setReport(data);
    setLoading(false);
  }, []);

  useEffect(() => {
    fetchReportsList().then(setHistory);
    loadReport();
  }, []); // eslint-disable-line

  function goWeek(delta: number) {
    const newIdx = weekIdx + delta;
    if (newIdx < 0 || newIdx >= history.length) return;
    setWeekIdx(newIdx);
    loadReport(history[newIdx].week);
  }

  const canPrev = weekIdx < history.length - 1;
  const canNext = weekIdx > 0;

  return (
    <main className="min-h-screen bg-[#f5f7fb]">

      {/* ── Hero ──────────────────────────────────────────────────────────── */}
      <div className="bg-gradient-to-br from-gray-900 via-blue-950 to-indigo-900 text-white">
        <div className="max-w-[1280px] mx-auto px-4 py-8 md:py-12">

          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div className="min-w-0 flex-1">
              <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 text-xs font-bold mb-4">
                <BarChart3 className="w-3.5 h-3.5 text-blue-300" />
                Weekly Insights
              </div>
              <h1 className="text-3xl sm:text-4xl md:text-5xl font-black mb-2">
                Trend Report
              </h1>
              <p className="text-blue-200 text-sm flex items-center gap-2 min-w-0">
                <Calendar className="w-3.5 h-3.5 shrink-0" />
                <span className="truncate">{report ? fmtWeek(report.week) : "Loading…"}</span>
              </p>
            </div>

            {/* Week navigator */}
            <div className="flex items-center gap-2 flex-wrap w-full sm:w-auto sm:justify-end min-w-0">
              <button
                onClick={() => goWeek(1)}
                disabled={!canPrev}
                className="p-2 rounded-xl border border-white/20 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-colors shrink-0"
                title="Previous week"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <select
                className="bg-white/10 border border-white/20 rounded-xl px-3 py-2 text-xs sm:text-sm font-medium text-white focus:outline-none appearance-none min-w-0 flex-1 sm:flex-none max-w-full sm:max-w-[11rem]"
                value={weekIdx}
                onChange={(e) => {
                  const idx = Number(e.target.value);
                  setWeekIdx(idx);
                  loadReport(history[idx].week);
                }}
              >
                {history.map((h, i) => (
                  <option key={h.week} value={i} className="bg-gray-900 text-white">
                    {h.week} {i === 0 ? "(Latest)" : ""}
                  </option>
                ))}
                {!history.length && (
                  <option value={0}>Current week</option>
                )}
              </select>
              <button
                onClick={() => goWeek(-1)}
                disabled={!canNext}
                className="p-2 rounded-xl border border-white/20 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-colors shrink-0"
                title="Next week"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
              <button
                onClick={() => { setWeekIdx(0); loadReport(); }}
                className="p-2 rounded-xl border border-white/20 hover:bg-white/10 transition-colors shrink-0"
                title="Refresh"
              >
                <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} />
              </button>
            </div>
          </div>

          {/* Summary stats */}
          {report && (
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4 mt-6 sm:mt-8">
              {[
                { label: "Total Views",       value: report.totalViews,       icon: Eye,        color: "from-blue-500/20 to-blue-600/20"    },
                { label: "Total Compares",    value: report.totalCompares,    icon: GitCompare, color: "from-violet-500/20 to-violet-600/20" },
                { label: "Cars Tracked",      value: report.uniqueCarsViewed, icon: Car,        color: "from-emerald-500/20 to-emerald-600/20"},
              ].map(({ label, value, icon: Icon, color }) => (
                <div
                  key={label}
                  className={cn(
                    "rounded-2xl border border-white/10 bg-gradient-to-br px-4 py-4 text-center min-w-0",
                    color
                  )}
                >
                  <Icon className="w-5 h-5 mx-auto mb-2 text-white/60" />
                  <p className="text-xl sm:text-2xl font-black tabular-nums break-all">{value.toLocaleString()}</p>
                  <p className="text-xs text-blue-200 mt-1">{label}</p>
                </div>
              ))}
            </div>
          )}

          {report?.dataSource === "fallback" && (
            <p className="mt-4 text-xs text-blue-300/70 flex items-center gap-1.5">
              <TrendingUp className="w-3.5 h-3.5" />
              Showing top-rated cars — live tracking data will populate as users browse the site.
            </p>
          )}
        </div>
      </div>

      {/* ── Content ───────────────────────────────────────────────────────── */}
      <div className="max-w-[1280px] mx-auto px-4 py-8">

        {loading && !report ? (
          <div className="flex justify-center items-center h-64">
            <div className="flex flex-col items-center gap-3 text-gray-400">
              <div className="w-10 h-10 border-2 border-gray-200 border-t-blue-500 rounded-full animate-spin" />
              <p className="text-sm">Generating report…</p>
            </div>
          </div>
        ) : !report ? (
          <div className="flex flex-col items-center gap-3 py-20 text-gray-400">
            <BarChart3 className="w-10 h-10" />
            <p className="text-sm">Could not load report. Please try again.</p>
            <button
              onClick={() => loadReport()}
              className="px-4 py-2 rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 transition-colors"
            >
              Retry
            </button>
          </div>
        ) : (
          <div className="rounded-[28px] bg-white border border-gray-200/60 shadow-sm overflow-hidden">

            {/* Tabs */}
            <div className="flex overflow-x-auto border-b border-gray-100 px-2 pt-2 gap-1 scrollbar-hide">
              {TABS.map(({ id, label, icon: Icon, color, count }) => {
                const cnt = count(report);
                return (
                  <button
                    key={id}
                    onClick={() => setTab(id)}
                    className={cn(
                      "flex items-center gap-2 px-4 py-3 rounded-t-xl text-sm font-semibold whitespace-nowrap transition-all duration-200 border-b-2",
                      tab === id
                        ? cn("border-current bg-gray-50", color)
                        : "border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50"
                    )}
                  >
                    <Icon className="w-4 h-4" />
                    {label}
                    <span className={cn(
                      "px-1.5 py-0.5 rounded-full text-[10px] font-bold",
                      tab === id ? "bg-current/10 text-current" : "bg-gray-100 text-gray-500"
                    )}>
                      {cnt}
                    </span>
                  </button>
                );
              })}
            </div>

            {/* Tab content */}
            <div className="p-4 md:p-6">
              <AnimatePresence mode="wait">
                <motion.div
                  key={tab}
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  transition={{ duration: 0.18 }}
                >
                  {tab === "popular" && (
                    <PopularCarsSection cars={report.popularCars} />
                  )}
                  {tab === "brands" && (
                    <PopularBrandsSection brands={report.popularBrands} />
                  )}
                  {tab === "evs" && (
                    <FastestEvSection evs={report.fastestGrowingEvs} />
                  )}
                  {tab === "viewed" && (
                    <ViewedComparedSection
                      cars={report.mostViewedCars}
                      metricKey="viewCount"
                      metricLabel="views"
                      metricColor="bg-amber-500"
                    />
                  )}
                  {tab === "compared" && (
                    <ViewedComparedSection
                      cars={report.mostComparedCars}
                      metricKey="compareCount"
                      metricLabel="compares"
                      metricColor="bg-rose-500"
                    />
                  )}
                </motion.div>
              </AnimatePresence>
            </div>

            {/* Footer */}
            <div className="px-4 sm:px-6 py-4 border-t border-gray-100 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between text-xs text-gray-400">
              <span className="min-w-0">
                Generated {new Date(report.generatedAt).toLocaleString("en-IN", {
                  day: "numeric", month: "short", year: "numeric",
                  hour: "2-digit", minute: "2-digit",
                })}
              </span>
              <Link href="/cars" className="text-blue-500 font-semibold hover:underline shrink-0">
                Browse all cars →
              </Link>
            </div>
          </div>
        )}
      </div>
    </main>
  );
}
