"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import ExperienciometroTabs from "@/components/experienciometro/ExperienciometroTabs";
import { SignalPill, TrendPill } from "@/components/experienciometro/ScorePills";
import type { ExperienceOverviewResponse } from "@/lib/experienciometro/types";

export default function ExperienciometroOverviewPage() {
  const [data, setData] = useState<ExperienceOverviewResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [signal, setSignal] = useState<"all" | "green" | "yellow" | "red">("all");

  useEffect(() => {
    const controller = new AbortController();

    const load = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const params = new URLSearchParams();
        if (search.trim()) {
          params.set("q", search.trim());
        }
        if (signal !== "all") {
          params.set("signal", signal);
        }

        const response = await fetch(`/api/experienciometro/overview?${params.toString()}`, {
          method: "GET",
          cache: "no-store",
          signal: controller.signal,
        });

        const payload = (await response.json()) as { error?: string } & ExperienceOverviewResponse;
        if (!response.ok) {
          throw new Error(payload.error ?? "No se pudo cargar Experienciómetro.");
        }

        setData(payload);
      } catch (loadError) {
        if (controller.signal.aborted) {
          return;
        }

        setError(loadError instanceof Error ? loadError.message : "No se pudo cargar Experienciómetro.");
      } finally {
        if (!controller.signal.aborted) {
          setIsLoading(false);
        }
      }
    };

    void load();

    return () => controller.abort();
  }, [search, signal]);

  const summary = useMemo(() => {
    const locations = data?.locations ?? [];
    const avgScore =
      locations.length > 0 ? Math.round((locations.reduce((acc, location) => acc + location.score, 0) / locations.length) * 10) / 10 : 0;
    const openFindings = locations.reduce((acc, location) => acc + location.openFindings, 0);

    return {
      locations: locations.length,
      avgScore,
      openFindings,
    };
  }, [data]);

  return (
    <div className="space-y-5">
      <header className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
        <p className="text-sm font-semibold uppercase tracking-wide text-benell-brown">Experienciómetro</p>
        <h1 className="mt-1 text-2xl font-semibold text-benell-text">Dashboard de experiencia por sucursal</h1>
        <p className="mt-1 text-sm text-benell-text-soft">Monitorea score, tendencia, evaluaciones y hallazgos abiertos en tiempo real.</p>
      </header>

      <ExperienciometroTabs />

      <section className="grid gap-3 md:grid-cols-3">
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Sucursales activas</p>
          <p className="mt-1 text-h2 font-semibold text-benell-text">{summary.locations}</p>
        </article>
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Score promedio</p>
          <p className="mt-1 text-h2 font-semibold text-benell-text">{summary.avgScore}</p>
        </article>
        <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <p className="text-label text-benell-text-soft">Hallazgos abiertos</p>
          <p className="mt-1 text-h2 font-semibold text-benell-text">{summary.openFindings}</p>
        </article>
      </section>

      <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
        <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_220px]">
          <label className="space-y-1">
            <span className="text-sm font-semibold text-benell-text">Buscar sucursal</span>
            <input
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              className="w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
              placeholder="Nombre o código"
            />
          </label>
          <label className="space-y-1">
            <span className="text-sm font-semibold text-benell-text">Semáforo</span>
            <select
              value={signal}
              onChange={(event) => setSignal(event.target.value as typeof signal)}
              className="w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
            >
              <option value="all">Todos</option>
              <option value="green">Excelente</option>
              <option value="yellow">Atención</option>
              <option value="red">Crítico</option>
            </select>
          </label>
        </div>
      </section>

      {error ? <p className="text-sm font-semibold text-benell-red">{error}</p> : null}
      {isLoading ? <p className="text-sm text-benell-text-soft">Cargando Experienciómetro...</p> : null}

      <section className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        {(data?.locations ?? []).map((location) => (
          <article key={location.id} className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <div className="flex items-start justify-between gap-2">
              <div>
                <h2 className="text-h3 font-semibold text-benell-text">{location.name}</h2>
                <p className="text-xs text-benell-text-soft">{location.city ?? "Sin ciudad"}</p>
              </div>
              <SignalPill signal={location.signal} />
            </div>

            <p className="mt-3 text-4xl font-semibold leading-none text-benell-text">{location.score.toFixed(1)}</p>
            <div className="mt-2">
              <TrendPill trendDirection={location.trendDirection} delta={location.trendDelta} />
            </div>

            <div className="mt-3 space-y-1 text-xs text-benell-text-soft">
              <p>Evaluaciones: {location.totalEvaluations}</p>
              <p>Hallazgos abiertos: {location.openFindings}</p>
              <p>Última evaluación: {location.lastEvaluationAt ? new Date(location.lastEvaluationAt).toLocaleString("es-MX") : "Sin registros"}</p>
              <p>Responsable: {location.managerName ?? "Sin asignar"}</p>
            </div>

            <div className="mt-4 flex gap-2">
              <Link
                href={`/experienciometro/sucursales/${location.id}`}
                className="rounded-pill border border-benell-stroke px-3 py-1.5 text-xs font-semibold text-benell-text hover:bg-benell-surface-muted"
              >
                Ver detalle
              </Link>
              <Link
                href={`/experienciometro/evaluaciones?locationId=${encodeURIComponent(location.id)}`}
                className="rounded-pill bg-benell-brown px-3 py-1.5 text-xs font-semibold text-white"
              >
                Nueva evaluación
              </Link>
            </div>
          </article>
        ))}
      </section>
    </div>
  );
}
