"use client";

import { useEffect, useState } from "react";
import {
  BarChart2, Users, TrendingUp, RefreshCw, MapPin, Fuel, Wallet,
  Car as CarIcon,
} from "lucide-react";
import { fetchLeadReport, generateLeadReport } from "@/lib/api";
import type { LeadReport } from "@/lib/api";

function BarList({ items, labelKey, countKey }: {
  items: Record<string, unknown>[];
  labelKey: string;
  countKey: string;
}) {
  if (!items?.length) return <p className="text-sm text-gray-400">No data</p>;
  const max = Math.max(...items.map((i) => Number(i[countKey]) || 0));
  return (
    <div className="space-y-2 min-w-0">
      {items.map((item, i) => {
        const label = String(item[labelKey] ?? "");
        const count = Number(item[countKey] ?? 0);
        const pct = max > 0 ? (count / max) * 100 : 0;
        return (
          <div key={i} className="flex items-center gap-2 sm:gap-3 min-w-0">
            <span className="text-sm text-gray-700 w-20 sm:w-32 truncate shrink-0">{label}</span>
            <div className="flex-1 min-w-0 h-2 bg-gray-100 rounded-full overflow-hidden">
              <div
                className="h-full bg-blue-500 rounded-full transition-all duration-700"
                style={{ width: `${pct}%` }}
              />
            </div>
            <span className="text-sm font-bold text-gray-700 w-8 text-right shrink-0 tabular-nums">{count}</span>
          </div>
        );
      })}
    </div>
  );
}

export default function LeadIntelligencePage() {
  const [report, setReport] = useState<LeadReport | null>(null);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);

  async function load() {
    setLoading(true);
    try {
      const data = await fetchLeadReport();
      setReport(data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }

  async function generate() {
    setGenerating(true);
    try {
      const result = await generateLeadReport();
      if (result) {
        setReport(result);
      } else {
        await load();
      }
    } catch (e) {
      console.error(e);
    } finally {
      setGenerating(false);
    }
  }

  useEffect(() => { load(); }, []);

  const weekLabel = report?.weekStart
    ? new Date(report.weekStart).toLocaleDateString("en-IN", { day: "2-digit", month: "short", year: "numeric" })
    : "—";

  return (
    <div className="p-4 sm:p-6 max-w-5xl mx-auto min-w-0 overflow-x-hidden pb-[calc(1.5rem+env(safe-area-inset-bottom,0px))]">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-6 min-w-0">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-black text-gray-900 flex items-center gap-2 min-w-0">
            <BarChart2 className="w-6 h-6 text-blue-600 shrink-0" />
            <span className="truncate">Lead Intelligence</span>
          </h1>
          <p className="text-gray-500 text-sm mt-1 break-words">
            Weekly lead analysis — popular cars, cities, conversion trends
          </p>
        </div>
        <div className="flex items-center gap-2 sm:gap-3 flex-wrap shrink-0">
          <button
            onClick={load}
            disabled={loading}
            className="flex items-center justify-center gap-1.5 min-h-10 px-4 py-2 rounded-xl border border-gray-200 text-sm font-semibold hover:bg-gray-50 transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </button>
          <button
            onClick={generate}
            disabled={generating}
            className="flex items-center justify-center gap-1.5 min-h-10 px-4 py-2 rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${generating ? "animate-spin" : ""}`} />
            Generate Report
          </button>
        </div>
      </div>

      {loading ? (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="h-24 rounded-2xl bg-gray-100 animate-pulse" />
          ))}
        </div>
      ) : !report ? (
        <div className="text-center py-24">
          <BarChart2 className="w-14 h-14 mx-auto text-gray-300 mb-4" />
          <h2 className="text-xl font-bold text-gray-700 mb-2">No Report Yet</h2>
          <p className="text-gray-500 text-sm mb-6">Reports are generated every Monday at 00:00 UTC.</p>
          <button
            onClick={generate}
            disabled={generating}
            className="px-6 py-3 bg-blue-600 text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors disabled:opacity-50"
          >
            {generating ? "Generating…" : "Generate First Report"}
          </button>
        </div>
      ) : (
        <>
          {/* Header */}
          <div className="mb-6 text-sm text-gray-500 break-words">
            Week of <span className="font-semibold text-gray-700">{weekLabel}</span>
            {" · "}Generated {new Date(report.generatedAt).toLocaleString("en-IN")}
          </div>

          {/* KPI cards */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-8 min-w-0">
            {[
              { icon: Users, label: "Total Leads", value: report.totalLeads, color: "bg-blue-50 border-blue-200 text-blue-700" },
              { icon: TrendingUp, label: "Converted", value: report.convertedLeads, color: "bg-green-50 border-green-200 text-green-700" },
              { icon: BarChart2, label: "Conversion %", value: `${report.conversionRate}%`, color: "bg-amber-50 border-amber-200 text-amber-700" },
              { icon: CarIcon, label: "Top Cars", value: report.topCars.length, color: "bg-purple-50 border-purple-200 text-purple-700" },
            ].map(({ icon: Icon, label, value, color }) => (
              <div key={label} className={`rounded-2xl border p-3 sm:p-5 min-w-0 ${color}`}>
                <Icon className="w-5 h-5 mb-2 opacity-70" />
                <p className="text-2xl sm:text-3xl font-black truncate">{value}</p>
                <p className="text-xs font-semibold opacity-70 mt-0.5 truncate">{label}</p>
              </div>
            ))}
          </div>

          {/* Charts grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 min-w-0">
            {/* Top Cars */}
            <div className="bg-white rounded-2xl border border-gray-100 p-4 sm:p-6 shadow-sm min-w-0">
              <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2 min-w-0">
                <CarIcon className="w-4 h-4 text-blue-500 shrink-0" />
                <span className="truncate">Most Enquired Cars</span>
              </h2>
              <BarList items={report.topCars} labelKey="name" countKey="count" />
            </div>

            {/* Top Brands */}
            <div className="bg-white rounded-2xl border border-gray-100 p-4 sm:p-6 shadow-sm min-w-0">
              <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2 min-w-0">
                <TrendingUp className="w-4 h-4 text-green-500 shrink-0" />
                <span className="truncate">Top Brands</span>
              </h2>
              <BarList items={report.topBrands} labelKey="name" countKey="count" />
            </div>

            {/* Top Cities */}
            <div className="bg-white rounded-2xl border border-gray-100 p-4 sm:p-6 shadow-sm min-w-0">
              <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2 min-w-0">
                <MapPin className="w-4 h-4 text-red-500 shrink-0" />
                <span className="truncate">Top Cities</span>
              </h2>
              <BarList items={report.topCities} labelKey="name" countKey="count" />
            </div>

            {/* Budget Ranges */}
            <div className="bg-white rounded-2xl border border-gray-100 p-4 sm:p-6 shadow-sm min-w-0">
              <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2 min-w-0">
                <Wallet className="w-4 h-4 text-purple-500 shrink-0" />
                <span className="truncate">Budget Distribution</span>
              </h2>
              <BarList items={report.topBudgetRanges} labelKey="range" countKey="count" />
            </div>

            {/* Fuel Types */}
            <div className="bg-white rounded-2xl border border-gray-100 p-4 sm:p-6 shadow-sm min-w-0">
              <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2 min-w-0">
                <Fuel className="w-4 h-4 text-amber-500 shrink-0" />
                <span className="truncate">Fuel Type Preferences</span>
              </h2>
              <BarList items={report.topFuelTypes} labelKey="type" countKey="count" />
            </div>
          </div>

          <p className="text-xs text-gray-400 mt-6 text-center">
            Reports auto-generated every Monday. Next report covers leads from the current week.
          </p>
        </>
      )}
    </div>
  );
}
