"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Fuel, Shield, Wrench, Settings2, TrendingDown,
  ChevronDown, ChevronUp, Info, Calculator, SlidersHorizontal,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { fetchOwnershipCost } from "@/lib/api";
import type { OwnershipCostResult, OwnershipYear } from "@/lib/types";

// ── Category config ────────────────────────────────────────────────────────────

const CATS = [
  { key: "fuelCost",     label: "Fuel Cost",    color: "#3b82f6", bg: "bg-blue-50",    text: "text-blue-600",   icon: Fuel       },
  { key: "insurance",    label: "Insurance",    color: "#8b5cf6", bg: "bg-violet-50",  text: "text-violet-600", icon: Shield     },
  { key: "serviceCost",  label: "Service",      color: "#10b981", bg: "bg-emerald-50", text: "text-emerald-600",icon: Wrench     },
  { key: "maintenance",  label: "Maintenance",  color: "#f59e0b", bg: "bg-amber-50",   text: "text-amber-600",  icon: Settings2  },
  { key: "depreciation", label: "Depreciation", color: "#ef4444", bg: "bg-red-50",     text: "text-red-500",    icon: TrendingDown},
] as const;

type CatKey = typeof CATS[number]["key"];

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

function fmtINR(n: number): string {
  if (!n && n !== 0) 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`;
  if (n >= 1_000)      return `₹${(n / 1_000).toFixed(0)}k`;
  return `₹${n.toLocaleString("en-IN")}`;
}

function fmtKm(n: number) {
  return n >= 1000 ? `${(n / 1000).toFixed(0)}k km` : `${n} km`;
}

// ── SVG Donut chart ────────────────────────────────────────────────────────────

function DonutChart({ by }: { by: Record<string, number> }) {
  const total = Object.values(by).reduce((a, b) => a + b, 0);
  if (!total) return null;

  const R   = 52;
  const CX  = 80;
  const CY  = 80;
  const C   = 2 * Math.PI * R;
  let offset = 0;

  const slices = CATS.map(({ key, color }) => {
    const val  = by[key] ?? 0;
    const frac = val / total;
    const dash = frac * C;
    const gap  = C - dash;
    const rot  = (offset / total) * 360 - 90;
    offset += val;
    return { key, color, dash, gap, rot };
  });

  return (
    <svg viewBox="0 0 160 160" className="w-40 h-40 shrink-0">
      {slices.map(({ key, color, dash, gap, rot }) => (
        <circle
          key={key}
          cx={CX} cy={CY} r={R}
          fill="none"
          stroke={color}
          strokeWidth="28"
          strokeDasharray={`${dash.toFixed(2)} ${gap.toFixed(2)}`}
          style={{
            transform:       `rotate(${rot}deg)`,
            transformOrigin: `${CX}px ${CY}px`,
          }}
        />
      ))}
      {/* inner white circle for donut hole */}
      <circle cx={CX} cy={CY} r="37" fill="white" />
      <text x={CX} y="76"  textAnchor="middle" fontSize="9"  fill="#9ca3af" fontWeight="500">5-Yr Total</text>
      <text x={CX} y="90"  textAnchor="middle" fontSize="11" fill="#111827" fontWeight="700">
        {fmtINR(total)}
      </text>
    </svg>
  );
}

// ── Stacked bar (one per year) ─────────────────────────────────────────────────

function YearBar({
  year,
  maxTotal,
  highlight,
}: {
  year:     OwnershipYear;
  maxTotal: number;
  highlight: boolean;
}) {
  const BAR_H = 130;

  return (
    <div className="flex flex-col items-center gap-1.5">
      <div
        className={cn(
          "relative w-9 flex flex-col-reverse rounded-lg overflow-hidden transition-all duration-300",
          highlight ? "ring-2 ring-blue-400 ring-offset-1" : "",
        )}
        style={{ height: BAR_H, backgroundColor: "#f3f4f6" }}
        title={`Year ${year.year}: ${fmtINR(year.total)}`}
      >
        {CATS.map(({ key, color }) => {
          const val  = year[key as CatKey] as number;
          const pct  = maxTotal > 0 ? (val / maxTotal) * 100 : 0;
          return (
            <div
              key={key}
              style={{ backgroundColor: color, height: `${pct}%` }}
              className="transition-all duration-500"
            />
          );
        })}
      </div>
      <span className={cn(
        "text-[11px] font-bold",
        highlight ? "text-blue-600" : "text-gray-400"
      )}>
        Y{year.year}
      </span>
    </div>
  );
}

// ── Main section ───────────────────────────────────────────────────────────────

interface Props {
  carId:    string;
  fuelType: string;
}

export default function OwnershipCostSection({ carId, fuelType }: Props) {
  const [data,       setData]       = useState<OwnershipCostResult | null>(null);
  const [loading,    setLoading]    = useState(true);
  const [kmPerYear,  setKmPerYear]  = useState(15_000);
  const [expandedYr, setExpandedYr] = useState<number | null>(null);
  const [hoverYr,    setHoverYr]    = useState<number | null>(null);

  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const load = useCallback((km: number) => {
    setLoading(true);
    fetchOwnershipCost(carId, { kmPerYear: km })
      .then((d) => { if (d) setData(d); })
      .finally(() => setLoading(false));
  }, [carId]);

  // Initial fetch
  useEffect(() => { load(kmPerYear); }, []); // eslint-disable-line

  function onKmChange(km: number) {
    setKmPerYear(km);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => load(km), 500);
  }

  const maxTotal = data ? Math.max(...data.years.map((y) => y.total)) : 0;
  const { summary, years } = data ?? { summary: null, years: [] as OwnershipYear[] };

  return (
    <section className="rounded-3xl border border-gray-200/80 bg-white shadow-sm overflow-hidden">

      {/* ── Header ─────────────────────────────────────────────────────────── */}
      <div className="flex items-center justify-between px-6 pt-6 pb-4 border-b border-gray-100">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-xl bg-blue-50">
            <Calculator className="w-5 h-5 text-blue-600" />
          </div>
          <div>
            <h2 className="text-lg font-bold text-gray-900">5-Year Ownership Cost</h2>
            <p className="text-xs text-gray-500 mt-0.5">
              Fuel · Insurance · Service · Maintenance · Depreciation
            </p>
          </div>
        </div>
        {loading && (
          <div className="w-5 h-5 border-2 border-blue-100 border-t-blue-500 rounded-full animate-spin" />
        )}
      </div>

      {/* ── Body ───────────────────────────────────────────────────────────── */}
      {!data && loading ? (
        <div className="flex justify-center items-center h-52">
          <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">Calculating ownership costs…</p>
          </div>
        </div>
      ) : !data ? (
        <div className="flex justify-center items-center h-32 text-gray-400 text-sm">
          Could not load ownership cost data.
        </div>
      ) : (
        <div className="p-6 space-y-7">

          {/* ── Summary hero ──────────────────────────────────────────────── */}
          <div className="grid grid-cols-3 gap-3">
            {[
              { label: "5-Year Total",  value: fmtINR(summary!.total5yr),   sub: "all-in ownership"          },
              { label: "Per Year",      value: fmtINR(summary!.avgAnnual),  sub: "average annual spend"      },
              { label: "Per Km",        value: `₹${summary!.costPerKm}`,    sub: `at ${fmtKm(kmPerYear)}/yr` },
            ].map(({ label, value, sub }) => (
              <div
                key={label}
                className="rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 px-4 py-3.5 text-center"
              >
                <p className="text-[11px] text-blue-500 font-semibold mb-1">{label}</p>
                <p className="text-xl font-black text-blue-900 leading-none">{value}</p>
                <p className="text-[10px] text-blue-400 mt-1">{sub}</p>
              </div>
            ))}
          </div>

          {/* ── Km slider ─────────────────────────────────────────────────── */}
          <div className="rounded-2xl bg-gray-50 border border-gray-200 px-5 py-4">
            <div className="flex items-center gap-2 mb-3">
              <SlidersHorizontal className="w-4 h-4 text-gray-400" />
              <span className="text-sm font-semibold text-gray-700 flex-1">
                Annual kilometres driven
              </span>
              <span className="text-sm font-bold text-blue-600 tabular-nums">
                {(kmPerYear / 1000).toFixed(0)},000 km / yr
              </span>
            </div>
            <input
              type="range" min={5000} max={50000} step={1000}
              value={kmPerYear}
              onChange={(e) => onKmChange(Number(e.target.value))}
              className="w-full accent-blue-600 cursor-pointer"
            />
            <div className="flex justify-between text-[10px] text-gray-400 mt-1.5 font-medium">
              <span>5,000</span>
              <span>Low ←</span>
              <span className="text-gray-500">15k avg</span>
              <span>→ High</span>
              <span>50,000</span>
            </div>
          </div>

          {/* ── Donut + category legend ────────────────────────────────────── */}
          <div className="flex flex-col sm:flex-row items-center gap-6">
            <DonutChart by={summary!.byCategory} />

            <div className="flex-1 w-full space-y-2">
              {CATS.map(({ key, label, color, bg, text, icon: Icon }) => {
                const val = summary!.byCategory[key] ?? 0;
                const pct = summary!.total5yr > 0
                  ? (val / summary!.total5yr) * 100
                  : 0;
                return (
                  <div key={key} className="flex items-center gap-2.5">
                    <div
                      className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                      style={{ backgroundColor: color }}
                    />
                    <Icon className={cn("w-3.5 h-3.5 shrink-0", text)} />
                    <span className="text-sm text-gray-600 flex-1 truncate">{label}</span>
                    <span className="text-sm font-bold text-gray-800 tabular-nums w-20 text-right">
                      {fmtINR(val)}
                    </span>
                    <span className="text-xs text-gray-400 w-8 text-right tabular-nums">
                      {pct.toFixed(0)}%
                    </span>
                    {/* mini bar */}
                    <div className="w-16 h-1.5 rounded-full bg-gray-100 overflow-hidden hidden sm:block">
                      <div
                        className="h-full rounded-full transition-all duration-500"
                        style={{ backgroundColor: color, width: `${pct}%` }}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Stacked bar chart (year-by-year) ──────────────────────────── */}
          <div className="rounded-2xl bg-gray-50 border border-gray-200 p-5">
            <p className="text-xs font-semibold text-gray-500 mb-4">
              Year-by-Year Breakdown
            </p>
            <div
              className="flex justify-around items-end"
              onMouseLeave={() => setHoverYr(null)}
            >
              {years.map((yr) => (
                <div
                  key={yr.year}
                  onMouseEnter={() => setHoverYr(yr.year)}
                  className="flex flex-col items-center gap-1"
                >
                  <AnimatePresence>
                    {hoverYr === yr.year && (
                      <motion.div
                        initial={{ opacity: 0, y: 4 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: 4 }}
                        className="absolute mt-[-40px] text-[10px] bg-gray-900 text-white rounded-lg px-2 py-1 whitespace-nowrap z-10"
                        style={{ transform: "translateY(-100%)" }}
                      >
                        {fmtINR(yr.total)}
                      </motion.div>
                    )}
                  </AnimatePresence>
                  <YearBar year={yr} maxTotal={maxTotal} highlight={hoverYr === yr.year} />
                </div>
              ))}
            </div>
            {/* Legend */}
            <div className="flex flex-wrap gap-x-4 gap-y-1.5 mt-4 justify-center">
              {CATS.map(({ label, color }) => (
                <div key={label} className="flex items-center gap-1.5">
                  <div className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: color }} />
                  <span className="text-[10px] text-gray-500 font-medium">{label}</span>
                </div>
              ))}
            </div>
          </div>

          {/* ── Detailed year table ────────────────────────────────────────── */}
          <div className="rounded-2xl border border-gray-200 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm min-w-[560px]">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-200">
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 w-20">Year</th>
                    {CATS.map(({ label, text }) => (
                      <th key={label} className={cn("text-right px-3 py-3 text-xs font-semibold", text)}>
                        {label}
                      </th>
                    ))}
                    <th className="text-right px-4 py-3 text-xs font-bold text-gray-700">Total</th>
                    <th className="w-8 px-2 py-3" />
                  </tr>
                </thead>
                <tbody>
                  {years.map((yr) => (
                    <>
                      <tr
                        key={yr.year}
                        className="border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors"
                        onClick={() => setExpandedYr(expandedYr === yr.year ? null : yr.year)}
                      >
                        <td className="px-4 py-3 font-semibold text-gray-800">Year {yr.year}</td>
                        <td className="px-3 py-3 text-right tabular-nums text-blue-600">
                          {fmtINR(yr.fuelCost)}
                        </td>
                        <td className="px-3 py-3 text-right tabular-nums text-violet-600">
                          {fmtINR(yr.insurance)}
                        </td>
                        <td className="px-3 py-3 text-right tabular-nums text-emerald-600">
                          {fmtINR(yr.serviceCost)}
                        </td>
                        <td className="px-3 py-3 text-right tabular-nums text-amber-600">
                          {fmtINR(yr.maintenance)}
                        </td>
                        <td className="px-3 py-3 text-right tabular-nums text-red-500">
                          {fmtINR(yr.depreciation)}
                        </td>
                        <td className="px-4 py-3 text-right font-bold text-gray-900 tabular-nums">
                          {fmtINR(yr.total)}
                        </td>
                        <td className="px-2 py-3 text-gray-400">
                          {expandedYr === yr.year
                            ? <ChevronUp className="w-4 h-4" />
                            : <ChevronDown className="w-4 h-4" />}
                        </td>
                      </tr>

                      <AnimatePresence>
                        {expandedYr === yr.year && (
                          <motion.tr
                            key={`${yr.year}-detail`}
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                          >
                            <td colSpan={8} className="bg-violet-50/40 border-b border-violet-100 px-6 py-4">
                              <p className="text-xs font-semibold text-violet-700 mb-2">
                                Insurance breakdown — Year {yr.year}
                                {yr.insuranceDetail.ncbPct > 0 && (
                                  <span className="ml-2 px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700">
                                    {yr.insuranceDetail.ncbPct}% NCB saved
                                  </span>
                                )}
                              </p>
                              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5">
                                {[
                                  {
                                    label: "IDV (Car Value)",
                                    value: fmtINR(yr.insuranceDetail.idv),
                                    sub: "insured declared value",
                                    color: "border-violet-200",
                                  },
                                  {
                                    label: "OD Premium",
                                    value: fmtINR(yr.insuranceDetail.odGross),
                                    sub: "own damage (before NCB)",
                                    color: "border-violet-200",
                                  },
                                  {
                                    label: `NCB Discount (${yr.insuranceDetail.ncbPct}%)`,
                                    value: yr.insuranceDetail.ncbDiscount > 0
                                      ? `−${fmtINR(yr.insuranceDetail.ncbDiscount)}`
                                      : "—",
                                    sub: "no-claim bonus savings",
                                    color: "border-emerald-200",
                                    green: true,
                                  },
                                  {
                                    label: "Third Party (TP)",
                                    value: fmtINR(yr.insuranceDetail.tp),
                                    sub: "IRDAI mandated premium",
                                    color: "border-violet-200",
                                  },
                                ].map(({ label, value, sub, color, green }) => (
                                  <div
                                    key={label}
                                    className={cn(
                                      "rounded-xl bg-white border px-3 py-2.5",
                                      color
                                    )}
                                  >
                                    <p className="text-[10px] text-gray-400 mb-1">{label}</p>
                                    <p className={cn(
                                      "text-sm font-bold",
                                      green ? "text-emerald-600" : "text-gray-800"
                                    )}>
                                      {value}
                                    </p>
                                    <p className="text-[9px] text-gray-400 mt-0.5">{sub}</p>
                                  </div>
                                ))}
                              </div>
                              <p className="text-[10px] text-gray-400 mt-2">
                                Total Insurance = OD net ({fmtINR(yr.insuranceDetail.odNet)}) + TP ({fmtINR(yr.insuranceDetail.tp)}) = {fmtINR(yr.insurance)}
                              </p>
                            </td>
                          </motion.tr>
                        )}
                      </AnimatePresence>
                    </>
                  ))}

                  {/* Totals row */}
                  <tr className="bg-gray-50 font-bold border-t-2 border-gray-200">
                    <td className="px-4 py-3.5 text-gray-900 text-sm">5-Year Total</td>
                    <td className="px-3 py-3.5 text-right tabular-nums text-blue-700">
                      {fmtINR(summary!.byCategory.fuelCost)}
                    </td>
                    <td className="px-3 py-3.5 text-right tabular-nums text-violet-700">
                      {fmtINR(summary!.byCategory.insurance)}
                    </td>
                    <td className="px-3 py-3.5 text-right tabular-nums text-emerald-700">
                      {fmtINR(summary!.byCategory.serviceCost)}
                    </td>
                    <td className="px-3 py-3.5 text-right tabular-nums text-amber-700">
                      {fmtINR(summary!.byCategory.maintenance)}
                    </td>
                    <td className="px-3 py-3.5 text-right tabular-nums text-red-600">
                      {fmtINR(summary!.byCategory.depreciation)}
                    </td>
                    <td className="px-4 py-3.5 text-right text-gray-900">
                      {fmtINR(summary!.total5yr)}
                    </td>
                    <td />
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* ── Cumulative cost progress ───────────────────────────────────── */}
          <div className="rounded-2xl bg-gray-50 border border-gray-200 px-5 py-4">
            <p className="text-xs font-semibold text-gray-500 mb-3">Cumulative Spend</p>
            <div className="space-y-2">
              {years.map((yr) => {
                const pct = summary!.total5yr > 0
                  ? (yr.cumulative / summary!.total5yr) * 100
                  : 0;
                return (
                  <div key={yr.year} className="flex items-center gap-3">
                    <span className="text-xs font-semibold text-gray-500 w-12">Year {yr.year}</span>
                    <div className="flex-1 h-2.5 rounded-full bg-gray-200 overflow-hidden">
                      <motion.div
                        initial={{ width: 0 }}
                        animate={{ width: `${pct}%` }}
                        transition={{ duration: 0.7, delay: yr.year * 0.1 }}
                        className="h-full rounded-full bg-gradient-to-r from-blue-500 to-indigo-500"
                      />
                    </div>
                    <span className="text-xs font-bold text-gray-700 tabular-nums w-20 text-right">
                      {fmtINR(yr.cumulative)}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Disclaimer ─────────────────────────────────────────────────── */}
          <div className="flex items-start gap-2 rounded-xl bg-amber-50 border border-amber-100 px-4 py-3">
            <Info className="w-3.5 h-3.5 text-amber-500 shrink-0 mt-0.5" />
            <p className="text-[11px] text-amber-700 leading-relaxed">
              Estimates are based on Delhi on-road price, IRDAI 2024-25 insurance premiums,
              standard service intervals, and a 5% annual fuel price escalation.
              Actual costs vary by city, insurer, driving habits, and maintenance history.
            </p>
          </div>

        </div>
      )}
    </section>
  );
}
