"use client";

import { useState, useEffect, useCallback, useDeferredValue, useRef } from "react";
import {
  Loader2,
  RefreshCw,
  Plus,
  Trash2,
  RotateCcw,
  Moon,
  CheckCircle2,
  XCircle,
  Clock,
  MapPin,
  Search,
  AlertTriangle,
  WifiOff,
  Activity,
  Play,
  Download,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Badge } from "@/shared/components/ui/badge";
import { Card, CardContent } from "@/shared/components/ui/card";
import { cn } from "@/shared/lib/utils";

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

type StepName = "sync_terenuri" | "sync_cladiri" | "import_nogeom" | "enrich";
type StepStatus = "pending" | "done" | "error";

type CityState = {
  siruta: string;
  name: string;
  county: string;
  priority: number;
  steps: Record<StepName, StepStatus>;
  lastActivity?: string;
  errorMessage?: string;
  dbStats?: {
    terenuri: number;
    cladiri: number;
    total: number;
    enriched: number;
  };
};

type QueueState = {
  cities: CityState[];
  lastSessionDate?: string;
  totalSessions: number;
  completedCycles: number;
};

type SyncStatus = "running" | "error" | "waiting" | "idle";

type CurrentActivity = {
  city: string;
  step: string;
  startedAt: string;
} | null;

const STEPS: StepName[] = [
  "sync_terenuri",
  "sync_cladiri",
  "import_nogeom",
  "enrich",
];

const STEP_LABELS: Record<StepName, string> = {
  sync_terenuri: "Terenuri",
  sync_cladiri: "Cladiri",
  import_nogeom: "No-geom",
  enrich: "Enrichment",
};

/** Auto-poll intervals */
const POLL_ACTIVE_MS = 15_000; // 15s when running
const POLL_IDLE_MS = 60_000;   // 60s when idle

/* ------------------------------------------------------------------ */
/*  Page                                                               */
/* ------------------------------------------------------------------ */

export default function WeekendDeepSyncPage() {
  const [state, setState] = useState<QueueState | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);

  // Live status
  const [syncStatus, setSyncStatus] = useState<SyncStatus>("idle");
  const [currentActivity, setCurrentActivity] = useState<CurrentActivity>(null);
  const [inWeekendWindow, setInWeekendWindow] = useState(false);
  const [fetchError, setFetchError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);

  // UAT autocomplete for adding cities
  type UatEntry = { siruta: string; name: string; county?: string };
  const [uatData, setUatData] = useState<UatEntry[]>([]);
  const [uatQuery, setUatQuery] = useState("");
  const [uatResults, setUatResults] = useState<UatEntry[]>([]);
  const [showUatResults, setShowUatResults] = useState(false);
  const uatRef = useRef<HTMLDivElement>(null);

  const fetchState = useCallback(async () => {
    try {
      const res = await fetch("/api/eterra/weekend-sync");
      if (!res.ok) {
        setFetchError(`Server: ${res.status} ${res.statusText}`);
        setLoading(false);
        return;
      }
      const data = (await res.json()) as {
        state: QueueState | null;
        syncStatus?: SyncStatus;
        currentActivity?: CurrentActivity;
        inWeekendWindow?: boolean;
      };
      setState(data.state);
      setSyncStatus(data.syncStatus ?? "idle");
      setCurrentActivity(data.currentActivity ?? null);
      setInWeekendWindow(data.inWeekendWindow ?? false);
      setFetchError(null);
      setLastRefresh(new Date());
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Conexiune esuata";
      setFetchError(msg);
    }
    setLoading(false);
  }, []);

  // Initial load + UAT list
  useEffect(() => {
    void fetchState();
    fetch("/api/eterra/uats")
      .then((r) => r.json())
      .then((data: { uats?: UatEntry[] }) => {
        if (data.uats) setUatData(data.uats);
      })
      .catch(() => {
        fetch("/uat.json")
          .then((r) => r.json())
          .then((fallback: UatEntry[]) => setUatData(fallback))
          .catch(() => {});
      });
  }, [fetchState]);

  // Auto-poll: 15s when running, 60s otherwise
  useEffect(() => {
    const interval = syncStatus === "running" ? POLL_ACTIVE_MS : POLL_IDLE_MS;
    const timer = setInterval(() => void fetchState(), interval);
    return () => clearInterval(timer);
  }, [fetchState, syncStatus]);

  // UAT autocomplete filter
  const normalizeText = (text: string) =>
    text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();

  const deferredUatQuery = useDeferredValue(uatQuery);
  useEffect(() => {
    const raw = deferredUatQuery.trim();
    if (raw.length < 2) { setUatResults([]); return; }
    const isDigit = /^\d+$/.test(raw);
    const query = normalizeText(raw);
    const nameMatches: UatEntry[] = [];
    const countyOnly: UatEntry[] = [];
    for (const item of uatData) {
      // Skip cities already in queue
      if (state?.cities.some((c) => c.siruta === item.siruta)) continue;
      if (isDigit) {
        if (item.siruta.startsWith(raw)) nameMatches.push(item);
      } else {
        if (normalizeText(item.name).includes(query)) nameMatches.push(item);
        else if (item.county && normalizeText(item.county).includes(query))
          countyOnly.push(item);
      }
    }
    setUatResults([...nameMatches, ...countyOnly].slice(0, 10));
  }, [deferredUatQuery, uatData, state?.cities]);

  const doAction = async (body: Record<string, unknown>) => {
    setActionLoading(true);
    try {
      const res = await fetch("/api/eterra/weekend-sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const data = (await res.json().catch(() => ({}))) as { error?: string };
        setFetchError(data.error ?? `Eroare: ${res.status}`);
      } else {
        setFetchError(null);
      }
      await fetchState();
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Actiune esuata";
      setFetchError(msg);
    }
    setActionLoading(false);
  };

  const handleAddUat = async (uat: UatEntry) => {
    await doAction({
      action: "add",
      siruta: uat.siruta,
      name: uat.name,
      county: uat.county ?? "",
      priority: 3,
    });
    setUatQuery("");
    setUatResults([]);
    setShowUatResults(false);
  };

  if (loading) {
    return (
      <div className="mx-auto max-w-4xl py-12 text-center text-muted-foreground">
        <Loader2 className="h-8 w-8 mx-auto mb-3 animate-spin opacity-40" />
        <p>Se incarca...</p>
      </div>
    );
  }

  const cities = state?.cities ?? [];
  const totalSteps = cities.length * STEPS.length;
  const doneSteps = cities.reduce(
    (sum, c) => sum + STEPS.filter((s) => c.steps[s] === "done").length,
    0,
  );
  const progressPct = totalSteps > 0 ? Math.round((doneSteps / totalSteps) * 100) : 0;

  return (
    <div className="mx-auto max-w-4xl space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
            <Moon className="h-6 w-6 text-indigo-500" />
            Weekend Deep Sync
          </h1>
          <p className="text-muted-foreground text-sm">
            Sincronizare Magic completa pentru municipii mari — Vin/Sam/Dum
            23:00-04:00
          </p>
        </div>
        <div className="flex items-center gap-2">
          {lastRefresh && (
            <span className="text-[10px] text-muted-foreground">
              {lastRefresh.toLocaleTimeString("ro-RO", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
            </span>
          )}
          {syncStatus !== "running" && (
            <>
              <Button
                variant="outline"
                size="sm"
                disabled={actionLoading}
                onClick={() => {
                  if (window.confirm("Descarca terenuri + cladiri pentru orasele pending?"))
                    void doAction({ action: "trigger", onlySteps: ["sync_terenuri", "sync_cladiri"] });
                }}
              >
                <Download className="h-4 w-4 mr-1" />
                Descarca parcele
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="text-indigo-600 border-indigo-300 hover:bg-indigo-50 dark:text-indigo-400 dark:border-indigo-700 dark:hover:bg-indigo-950/30"
                disabled={actionLoading}
                onClick={() => {
                  if (window.confirm("Pornesti sincronizarea completa? Va procesa toti pasii pending."))
                    void doAction({ action: "trigger" });
                }}
              >
                <Play className="h-4 w-4 mr-1" />
                Sync complet
              </Button>
            </>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={() => void fetchState()}
            disabled={loading}
          >
            <RefreshCw className={cn("h-4 w-4 mr-1", loading && "animate-spin")} />
            Reincarca
          </Button>
        </div>
      </div>

      {/* Connection error banner */}
      {fetchError && (
        <div className="flex items-center gap-2 rounded-md border border-rose-200 bg-rose-50 px-4 py-2.5 text-sm text-rose-700 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-400">
          <WifiOff className="h-4 w-4 shrink-0" />
          <span>{fetchError}</span>
        </div>
      )}

      {/* Live status banner */}
      {syncStatus === "running" && (
        <div className="flex items-center gap-2 rounded-md border border-indigo-200 bg-indigo-50 px-4 py-2.5 text-sm text-indigo-700 dark:border-indigo-800 dark:bg-indigo-950/30 dark:text-indigo-400">
          <Activity className="h-4 w-4 shrink-0 animate-pulse" />
          <span className="font-medium">Sincronizarea ruleaza</span>
          {currentActivity && (
            <span>
              — {currentActivity.city} / {STEP_LABELS[currentActivity.step as StepName] ?? currentActivity.step}
            </span>
          )}
          <Loader2 className="h-3.5 w-3.5 ml-auto animate-spin opacity-50" />
        </div>
      )}
      {syncStatus === "error" && (
        <div className="flex items-center gap-2 rounded-md border border-rose-200 bg-rose-50 px-4 py-2.5 text-sm text-rose-700 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-400">
          <AlertTriangle className="h-4 w-4 shrink-0" />
          <span className="font-medium">Erori in ultimul ciclu</span>
          <span>
            — {cities.filter((c) => STEPS.some((s) => c.steps[s] === "error")).map((c) => c.name).join(", ")}
          </span>
        </div>
      )}
      {syncStatus === "waiting" && !fetchError && (
        <div className="flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-4 py-2.5 text-sm text-amber-700 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-400">
          <Clock className="h-4 w-4 shrink-0" />
          <span>Fereastra weekend activa — se asteapta urmatorul slot de procesare</span>
        </div>
      )}

      {/* Stats bar */}
      <Card>
        <CardContent className="py-3 px-4">
          <div className="flex items-center gap-4 flex-wrap text-sm">
            <span>
              <span className="font-semibold">{cities.length}</span> orase in
              coada
            </span>
            <span>
              Progres ciclu:{" "}
              <span className="font-semibold">{doneSteps}/{totalSteps}</span>{" "}
              pasi ({progressPct}%)
            </span>
            {state?.totalSessions != null && state.totalSessions > 0 && (
              <span className="text-muted-foreground">
                {state.totalSessions} sesiuni | {state.completedCycles ?? 0}{" "}
                cicluri complete
              </span>
            )}
            {state?.lastSessionDate && (
              <span className="text-muted-foreground">
                Ultima sesiune: {state.lastSessionDate}
              </span>
            )}
          </div>
          {totalSteps > 0 && (
            <div className="h-2 w-full rounded-full bg-muted mt-2">
              <div
                className="h-2 rounded-full bg-indigo-500 transition-all duration-300"
                style={{ width: `${Math.max(1, progressPct)}%` }}
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* City cards */}
      <div className="space-y-3">
        {cities
          .sort((a, b) => a.priority - b.priority)
          .map((city) => {
            const doneCount = STEPS.filter(
              (s) => city.steps[s] === "done",
            ).length;
            const hasError = STEPS.some((s) => city.steps[s] === "error");
            const allDone = doneCount === STEPS.length;
            const isActive = currentActivity?.city === city.name;

            return (
              <Card
                key={city.siruta}
                className={cn(
                  "transition-colors",
                  isActive && "border-indigo-300 ring-1 ring-indigo-200 dark:border-indigo-700 dark:ring-indigo-800",
                  allDone && !isActive && "border-emerald-200 dark:border-emerald-800",
                  hasError && !isActive && "border-rose-200 dark:border-rose-800",
                )}
              >
                <CardContent className="py-3 px-4 space-y-2">
                  {/* City header */}
                  <div className="flex items-center gap-2 flex-wrap">
                    <MapPin className="h-4 w-4 text-muted-foreground" />
                    <span className="font-semibold">{city.name}</span>
                    {city.county && (
                      <span className="text-xs text-muted-foreground">
                        jud. {city.county}
                      </span>
                    )}
                    <Badge
                      variant="outline"
                      className="text-[10px] font-mono"
                    >
                      {city.siruta}
                    </Badge>
                    <Badge
                      variant="outline"
                      className="text-[10px]"
                    >
                      P{city.priority}
                    </Badge>

                    {/* Status icon */}
                    {allDone ? (
                      <CheckCircle2 className="h-4 w-4 text-emerald-500 ml-auto" />
                    ) : hasError ? (
                      <XCircle className="h-4 w-4 text-rose-500 ml-auto" />
                    ) : doneCount > 0 ? (
                      <Clock className="h-4 w-4 text-amber-500 ml-auto" />
                    ) : null}

                    {/* Actions */}
                    <div className="flex gap-1 ml-auto">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 px-2 text-[10px]"
                        disabled={actionLoading}
                        onClick={() =>
                          void doAction({
                            action: "reset",
                            siruta: city.siruta,
                          })
                        }
                        title="Reseteaza progresul"
                      >
                        <RotateCcw className="h-3 w-3" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 px-2 text-[10px] text-destructive"
                        disabled={actionLoading}
                        onClick={() => {
                          if (
                            window.confirm(
                              `Stergi ${city.name} din coada?`,
                            )
                          )
                            void doAction({
                              action: "remove",
                              siruta: city.siruta,
                            });
                        }}
                        title="Sterge din coada"
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  </div>

                  {/* Steps progress */}
                  <div className="flex gap-1.5">
                    {STEPS.map((step) => {
                      const status = city.steps[step];
                      const isRunning = isActive && currentActivity?.step === step;
                      return (
                        <div
                          key={step}
                          className={cn(
                            "flex-1 rounded-md border px-2 py-1.5 text-center text-[11px] transition-colors",
                            isRunning &&
                              "bg-indigo-50 border-indigo-300 text-indigo-700 dark:bg-indigo-950/30 dark:border-indigo-700 dark:text-indigo-400 animate-pulse",
                            !isRunning && status === "done" &&
                              "bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/30 dark:border-emerald-800 dark:text-emerald-400",
                            !isRunning && status === "error" &&
                              "bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-950/30 dark:border-rose-800 dark:text-rose-400",
                            !isRunning && status === "pending" &&
                              "bg-muted/30 border-muted text-muted-foreground",
                          )}
                        >
                          {isRunning && <Loader2 className="h-3 w-3 inline mr-1 animate-spin" />}
                          {STEP_LABELS[step]}
                        </div>
                      );
                    })}
                  </div>

                  {/* DB stats + error */}
                  <div className="flex items-center gap-3 text-[11px] text-muted-foreground">
                    {city.dbStats && city.dbStats.total > 0 && (
                      <>
                        <span>
                          DB: {city.dbStats.terenuri.toLocaleString("ro")} ter.
                          + {city.dbStats.cladiri.toLocaleString("ro")} clad.
                        </span>
                        {city.dbStats.enriched > 0 && (
                          <span className="text-teal-600 dark:text-teal-400">
                            {city.dbStats.enriched.toLocaleString("ro")}{" "}
                            enriched
                          </span>
                        )}
                      </>
                    )}
                    {city.lastActivity && (
                      <span>
                        Ultima activitate:{" "}
                        {new Date(city.lastActivity).toLocaleString("ro-RO", {
                          day: "2-digit",
                          month: "2-digit",
                          hour: "2-digit",
                          minute: "2-digit",
                        })}
                      </span>
                    )}
                    {city.errorMessage && (
                      <span className="text-rose-500 truncate max-w-[300px]">
                        {city.errorMessage}
                      </span>
                    )}
                  </div>
                </CardContent>
              </Card>
            );
          })}
      </div>

      {/* Add city — UAT autocomplete */}
      <Card>
        <CardContent className="py-4">
          <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
            <Plus className="h-4 w-4" />
            Adauga oras in coada
          </h3>
          <div className="relative" ref={uatRef}>
            <div className="relative">
              <Search className="absolute left-2.5 top-2 h-4 w-4 text-muted-foreground pointer-events-none" />
              <Input
                placeholder="Cauta UAT — scrie nume sau cod SIRUTA..."
                value={uatQuery}
                onChange={(e) => {
                  setUatQuery(e.target.value);
                  setShowUatResults(true);
                }}
                onFocus={() => setShowUatResults(true)}
                onBlur={() => setTimeout(() => setShowUatResults(false), 150)}
                className="pl-9 h-9"
                autoComplete="off"
              />
            </div>
            {showUatResults && uatResults.length > 0 && (
              <div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-60 overflow-auto">
                {uatResults.map((item) => (
                  <button
                    key={item.siruta}
                    type="button"
                    className="flex w-full items-center justify-between px-3 py-2 text-sm hover:bg-accent transition-colors text-left"
                    onMouseDown={(e) => {
                      e.preventDefault();
                      void handleAddUat(item);
                    }}
                  >
                    <span className="flex items-center gap-1.5">
                      <MapPin className="h-3.5 w-3.5 text-muted-foreground" />
                      <span className="font-medium">{item.name}</span>
                      <span className="text-muted-foreground">
                        ({item.siruta})
                      </span>
                      {item.county && (
                        <span className="text-muted-foreground">
                          — jud. {item.county}
                        </span>
                      )}
                    </span>
                    <Plus className="h-3.5 w-3.5 text-muted-foreground" />
                  </button>
                ))}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Reset all button */}
      {cities.length > 0 && (
        <div className="flex justify-end">
          <Button
            variant="outline"
            size="sm"
            className="text-xs"
            disabled={actionLoading}
            onClick={() => {
              if (
                window.confirm(
                  "Resetezi progresul pentru TOATE orasele? Se va reporni ciclul de la zero.",
                )
              )
                void doAction({ action: "reset_all" });
            }}
          >
            <RotateCcw className="h-3 w-3 mr-1" />
            Reseteaza tot
          </Button>
        </div>
      )}

      {/* Info footer */}
      <div className="text-xs text-muted-foreground space-y-1 pb-4">
        <p>
          Sincronizarea ruleaza automat Vineri, Sambata si Duminica noaptea
          (23:00-04:00). Procesarea e intercalata intre orase si se reia de
          unde a ramas. Pagina se actualizeaza automat la fiecare {syncStatus === "running" ? "15" : "60"} secunde.
        </p>
        <p>
          Prioritate: P1 = primele procesate, P2 = urmatoarele, P3 = adaugate
          manual. In cadrul aceleiasi prioritati, ordinea e aleatorie.
        </p>
      </div>
    </div>
  );
}
