"use client";

import { useState, useEffect, useCallback } from "react";
import { motion } from "framer-motion";
import {
  DollarSign,
  TrendingUp,
  TrendingDown,
  RefreshCw,
  Loader2,
  ArrowUpRight,
  ArrowDownRight,
  Minus,
  Play,
} from "lucide-react";
import { fetchRecentPriceChanges, runPriceTracking } from "@/lib/api";
import type { PriceHistoryEntry } from "@/lib/types";
import { cn, formatPrice } from "@/lib/utils";

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

function fmt(iso: string | null | undefined) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString("en-IN", {
      day: "numeric", month: "short", year: "numeric",
      hour: "2-digit", minute: "2-digit",
    });
  } catch { return "—"; }
}

function PriceChangeBadge({ type, amount, pct }: { type: string; amount: number; pct: number }) {
  const isIncrease = type === "increase";
  const isDecrease = type === "decrease";
  return (
    <span className={cn(
      "inline-flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-lg whitespace-nowrap shrink-0",
      isIncrease ? "bg-red-50 text-red-600" :
      isDecrease ? "bg-green-50 text-green-600" :
      "bg-gray-100 text-gray-500",
    )}>
      {isIncrease ? <ArrowUpRight className="w-3 h-3 shrink-0" /> :
       isDecrease ? <ArrowDownRight className="w-3 h-3 shrink-0" /> :
       <Minus className="w-3 h-3 shrink-0" />}
      {isIncrease ? "+" : isDecrease ? "-" : ""}
      {formatPrice(Math.abs(amount))}
      <span className="opacity-70">({Math.abs(pct).toFixed(1)}%)</span>
    </span>
  );
}

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

export default function AdminPricesPage() {
  const [changes, setChanges]   = useState<PriceHistoryEntry[]>([]);
  const [total, setTotal]       = useState(0);
  const [loading, setLoading]   = useState(true);
  const [running, setRunning]   = useState(false);
  const [runMsg, setRunMsg]     = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetchRecentPriceChanges(50);
      setChanges(res.changes ?? []);
      setTotal(res.total ?? 0);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function handleRunTracking() {
    setRunning(true);
    setRunMsg(null);
    try {
      const data = await runPriceTracking();
      setRunMsg(`Tracked ${data?.tracked ?? 0} cars, ${data?.changes ?? 0} price changes found.`);
      await load();
    } catch {
      setRunMsg("Price tracking job failed.");
    } finally {
      setRunning(false);
    }
  }

  const increases = changes.filter(c => c.changeType === "increase").length;
  const decreases = changes.filter(c => c.changeType === "decrease").length;

  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-[1200px] 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">
            <DollarSign className="w-6 h-6 text-blue-600 shrink-0" />
            <span className="min-w-0 break-words">Price Tracking</span>
          </h1>
          <p className="text-sm text-gray-500 mt-0.5 break-words">
            {total.toLocaleString()} price changes tracked · runs daily
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2 sm:gap-3 min-w-0 shrink-0">
          <button
            onClick={load}
            disabled={loading}
            className="inline-flex items-center justify-center gap-2 min-h-11 px-4 py-2.5 rounded-2xl border border-gray-200 bg-white text-sm font-bold text-gray-700 hover:border-gray-300 transition-all disabled:opacity-50"
          >
            <RefreshCw className={cn("w-4 h-4 shrink-0", loading && "animate-spin")} />
            Refresh
          </button>
          <button
            onClick={handleRunTracking}
            disabled={running}
            className="inline-flex items-center justify-center gap-2 min-h-11 px-4 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 Now
          </button>
        </div>
      </div>

      {/* Run message */}
      {runMsg && (
        <div className="mb-4 px-4 py-3 rounded-2xl bg-blue-50 border border-blue-100 text-sm text-blue-700 font-medium break-words min-w-0">
          {runMsg}
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 sm:gap-4 mb-6 min-w-0">
        {[
          { label: "Total Changes", value: total, icon: DollarSign, color: "text-blue-600" },
          { label: "Price Increases", value: increases, icon: TrendingUp, color: "text-red-500" },
          { label: "Price Drops", value: decreases, icon: TrendingDown, color: "text-green-600" },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-white rounded-2xl border border-gray-100 p-3 sm:p-4 shadow-sm min-w-0">
            <div className="flex items-center gap-2 mb-1 min-w-0">
              <Icon className={cn("w-4 h-4 shrink-0", color)} />
              <span className="text-xs font-bold text-gray-500 uppercase tracking-wide truncate">{label}</span>
            </div>
            <p className="text-2xl font-black text-gray-900 truncate">{value}</p>
          </div>
        ))}
      </div>

      {/* Changes list */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden min-w-0">
        <div className="px-4 sm:px-5 py-3 border-b border-gray-100 bg-gray-50/50 min-w-0">
          <p className="text-xs font-bold text-gray-500 uppercase tracking-wide truncate">Recent Price Changes</p>
        </div>
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-6 h-6 animate-spin text-blue-500" />
          </div>
        ) : changes.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 px-4 text-center min-w-0">
            <DollarSign className="w-10 h-10 text-gray-200 mb-3" />
            <p className="text-sm font-semibold text-gray-400">No price changes tracked yet</p>
            <p className="text-xs text-gray-300 mt-1 break-words">Run the tracker to start monitoring prices</p>
          </div>
        ) : (
          <div className="overflow-x-auto min-w-0">
            <table className="w-full text-sm min-w-[640px]">
              <thead>
                <tr className="border-b border-gray-100">
                  <th className="text-left px-3 sm:px-5 py-3 text-xs font-bold text-gray-500 uppercase tracking-wide whitespace-nowrap">Car</th>
                  <th className="text-left px-3 sm:px-5 py-3 text-xs font-bold text-gray-500 uppercase tracking-wide whitespace-nowrap">New Price</th>
                  <th className="text-left px-3 sm:px-5 py-3 text-xs font-bold text-gray-500 uppercase tracking-wide whitespace-nowrap">Change</th>
                  <th className="text-left px-3 sm:px-5 py-3 text-xs font-bold text-gray-500 uppercase tracking-wide whitespace-nowrap">Date</th>
                  <th className="text-left px-3 sm:px-5 py-3 text-xs font-bold text-gray-500 uppercase tracking-wide whitespace-nowrap">Source</th>
                </tr>
              </thead>
              <tbody>
                {changes.map((c, i) => (
                  <tr key={i} className="border-b border-gray-50 hover:bg-gray-50/50 transition-colors">
                    <td className="px-3 sm:px-5 py-3 font-semibold text-gray-800 max-w-[10rem] truncate" title={c.carId}>{c.carId}</td>
                    <td className="px-3 sm:px-5 py-3 text-gray-700 whitespace-nowrap">{formatPrice(c.priceMin ?? c.price)}</td>
                    <td className="px-3 sm:px-5 py-3 whitespace-nowrap">
                      <PriceChangeBadge type={c.changeType} amount={c.changeAmount} pct={c.changePct} />
                    </td>
                    <td className="px-3 sm:px-5 py-3 text-gray-500 text-xs whitespace-nowrap">{fmt(c.recordedAt)}</td>
                    <td className="px-3 sm:px-5 py-3 text-gray-400 text-xs max-w-[8rem] truncate" title={c.source ?? undefined}>{c.source ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
