"use client";

import { useState, useEffect, useCallback } from "react";
import { motion } from "framer-motion";
import {
  Swords,
  Loader2,
  Play,
  CheckCircle2,
  Car,
  TrendingUp,
  AlertCircle,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { fetchCars, runRivalsJob } from "@/lib/api";

// ── helpers ───────────────────────────────────────────────────────────────────

interface RivalsJobResult {
  processed: number;
  updated: number;
  errors: number;
  durationMs?: number;
}

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

export default function AdminRivalsPage() {
  const [jobResult, setJobResult] = useState<RivalsJobResult | null>(null);
  const [running, setRunning]     = useState(false);
  const [loading, setLoading]     = useState(false);
  const [stats, setStats]         = useState<{ total: number; withRivals: number } | null>(null);

  const loadStats = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchCars({ limit: 1 });
      setStats({ total: data.total ?? 0, withRivals: 0 });
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function handleRunJob() {
    setRunning(true);
    setJobResult(null);
    try {
      const start = Date.now();
      const data = await runRivalsJob();
      setJobResult({ ...data, durationMs: Date.now() - start });
      await loadStats();
    } catch {
      setJobResult({ processed: 0, updated: 0, errors: 1 });
    } finally {
      setRunning(false);
    }
  }

  return (
    <div className="px-4 sm:px-6 pt-[calc(1.5rem+env(safe-area-inset-top,0px))] pb-[calc(1.5rem+env(safe-area-inset-bottom,0px))] max-w-[1000px] mx-auto min-w-0 overflow-x-hidden">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center 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">
            <Swords className="w-6 h-6 text-blue-600 shrink-0" />
            <span className="min-w-0 break-words">Rival Engine</span>
          </h1>
          <p className="text-sm text-gray-500 mt-0.5 break-words">
            Automatically identify direct rivals, budget alternatives, and premium alternatives for every car
          </p>
        </div>
        <button
          onClick={handleRunJob}
          disabled={running}
          className="inline-flex items-center justify-center gap-2 min-h-11 w-full sm:w-auto shrink-0 px-5 py-2.5 rounded-2xl bg-gradient-to-r from-blue-600 to-cyan-500 text-white text-sm font-bold shadow-lg shadow-blue-200 hover:opacity-90 transition-all disabled:opacity-60"
        >
          {running ? <Loader2 className="w-4 h-4 animate-spin shrink-0" /> : <Play className="w-4 h-4 shrink-0" />}
          Run Rivals Job
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
        {[
          {
            label: "Total Cars",
            value: loading ? "…" : (stats?.total ?? 0).toLocaleString(),
            icon: Car, color: "text-blue-600",
          },
          {
            label: "Cars with Rivals",
            value: loading ? "…" : (stats?.withRivals ?? 0).toLocaleString(),
            icon: Swords, color: "text-violet-600",
          },
          {
            label: "Coverage",
            value: stats?.total ? `${Math.round((stats.withRivals / stats.total) * 100)}%` : "—",
            icon: TrendingUp, color: "text-green-600",
          },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm">
            <div className="flex items-center gap-2 mb-1">
              <Icon className={cn("w-4 h-4", color)} />
              <span className="text-xs font-bold text-gray-500 uppercase tracking-wide">{label}</span>
            </div>
            <p className="text-2xl font-black text-gray-900">{value}</p>
          </div>
        ))}
      </div>

      {/* Job result */}
      {jobResult && (
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          className={cn(
            "rounded-2xl border p-5 mb-6",
            jobResult.errors > 0
              ? "bg-amber-50 border-amber-100"
              : "bg-green-50 border-green-100"
          )}
        >
          <div className="flex items-center gap-2 mb-3">
            {jobResult.errors > 0
              ? <AlertCircle className="w-5 h-5 text-amber-600" />
              : <CheckCircle2 className="w-5 h-5 text-green-600" />
            }
            <span className={cn("font-bold text-sm", jobResult.errors > 0 ? "text-amber-700" : "text-green-700")}>
              Rivals job completed
            </span>
          </div>
          <div className="grid grid-cols-3 gap-4">
            {[
              { label: "Processed", value: jobResult.processed },
              { label: "Updated",   value: jobResult.updated },
              { label: "Errors",    value: jobResult.errors },
            ].map(({ label, value }) => (
              <div key={label} className="text-center">
                <p className="text-xl font-black text-gray-900">{value}</p>
                <p className="text-xs text-gray-500 font-medium mt-0.5">{label}</p>
              </div>
            ))}
          </div>
          {jobResult.durationMs && (
            <p className="text-xs text-gray-400 mt-3 text-center">
              Completed in {(jobResult.durationMs / 1000).toFixed(1)}s
            </p>
          )}
        </motion.div>
      )}

      {/* Info card */}
      <div className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
        <h2 className="text-sm font-black text-gray-900 mb-4">How the Rival Engine Works</h2>
        <div className="space-y-3">
          {[
            {
              step: "1",
              title: "Score Each Car",
              desc: "Scores every car across price range, body type, fuel type, and segment.",
            },
            {
              step: "2",
              title: "Find Direct Rivals",
              desc: "Cars within ±20% price, same body type, same segment (e.g., SUV vs SUV).",
            },
            {
              step: "3",
              title: "Find Budget Alternatives",
              desc: "Cars that are 20–40% cheaper but in the same category.",
            },
            {
              step: "4",
              title: "Find Premium Alternatives",
              desc: "Cars that are 20–40% more expensive with higher ratings.",
            },
            {
              step: "5",
              title: "Generate Comparison Links",
              desc: "Creates /compare?ids=X,Y links for each rival pair for quick comparisons.",
            },
          ].map(({ step, title, desc }) => (
            <div key={step} className="flex items-start gap-3">
              <div className="w-6 h-6 rounded-full bg-blue-100 text-blue-600 text-xs font-black flex items-center justify-center shrink-0 mt-0.5">
                {step}
              </div>
              <div>
                <p className="text-sm font-bold text-gray-800">{title}</p>
                <p className="text-xs text-gray-500 mt-0.5">{desc}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="mt-5 p-4 rounded-xl bg-blue-50 border border-blue-100">
          <p className="text-xs font-bold text-blue-700 mb-1">Scheduler</p>
          <p className="text-xs text-blue-600">
            The rivals job runs automatically every Sunday at 02:00 UTC to keep rival data fresh.
            Use &quot;Run Rivals Job&quot; to trigger an immediate update.
          </p>
        </div>
      </div>
    </div>
  );
}
