"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import ExperienciometroTabs from "@/components/experienciometro/ExperienciometroTabs";
import { SignalPill, TrendPill } from "@/components/experienciometro/ScorePills";
import type { ExperienceLocationDetailResponse } from "@/lib/experienciometro/types";

export default function ExperienciometroBranchDetailPage() {
  const params = useParams<{ id: string }>();
  const locationId = String(params?.id ?? "");

  const [data, setData] = useState<ExperienceLocationDetailResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!locationId) {
      return;
    }

    const controller = new AbortController();

    const load = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/experienciometro/locations/${locationId}`, {
          method: "GET",
          cache: "no-store",
          signal: controller.signal,
        });

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

        setData(payload);
      } catch (loadError) {
        if (controller.signal.aborted) {
          return;
        }
        setError(loadError instanceof Error ? loadError.message : "No se pudo cargar la sucursal.");
      } finally {
        if (!controller.signal.aborted) {
          setIsLoading(false);
        }
      }
    };

    void load();

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

  const trendData = (data?.trend ?? []).map((point) => ({
    ...point,
    date: new Date(point.evaluatedAt).toLocaleDateString("es-MX", { month: "short", day: "numeric" }),
  }));

  return (
    <div className="space-y-5">
      <header className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <p className="text-sm font-semibold uppercase tracking-wide text-benell-brown">Detalle de sucursal</p>
            <h1 className="mt-1 text-2xl font-semibold text-benell-text">{data?.location.name ?? "Sucural"}</h1>
            <p className="mt-1 text-sm text-benell-text-soft">
              {data?.location.city ?? "Sin ciudad"} · Responsable: {data?.location.managerName ?? "Sin asignar"}
            </p>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            {data?.location ? <SignalPill signal={data.location.signal} /> : null}
            {data?.location ? <TrendPill trendDirection={data.location.trendDirection} delta={data.location.trendDelta} /> : null}
            <Link
              href={`/experienciometro/evaluaciones?locationId=${encodeURIComponent(locationId)}`}
              className="rounded-pill bg-benell-brown px-3 py-2 text-sm font-semibold text-white"
            >
              Nueva evaluación
            </Link>
          </div>
        </div>
      </header>

      <ExperienciometroTabs />

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

      {data ? (
        <>
          <section className="grid gap-3 md:grid-cols-4">
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <p className="text-label text-benell-text-soft">Score actual</p>
              <p className="mt-1 text-h2 font-semibold text-benell-text">{data.location.score.toFixed(1)}</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">Evaluaciones</p>
              <p className="mt-1 text-h2 font-semibold text-benell-text">{data.location.totalEvaluations}</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">{data.location.openFindings}</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">Última evaluación</p>
              <p className="mt-1 text-sm font-semibold text-benell-text">
                {data.location.lastEvaluationAt ? new Date(data.location.lastEvaluationAt).toLocaleString("es-MX") : "Sin registros"}
              </p>
            </article>
          </section>

          <section className="grid gap-4 xl:grid-cols-2">
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <h2 className="text-h2 font-semibold">Breakdown por categoría</h2>
              <div className="mt-3 h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={data.categoryBreakdown} layout="vertical" margin={{ left: 24 }}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis type="number" domain={[0, 100]} />
                    <YAxis dataKey="categoryName" type="category" width={150} />
                    <Tooltip formatter={(value) => `${value}%`} />
                    <Bar dataKey="avgScorePct" fill="#8a6a3d" radius={[4, 4, 4, 4]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </article>

            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <h2 className="text-h2 font-semibold">Tendencia histórica</h2>
              <div className="mt-3 h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={trendData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis domain={[0, 100]} />
                    <Tooltip formatter={(value) => `${value}`} />
                    <Line dataKey="score" stroke="#3A2A1E" strokeWidth={2} dot={{ r: 3 }} />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </article>
          </section>

          <section className="grid gap-4 xl:grid-cols-2">
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <h2 className="text-h2 font-semibold">Últimas evaluaciones</h2>
              <ul className="mt-3 space-y-2">
                {data.evaluations.slice(0, 10).map((evaluation) => (
                  <li key={evaluation.id} className="rounded-xl border border-benell-stroke bg-white p-3">
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-sm font-semibold text-benell-text">{new Date(evaluation.evaluatedAt).toLocaleString("es-MX")}</p>
                      <SignalPill signal={evaluation.signal} />
                    </div>
                    <p className="text-xs text-benell-text-soft">Score: {evaluation.totalScore.toFixed(1)} · Evaluó: {evaluation.createdByName ?? "N/A"}</p>
                  </li>
                ))}
              </ul>
            </article>

            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <div className="mb-3 flex items-center justify-between gap-2">
                <h2 className="text-h2 font-semibold">Hallazgos recientes</h2>
                <Link href="/experienciometro/hallazgos" className="text-xs font-semibold text-benell-brown">
                  Ver todos
                </Link>
              </div>
              <ul className="space-y-2">
                {data.findings.slice(0, 10).map((finding) => (
                  <li key={finding.id} className="rounded-xl border border-benell-stroke bg-white p-3">
                    <p className="text-sm font-semibold text-benell-text">{finding.title}</p>
                    <p className="text-xs text-benell-text-soft">{finding.categoryLabel ?? "General"} · {finding.priority} · {finding.status}</p>
                    <p className="text-xs text-benell-text-soft">Responsable: {finding.responsibleName ?? "Sin asignar"}</p>
                  </li>
                ))}
              </ul>
            </article>
          </section>
        </>
      ) : null}
    </div>
  );
}
