"use client";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { PoleBadge } from "@/components/pole-badge";
import { useProjectStates } from "@/components/use-project-states";
import { getDefaultProjectState, projectStateTones } from "@/lib/project-state";

type Project = {
  id: string;
  name: string;
  client: string;
  manager: string;
  plannedDays: number;
  doneDays: number;
  poles: string[];
  startsAt: string;
  endsAt: string;
};

type Person = {
  id: string;
  name: string;
  role: string;
  poles: string[];
  load: number;
  availability: string;
  projects: string[];
};

type Planning = {
  projectId: string;
  team: Array<{ name: string; role: string; weekly: number[] }>;
};

export function StaffingView({ projects, people, planning }: { projects: Project[]; people: Person[]; planning: Planning[] }) {
  const { statesByProject } = useProjectStates(projects);
  const needs = projects
    .map((project) => ({
      project,
      state: statesByProject[project.id] ?? getDefaultProjectState(project),
      team: planning.find((item) => item.projectId === project.id)?.team ?? [],
      rest: Math.max(0, project.plannedDays - project.doneDays)
    }))
    .filter((item) => item.state !== "Fini")
    .sort((a, b) => b.rest - a.rest)
    .slice(0, 14);

  const availablePeople = [...people].sort((a, b) => a.load - b.load);

  return (
    <div className="min-w-0 space-y-4">
      <section className="grid gap-3 lg:grid-cols-[1fr_360px]">
        <Card className="min-w-0 overflow-hidden">
          <CardHeader className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <h1 className="text-lg font-black text-primary">Staffing projets</h1>
              <p className="text-sm text-muted-foreground">Vue de travail pour affecter les personnes disponibles sur les projets à venir ou actifs.</p>
            </div>
            <Badge tone="blue">{needs.length} besoins visibles</Badge>
          </CardHeader>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="w-full min-w-[1020px] border-collapse text-sm">
                <thead>
                  <tr className="border-b border-border bg-muted/60 text-left text-xs uppercase text-muted-foreground">
                    <th className="px-3 py-2">État</th>
                    <th className="px-3 py-2">Client</th>
                    <th className="px-3 py-2">Projet</th>
                    <th className="px-3 py-2">Pôle</th>
                    <th className="px-3 py-2">Période</th>
                    <th className="px-3 py-2">Reste</th>
                    <th className="px-3 py-2">Équipe actuelle</th>
                    <th className="px-3 py-2">Suggestions</th>
                  </tr>
                </thead>
                <tbody>
                  {needs.map(({ project, state, team, rest }) => {
                    const suggestions = suggestPeople(project, people, team.map((member) => member.name));

                    return (
                      <tr key={project.id} className="border-b border-border/70 hover:bg-[#faf7f7]">
                        <td className="px-3 py-2">
                          <Badge tone={projectStateTones[state]}>{state}</Badge>
                        </td>
                        <td className="max-w-[170px] truncate px-3 py-2 font-bold text-primary" title={project.client}>
                          {project.client}
                        </td>
                        <td className="max-w-[240px] truncate px-3 py-2" title={project.name}>
                          {project.name}
                        </td>
                        <td className="px-3 py-2">
                          <div className="flex flex-wrap gap-1">
                            {project.poles.map((pole) => (
                              <PoleBadge key={pole} pole={pole} />
                            ))}
                          </div>
                        </td>
                        <td className="px-3 py-2 text-xs text-muted-foreground">
                          {formatDate(project.startsAt)} → {formatDate(project.endsAt)}
                        </td>
                        <td className="px-3 py-2 font-bold tabular-nums text-primary">{formatNumber(rest)} j</td>
                        <td className="px-3 py-2">
                          <div className="flex max-w-[220px] flex-wrap gap-1">
                            {team.length > 0 ? (
                              team.slice(0, 4).map((member) => (
                                <span key={`${project.id}-${member.name}`} className="rounded-sm bg-[#f3eff8] px-2 py-1 text-xs font-semibold text-primary">
                                  {member.name}
                                </span>
                              ))
                            ) : (
                              <span className="text-xs text-muted-foreground">À définir</span>
                            )}
                          </div>
                        </td>
                        <td className="px-3 py-2">
                          <div className="flex max-w-[250px] flex-wrap gap-1">
                            {suggestions.map((person) => (
                              <span key={`${project.id}-${person.id}`} className="rounded-sm border border-[#cbc4df] bg-white px-2 py-1 text-xs font-semibold text-primary">
                                {person.name} · {100 - person.load}%
                              </span>
                            ))}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>

        <aside className="space-y-4">
          <Card>
            <CardHeader>
              <h2 className="text-sm font-black text-primary">Disponibilités</h2>
            </CardHeader>
            <CardContent className="space-y-2">
              {availablePeople.map((person) => (
                <div key={person.id} className="rounded-md border border-border p-2">
                  <div className="flex items-center justify-between gap-2">
                    <div className="min-w-0">
                      <div className="truncate text-sm font-bold text-primary">{person.name}</div>
                      <div className="truncate text-xs text-muted-foreground">{person.role}</div>
                    </div>
                    <span className="text-xs font-black text-primary">{person.load}%</span>
                  </div>
                  <div className="mt-2 h-2 overflow-hidden rounded-full bg-[#eee9f6]">
                    <div className="h-full bg-primary" style={{ width: `${Math.min(100, person.load)}%` }} />
                  </div>
                  <div className="mt-2 flex flex-wrap gap-1">
                    {person.poles.map((pole) => (
                      <PoleBadge key={pole} pole={pole} />
                    ))}
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>
        </aside>
      </section>
    </div>
  );
}

function suggestPeople(project: Project, people: Person[], alreadyAssigned: string[]) {
  return people
    .filter((person) => !alreadyAssigned.includes(person.name))
    .filter((person) => person.poles.some((pole) => project.poles.includes(pole)))
    .sort((a, b) => a.load - b.load)
    .slice(0, 3);
}

function formatDate(value: string) {
  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  return new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "2-digit", year: "numeric" }).format(date);
}

function formatNumber(value: number) {
  return new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 1 }).format(value);
}
