"use client";

import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import type { TalleresSnapshot, WorkshopEvidenceView, WorkshopView } from "@/lib/talleres/types";

type TalleresDesarrolloViewProps = {
  initialSnapshot: TalleresSnapshot;
  initialDimension?: string | null;
};

type ApiResponse = {
  ok?: boolean;
  error?: string;
  warning?: string;
  payload?: TalleresSnapshot;
};

function statusTone(status: WorkshopView["status"]) {
  if (status === "APPROVED") {
    return "border-[#b6e5cd] bg-[#e7f8ef] text-[#1b8f62]";
  }

  if (status === "REJECTED") {
    return "border-[#efc4c4] bg-[#fff0f0] text-[#a43f3f]";
  }

  if (status === "EVIDENCE_SUBMITTED") {
    return "border-[#d5caef] bg-[#f3edff] text-[#6a4aa8]";
  }

  if (status === "WATCHED") {
    return "border-[#c5d8f0] bg-[#ecf4ff] text-[#2f5ea4]";
  }

  if (status === "SKIPPED") {
    return "border-[#d9dfea] bg-[#f3f6fb] text-[#5e6f8e]";
  }

  return "border-[#d9dfea] bg-[#f3f6fb] text-[#5e6f8e]";
}

function statusLabel(status: WorkshopView["status"]) {
  if (status === "APPROVED") {
    return "Aprobado";
  }

  if (status === "REJECTED") {
    return "Rechazado";
  }

  if (status === "EVIDENCE_SUBMITTED") {
    return "Evidencia enviada";
  }

  if (status === "WATCHED") {
    return "Visto";
  }

  if (status === "SKIPPED") {
    return "Lo vere despues";
  }

  return "Pendiente";
}

function evidenceTone(status: WorkshopEvidenceView["validationStatus"] | undefined) {
  if (status === "APPROVED") {
    return "text-[#1f865f]";
  }

  if (status === "REJECTED") {
    return "text-[#a43f3f]";
  }

  if (status === "ERROR") {
    return "text-[#8559bd]";
  }

  return "text-[#476088]";
}

function validationLabel(status: WorkshopEvidenceView["validationStatus"] | undefined) {
  if (status === "APPROVED") {
    return "Aprobada";
  }

  if (status === "REJECTED") {
    return "Rechazada";
  }

  if (status === "ERROR") {
    return "Pendiente por validar";
  }

  if (status === "PENDING") {
    return "En validacion";
  }

  return "Sin evidencia";
}

export function TalleresDesarrolloView({ initialSnapshot, initialDimension }: TalleresDesarrolloViewProps) {
  const [snapshot, setSnapshot] = useState<TalleresSnapshot>(initialSnapshot);
  const [activeDimension, setActiveDimension] = useState<string>(() => {
    const keySet = new Set(initialSnapshot.dimensions.map((dimension) => dimension.moduleKey));
    if (initialDimension && keySet.has(initialDimension)) {
      return initialDimension;
    }

    return initialSnapshot.dimensions[0]?.moduleKey ?? "";
  });
  const [activeWorkshop, setActiveWorkshop] = useState<WorkshopView | null>(null);
  const [uploadingWorkshopId, setUploadingWorkshopId] = useState<string | null>(null);
  const [isSavingProgress, setIsSavingProgress] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const activeDimensionMeta = snapshot.dimensions.find((dimension) => dimension.moduleKey === activeDimension) ?? null;
  const workshops = snapshot.workshopsByDimension[activeDimension] ?? [];

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

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setActiveWorkshop(null);
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [activeWorkshop]);

  const dimensionsWithGapCount = useMemo(() => snapshot.dimensions.filter((dimension) => dimension.gapLevel !== "baja").length, [snapshot]);

  function clearMessages() {
    setErrorMessage(null);
    setSuccessMessage(null);
  }

  function applyPayload(payload?: TalleresSnapshot) {
    if (!payload) {
      return;
    }

    setSnapshot(payload);

    if (!payload.dimensions.some((dimension) => dimension.moduleKey === activeDimension)) {
      setActiveDimension(payload.dimensions[0]?.moduleKey ?? "");
    }
  }

  async function saveProgress(workshopId: string, action: "WATCHED" | "SKIPPED") {
    clearMessages();
    setIsSavingProgress(true);

    try {
      const response = await fetch("/api/talleres/progress", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ workshopId, action }),
      });

      const payload = (await response.json().catch(() => ({}))) as ApiResponse;

      if (!response.ok || !payload.ok || !payload.payload) {
        setErrorMessage(payload.error ?? "No fue posible actualizar el avance del taller.");
        return;
      }

      applyPayload(payload.payload);
      setSuccessMessage(action === "WATCHED" ? "Taller marcado como visto." : "Guardamos que lo veras despues.");
    } catch {
      setErrorMessage("No fue posible actualizar el avance del taller.");
    } finally {
      setIsSavingProgress(false);
    }
  }

  async function uploadEvidence(workshopId: string, file: File) {
    clearMessages();
    setUploadingWorkshopId(workshopId);

    try {
      const formData = new FormData();
      formData.append("workshopId", workshopId);
      formData.append("file", file);

      const response = await fetch("/api/talleres/evidence", {
        method: "POST",
        body: formData,
      });

      const payload = (await response.json().catch(() => ({}))) as ApiResponse;

      if (!response.ok || !payload.ok || !payload.payload) {
        setErrorMessage(payload.error ?? "No fue posible subir tu evidencia.");
        return;
      }

      applyPayload(payload.payload);
      setSuccessMessage(payload.warning ?? "Evidencia enviada correctamente.");
      setActiveWorkshop(null);
    } catch {
      setErrorMessage("No fue posible subir tu evidencia.");
    } finally {
      setUploadingWorkshopId(null);
    }
  }

  return (
    <div className="space-y-5">
      <div className="grid gap-3 md:grid-cols-3">
        <Card>
          <CardContent className="py-4">
            <p className="text-sm text-[#5f7294]">Indice de Madurez</p>
            <p className="mt-1 text-5xl font-semibold text-[#12274d]">{Math.round(snapshot.overallMaturity)}%</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-sm text-[#5f7294]">Dimensiones con Brechas</p>
            <p className="mt-1 text-5xl font-semibold text-[#12274d]">{dimensionsWithGapCount} de {snapshot.dimensions.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-sm text-[#5f7294]">Meta</p>
            <p className="mt-1 text-5xl font-semibold text-[#1fa574]">100%</p>
          </CardContent>
        </Card>
      </div>

      <Card className="border-[#d8e2ef] bg-[#f7fafc]">
        <CardContent className="py-4 text-sm text-[#304560]">
          <p>
            <span className="font-semibold text-[#18325f]">Como funciona?</span> Cada taller te ensena como cumplir un requisito especifico.
            Al finalizar, sube tu evidencia (documento, imagen, etc.) y nuestra validacion automatica evaluara el archivo al instante.
          </p>
        </CardContent>
      </Card>

      <div className="flex flex-wrap gap-2">
        {snapshot.dimensions.map((dimension) => (
          <button
            key={dimension.moduleKey}
            type="button"
            onClick={() => setActiveDimension(dimension.moduleKey)}
            className={`rounded-full border px-4 py-2 text-sm font-semibold transition-colors ${
              activeDimension === dimension.moduleKey
                ? "border-[#12306a] bg-[#12306a] text-white"
                : "border-[#d2dbea] bg-white text-[#52678c] hover:border-[#9fb4d6]"
            }`}
          >
            {dimension.moduleName} <span className="ml-2 rounded-full bg-[#26a879] px-2 py-0.5 text-white">{Math.round(dimension.displayScore)}%</span>
          </button>
        ))}
      </div>

      <Card>
        <CardHeader className="flex flex-row flex-wrap items-center justify-between gap-2">
          <div>
            <h3 className="text-3xl font-semibold text-[#132447] [font-family:var(--font-display)]">{activeDimensionMeta?.moduleName ?? "Dimension"}</h3>
            <p className="text-sm text-[#60718f]">{workshops.length} brechas por cubrir con talleres guiados.</p>
          </div>
          {activeDimensionMeta ? (
            <span className="rounded-full border border-[#d3dced] bg-[#f6f8fc] px-3 py-1 text-sm font-semibold text-[#243b63]">
              Puntaje: {Math.round(activeDimensionMeta.displayScore)}%
            </span>
          ) : null}
        </CardHeader>
        <CardContent className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {workshops.map((workshop) => (
            <article key={workshop.id} className="rounded-2xl border border-[#d7dfed] bg-white p-4">
              <div className="flex flex-wrap items-start justify-between gap-2">
                <h4 className="text-xl font-semibold text-[#152748]">{workshop.title}</h4>
                <span className={`rounded-full border px-2 py-1 text-xs font-semibold ${statusTone(workshop.status)}`}>{statusLabel(workshop.status)}</span>
              </div>
              <p className="mt-1 text-sm text-[#607291]">Duracion: {workshop.durationMinutes} min</p>
              <p className="mt-3 text-sm text-[#607291]">{workshop.summary}</p>

              <div className="mt-3 rounded-xl border border-[#dbe3ef] bg-[#f9fbfe] p-3 text-sm text-[#314864]">
                <p className="font-semibold text-[#173463]">Brecha a cubrir</p>
                <p className="mt-1">Al completar este taller y subir evidencia, mejoraras tu puntaje en esta dimension.</p>
              </div>

              <div className="mt-3">
                <p className="text-sm font-semibold text-[#173463]">Aprenderas:</p>
                <ul className="mt-1 space-y-1 text-sm text-[#607291]">
                  {workshop.learningObjectives.map((objective) => (
                    <li key={objective}>- {objective}</li>
                  ))}
                </ul>
              </div>

              {workshop.latestEvidence ? (
                <p className={`mt-3 text-xs font-semibold ${evidenceTone(workshop.latestEvidence.validationStatus)}`}>
                  Evidencia {validationLabel(workshop.latestEvidence.validationStatus)}: {workshop.latestEvidence.fileName}
                </p>
              ) : null}

              <div className="mt-4 space-y-2">
                <Button
                  variant="secondary"
                  className="w-full"
                  onClick={() => {
                    setActiveWorkshop(workshop);
                  }}
                >
                  Ver Taller
                </Button>

                <label className="block">
                  <input
                    type="file"
                    className="hidden"
                    accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                    onChange={(event) => {
                      const file = event.target.files?.[0];
                      if (file) {
                        void uploadEvidence(workshop.id, file);
                      }
                      event.target.value = "";
                    }}
                  />
                  <span className="inline-flex h-10 w-full items-center justify-center rounded-lg bg-[#0f2a5f] px-4 text-sm font-semibold text-white transition-colors hover:bg-[#0c234e]">
                    {uploadingWorkshopId === workshop.id ? "Subiendo evidencia..." : "Subir Evidencia"}
                  </span>
                </label>
              </div>
            </article>
          ))}
        </CardContent>
      </Card>

      {errorMessage ? <p className="rounded-xl border border-[#efc4c4] bg-[#fff1f1] px-3 py-2 text-sm text-[#ad3f3f]">{errorMessage}</p> : null}
      {successMessage ? <p className="rounded-xl border border-[#bde5ce] bg-[#ecf9f1] px-3 py-2 text-sm text-[#1f7f4f]">{successMessage}</p> : null}

      {activeWorkshop ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-[#07142d]/55 p-4"
          role="dialog"
          aria-modal="true"
          onMouseDown={(event) => {
            if (event.target === event.currentTarget) {
              setActiveWorkshop(null);
            }
          }}
        >
          <div className="max-h-[92vh] w-full max-w-5xl overflow-y-auto rounded-2xl bg-white p-4 md:p-6">
            <div className="mb-4 flex items-start justify-between gap-3">
              <div>
                <h4 className="text-3xl font-semibold text-[#12274d]">{activeWorkshop.title}</h4>
                <p className="text-sm text-[#60718f]">{activeWorkshop.summary}</p>
              </div>
              <Button variant="secondary" onClick={() => setActiveWorkshop(null)}>
                Cerrar
              </Button>
            </div>

            <div className="overflow-hidden rounded-xl border border-[#d4dceb]">
              <iframe
                className="h-[320px] w-full md:h-[460px]"
                src={activeWorkshop.videoUrl}
                title={`Video de ${activeWorkshop.title}`}
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                referrerPolicy="strict-origin-when-cross-origin"
                allowFullScreen
              />
            </div>

            <div className="mt-4 space-y-3">
              <div className="rounded-xl border border-[#dce3ef] bg-[#f8fbfe] p-3">
                <p className="font-semibold text-[#15305d]">Evidencia requerida:</p>
                <p className="text-sm text-[#60718f]">{activeWorkshop.evidenceRequired}</p>
              </div>

              <div className="rounded-xl border border-[#c8d8f2] bg-[#eef5ff] p-3">
                <p className="font-semibold text-[#1a3768]">Proceso para completar el taller:</p>
                <ol className="mt-2 space-y-1 text-sm text-[#31507b]">
                  <li>1. Ve el video completo para entender los conceptos.</li>
                  <li>2. Aplica lo aprendido con tu equipo.</li>
                  <li>3. Prepara tu evidencia en PDF o imagen.</li>
                  <li>4. Sube tu evidencia para validacion automatica.</li>
                </ol>
              </div>
            </div>

            <div className="mt-4 grid gap-2 md:grid-cols-2">
              <Button
                disabled={isSavingProgress}
                onClick={() => {
                  void saveProgress(activeWorkshop.id, "WATCHED");
                }}
              >
                {isSavingProgress ? "Guardando..." : "Ya vi el video, quiero subir evidencia"}
              </Button>
              <Button
                variant="secondary"
                disabled={isSavingProgress}
                onClick={() => {
                  void saveProgress(activeWorkshop.id, "SKIPPED");
                  setActiveWorkshop(null);
                }}
              >
                Lo vere despues
              </Button>
            </div>

            <label className="mt-2 block">
              <input
                type="file"
                className="hidden"
                accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                onChange={(event) => {
                  const file = event.target.files?.[0];
                  if (file) {
                    void uploadEvidence(activeWorkshop.id, file);
                  }
                  event.target.value = "";
                }}
              />
              <span className="inline-flex h-10 w-full items-center justify-center rounded-lg bg-[#0f2a5f] px-4 text-sm font-semibold text-white transition-colors hover:bg-[#0c234e]">
                {uploadingWorkshopId === activeWorkshop.id ? "Subiendo evidencia..." : "Subir evidencia ahora"}
              </span>
            </label>
          </div>
        </div>
      ) : null}
    </div>
  );
}
