"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;
  progress: number;
  budget: string;
  plannedDays: number;
  doneDays: number;
  riskLabel: string;
  riskTone: "neutral" | "green" | "yellow" | "orange" | "red" | "blue";
  poles: string[];
  startsAt: string;
  endsAt: string;
  nextMilestone: string;
  nextMilestoneDate: string;
};

type Pole = {
  name: string;
  load: number;
  capacity: string;
  delta: string;
};

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

const currentMonth = 5;
const currentYear = 2026;

export function PortfolioView({ projects, poles, planning }: { projects: Project[]; poles: Pole[]; planning: Planning[] }) {
  const { statesByProject } = useProjectStates(projects);
  const activeThisMonth = projects.filter(isActiveInCurrentMonth);
  const riskyProjects = projects.filter((project) => ["red", "orange", "yellow"].includes(project.riskTone));
  const visibleProjects = [...projects].sort((a, b) => {
    const activeDelta = Number(isActiveInCurrentMonth(b)) - Number(isActiveInCurrentMonth(a));
    return activeDelta || a.client.localeCompare(b.client, "fr");
  });
  const totalPlanned = sum(projects.map((project) => project.plannedDays));
  const totalDone = sum(projects.map((project) => project.doneDays));

  return (
    <div className="min-w-0 space-y-4">
      <section className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <Kpi label="Projets suivis" value={projects.length.toString()} detail={`${activeThisMonth.length} actifs en juin 2026`} />
        <Kpi label="Charge prévue" value={`${formatNumber(totalPlanned)} j`} detail={`${formatNumber(totalDone)} j déjà consommés`} />
        <Kpi label="Points à arbitrer" value={riskyProjects.length.toString()} detail="risque, budget ou planning" />
        <Kpi label="Pôles" value={poles.length.toString()} detail="vue capacité et tension" />
      </section>

      <section className="grid min-w-0 gap-4 xl:grid-cols-[1fr_340px]">
        <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">Portefeuille agence</h1>
              <p className="text-sm text-muted-foreground">Vue de pilotage pour direction et responsables de pôles.</p>
            </div>
            <Badge tone="blue">{activeThisMonth.length} actifs ce mois</Badge>
          </CardHeader>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="w-full min-w-[1120px] 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">CP</th>
                    <th className="px-3 py-2">Avancement</th>
                    <th className="px-3 py-2">Risque</th>
                    <th className="px-3 py-2">Jours</th>
                    <th className="px-3 py-2">Jalon</th>
                  </tr>
                </thead>
                <tbody>
                  {visibleProjects.map((project) => {
                    const state = statesByProject[project.id] ?? getDefaultProjectState(project);
                    const projectLoad = planning.find((item) => item.projectId === project.id)?.team.length ?? 0;

                    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">{project.manager}</td>
                        <td className="px-3 py-2">
                          <div className="h-2 w-28 overflow-hidden rounded-full bg-[#eee9f6]">
                            <div className="h-full bg-primary" style={{ width: `${Math.min(100, project.progress)}%` }} />
                          </div>
                          <span className="mt-1 block text-xs text-muted-foreground">{project.progress}%</span>
                        </td>
                        <td className="px-3 py-2">
                          <Badge tone={project.riskTone}>{project.riskLabel}</Badge>
                        </td>
                        <td className="px-3 py-2 tabular-nums">
                          {formatNumber(project.doneDays)} / {formatNumber(project.plannedDays)}
                          <span className="ml-1 text-muted-foreground">({projectLoad})</span>
                        </td>
                        <td className="px-3 py-2">
                          <span className="block font-semibold text-primary">{project.nextMilestone}</span>
                          <span className="text-xs text-muted-foreground">{project.nextMilestoneDate}</span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>

        <aside className="space-y-4">
          <Card>
            <CardHeader>
              <h2 className="text-sm font-black text-primary">Capacité par pôle</h2>
            </CardHeader>
            <CardContent className="space-y-3">
              {poles.map((pole) => (
                <div key={pole.name} className="space-y-1">
                  <div className="flex items-center justify-between gap-2">
                    <PoleBadge pole={pole.name} compact={false} className="max-w-[210px] truncate" />
                    <span className="text-xs font-bold text-primary">{pole.capacity}</span>
                  </div>
                  <div className="h-2 overflow-hidden rounded-full bg-[#eee9f6]">
                    <div className="h-full bg-accent" style={{ width: `${Math.min(100, pole.load)}%` }} />
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <h2 className="text-sm font-black text-primary">Signaux faibles</h2>
            </CardHeader>
            <CardContent className="space-y-2">
              {riskyProjects.slice(0, 6).map((project) => (
                <div key={project.id} className="rounded-md border border-border p-2">
                  <div className="truncate text-sm font-bold text-primary">{project.client}</div>
                  <div className="truncate text-xs text-muted-foreground">{project.name}</div>
                  <Badge tone={project.riskTone} className="mt-2">
                    {project.riskLabel}
                  </Badge>
                </div>
              ))}
            </CardContent>
          </Card>
        </aside>
      </section>
    </div>
  );
}

function Kpi({ label, value, detail }: { label: string; value: string; detail: string }) {
  return (
    <Card>
      <CardContent className="p-3">
        <div className="text-xs font-bold uppercase text-muted-foreground">{label}</div>
        <div className="mt-1 text-2xl font-black text-primary">{value}</div>
        <div className="text-xs text-muted-foreground">{detail}</div>
      </CardContent>
    </Card>
  );
}

function isActiveInCurrentMonth(project: Project) {
  const start = new Date(project.startsAt);
  const end = new Date(project.endsAt);
  const monthStart = new Date(currentYear, currentMonth, 1);
  const monthEnd = new Date(currentYear, currentMonth + 1, 0);

  return start <= monthEnd && end >= monthStart;
}

function sum(values: number[]) {
  return values.reduce((total, value) => total + value, 0);
}

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