"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { Users } from "lucide-react";
import { formatDate } from "@/lib/marketing/labels";
import type { Employee, Initiative, Task } from "@/lib/projects/types";

export default function ProjectsTeamPage() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [initiatives, setInitiatives] = useState<Initiative[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function load() {
      setIsLoading(true);
      try {
        const response = await fetch("/api/projects/dashboard", {
          method: "GET",
          cache: "no-store",
        });

        const payload = (await response.json()) as {
          error?: string;
          employees?: Employee[];
          initiatives?: Initiative[];
          tasks?: Task[];
        };

        if (!response.ok) {
          throw new Error(payload.error ?? "No se pudo cargar Team.");
        }

        if (cancelled) {
          return;
        }

        setEmployees(payload.employees ?? []);
        setInitiatives(payload.initiatives ?? []);
        setTasks(payload.tasks ?? []);
        setError(null);
      } catch (loadError) {
        if (!cancelled) {
          setError(loadError instanceof Error ? loadError.message : "No se pudo cargar Team.");
        }
      } finally {
        if (!cancelled) {
          setIsLoading(false);
        }
      }
    }

    void load();

    return () => {
      cancelled = true;
    };
  }, []);

  const initiativeById = useMemo(() => Object.fromEntries(initiatives.map((initiative) => [initiative.id, initiative])), [initiatives]);

  const rows = useMemo(() => {
    return employees.map((employee) => {
      const assignedTasks = tasks.filter((task) => task.assigneeId === employee.id);
      const blockedItems = assignedTasks.filter((task) => task.status === "blocked");
      const assignedProjects = Array.from(new Set(assignedTasks.map((task) => initiativeById[task.initiativeId]?.name).filter(Boolean))).slice(0, 4);

      return {
        employee,
        assignedTasks,
        blockedItems,
        assignedProjects,
      };
    });
  }, [employees, initiativeById, tasks]);

  return (
    <div className="space-y-5">
      <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
        <div className="flex items-start gap-3">
          <span className="mt-1 inline-flex size-8 items-center justify-center rounded-full bg-benell-brown/10 text-benell-brown">
            <Users className="size-4" aria-hidden />
          </span>
          <div>
            <p className="text-sm font-semibold uppercase tracking-wide text-benell-brown">Projects Team</p>
            <h1 className="mt-1 text-2xl font-semibold text-benell-text">Visibilidad de equipo</h1>
            <p className="mt-1 text-sm text-benell-text-soft">Vista de sólo lectura de roles, carga activa y bloqueos.</p>
          </div>
        </div>
      </section>

      {error ? <section className="rounded-benell border border-benell-red/40 bg-benell-red/10 p-4 text-sm text-benell-red">{error}</section> : null}

      <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-benell-stroke text-sm">
            <thead className="bg-benell-surface-muted text-left text-xs uppercase tracking-wide text-benell-text-soft">
              <tr>
                <th className="px-3 py-2">Miembro</th>
                <th className="px-3 py-2">Rol</th>
                <th className="px-3 py-2">Tareas asignadas</th>
                <th className="px-3 py-2">Bloqueos</th>
                <th className="px-3 py-2">Proyectos</th>
                <th className="px-3 py-2">Acciones</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-benell-stroke">
              {rows.map(({ employee, assignedTasks, blockedItems, assignedProjects }) => (
                <tr key={employee.id} className="hover:bg-benell-surface-muted/70">
                  <td className="px-3 py-2 font-semibold text-benell-text">{employee.name}</td>
                  <td className="px-3 py-2 text-benell-text-soft">{employee.roleTitle}</td>
                  <td className="px-3 py-2 text-benell-text-soft">{assignedTasks.length}</td>
                  <td className="px-3 py-2 text-benell-red">{blockedItems.length}</td>
                  <td className="px-3 py-2 text-benell-text-soft">
                    {assignedProjects.length > 0 ? assignedProjects.join(", ") : "-"}
                  </td>
                  <td className="px-3 py-2">
                    <div className="flex flex-wrap gap-2">
                      <Link href={`/people/${employee.id}`} className="text-xs font-semibold text-benell-brown hover:underline">
                        Ver persona
                      </Link>
                      <Link href="/departments/projects/projects" className="text-xs font-semibold text-benell-brown hover:underline">
                        Ver proyectos
                      </Link>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="mt-4 grid gap-3 md:grid-cols-2">
          {rows.slice(0, 4).map(({ employee, blockedItems }) => (
            <article key={`blocked_${employee.id}`} className="rounded-lg border border-benell-stroke bg-white p-3">
              <p className="text-sm font-semibold text-benell-text">Bloqueos de {employee.name}</p>
              {blockedItems.length === 0 ? (
                <p className="mt-1 text-xs text-benell-text-soft">Sin bloqueos activos.</p>
              ) : (
                <ul className="mt-2 space-y-1 text-xs text-benell-text-soft">
                  {blockedItems.slice(0, 3).map((task) => (
                    <li key={task.id}>
                      {task.title} · vence {formatDate(task.dueDate)}
                    </li>
                  ))}
                </ul>
              )}
            </article>
          ))}
        </div>

        {isLoading ? <p className="mt-4 text-sm text-benell-text-soft">Actualizando equipo...</p> : null}
      </section>
    </div>
  );
}
