import type { BadgeTone } from "@/components/ui/badge";
import {
  activeProjects as importedActiveProjects,
  personProjectAssignments,
  projectPlanning as importedProjectPlanning,
  projects as importedProjects,
  poles as importedPoles
} from "@/lib/project-data-2026";
import { chiffragePlanningOverrides, chiffrageProjectOverrides } from "@/lib/chiffrage-imports";
import { exportedProjectPlanning, exportedProjects } from "@/lib/project-export-imports";
import { teamPeople } from "@/lib/team-data";

const projectOverridesById = chiffrageProjectOverrides as Record<string, Partial<(typeof importedProjects)[number]>>;
const planningOverridesById = chiffragePlanningOverrides as Record<string, (typeof importedProjectPlanning)[number]>;
const exportedProjectsList = exportedProjects as Array<(typeof importedProjects)[number]>;
const exportedPlanningList = exportedProjectPlanning as Array<(typeof importedProjectPlanning)[number]>;
const sentQuoteNumbers = new Set(exportedProjectsList.map((project) => project.quoteNumber).filter(Boolean));

export const poles = importedPoles;
export const projects = mergeExportedProjects(importedProjects).map(applyChiffrageProjectOverrides);
export const activeProjects = mergeExportedProjects(importedActiveProjects).map(applyChiffrageProjectOverrides);
export const projectPlanning = mergeExportedPlanning(projects, importedProjectPlanning).map((planning) => planningOverridesById[planning.projectId] ?? planning);

const legacyPoles = [
  { name: "Strategie a impact", load: 82, capacity: "31 j", delta: "+4 j" },
  { name: "Innovation et experimentation", load: 68, capacity: "24 j", delta: "-2 j" },
  { name: "UX/UI responsable", load: 94, capacity: "38 j", delta: "+9 j" },
  { name: "Design des vulnerabilites", load: 57, capacity: "18 j", delta: "-5 j" }
];

const legacyProjects = [
  {
    id: "refonte-parcours-usagers",
    name: "IMDEO Gestion intervention 2",
    client: "IMDEO",
    type: "CLIENT",
    manager: "Camille Bechet",
    progress: 62,
    budget: "9 315 EUR",
    consumed: "51 kEUR",
    margin: "28%",
    plannedDays: 124,
    doneDays: 79,
    period: "Sept. 2026 - Mars 2027",
    temperature: "Risque charge",
    tone: "red" as BadgeTone,
    riskLabel: "Risque charge",
    riskTone: "red" as BadgeTone,
    poles: ["Strategie a impact", "UX/UI responsable"],
    nextMilestone: "Prototype teste",
    nextMilestoneDate: "18 nov."
  },
  {
    id: "lab-inclusion-numerique",
    name: "HEPPNER",
    client: "Sigma Informatique",
    type: "INTERNAL_RD",
    manager: "Guillaume Bono",
    progress: 34,
    budget: "67 770 EUR",
    consumed: "18 j",
    margin: "n/a",
    plannedDays: 52,
    doneDays: 18,
    period: "Oct. 2026 - Juin 2027",
    temperature: "OK planning",
    tone: "green" as BadgeTone,
    riskLabel: "OK planning",
    riskTone: "green" as BadgeTone,
    poles: ["Innovation et experimentation", "Design des vulnerabilites"],
    nextMilestone: "Note d'experimentation",
    nextMilestoneDate: "5 dec."
  },
  {
    id: "diagnostic-accessibilite-service",
    name: "INTM - SNCF",
    client: "INTM SNCF",
    type: "CLIENT",
    manager: "Vincent Pujos",
    progress: 78,
    budget: "72 930 EUR",
    consumed: "33 kEUR",
    margin: "19%",
    plannedDays: 61,
    doneDays: 48,
    period: "Aout 2026 - Dec. 2026",
    temperature: "A surveiller",
    tone: "yellow" as BadgeTone,
    riskLabel: "A surveiller",
    riskTone: "yellow" as BadgeTone,
    poles: ["UX/UI responsable"],
    nextMilestone: "Restitution direction",
    nextMilestoneDate: "29 oct."
  },
  {
    id: "cadre-admin-sos",
    name: "NUOMA - projet",
    client: "NUOMA",
    type: "INTERNAL_ADMIN",
    manager: "Denis Charrier",
    progress: 21,
    budget: "7 000 EUR",
    consumed: "9 j",
    margin: "n/a",
    plannedDays: 38,
    doneDays: 8,
    period: "Nov. 2026 - Jan. 2027",
    temperature: "Risque budget",
    tone: "red" as BadgeTone,
    riskLabel: "Risque budget",
    riskTone: "red" as BadgeTone,
    poles: ["Strategie a impact"],
    nextMilestone: "Regles de gouvernance",
    nextMilestoneDate: "12 nov."
  }
];

const legacyActiveProjects = [
  ...projects,
  {
    id: "esean",
    name: "ESEAN",
    client: "E.S.E.A.N",
    type: "CLIENT",
    manager: "Clara Tortorici",
    progress: 48,
    budget: "61 kEUR",
    consumed: "34 kEUR",
    margin: "22%",
    plannedDays: 89,
    doneDays: 43,
    period: "Janv. 2026 - Avril 2026",
    temperature: "OK planning",
    tone: "green" as BadgeTone,
    riskLabel: "OK planning",
    riskTone: "green" as BadgeTone,
    poles: ["Strategie a impact", "UX/UI responsable"],
    nextMilestone: "Entretiens terrain",
    nextMilestoneDate: "S12"
  },
  {
    id: "hdpa",
    name: "HDPA Design artefacts",
    client: "HDPA",
    type: "CLIENT",
    manager: "Léo Fremaux",
    progress: 55,
    budget: "59 kEUR",
    consumed: "42 kEUR",
    margin: "18%",
    plannedDays: 74,
    doneDays: 41,
    period: "Fev. 2026 - Avril 2026",
    temperature: "A facturer",
    tone: "blue" as BadgeTone,
    riskLabel: "A facturer",
    riskTone: "blue" as BadgeTone,
    poles: ["Innovation et experimentation"],
    nextMilestone: "Synthese parcours",
    nextMilestoneDate: "S16"
  },
  {
    id: "aia-melioris",
    name: "NANTES CITY LAB - AAE 3",
    client: "Nantes City Lab",
    type: "CLIENT",
    manager: "Camille Sechet",
    progress: 72,
    budget: "25 kEUR",
    consumed: "19 kEUR",
    margin: "24%",
    plannedDays: 44,
    doneDays: 32,
    period: "Janv. 2026 - Juil. 2026",
    temperature: "Risque planning",
    tone: "orange" as BadgeTone,
    riskLabel: "Risque planning",
    riskTone: "orange" as BadgeTone,
    poles: ["UX/UI responsable"],
    nextMilestone: "Prototype V2",
    nextMilestoneDate: "S24"
  },
  {
    id: "edna-dgcs",
    name: "EDNA COURS DGCS",
    client: "DGCS",
    type: "CLIENT",
    manager: "Clara Chanteloup",
    progress: 38,
    budget: "50 kEUR",
    consumed: "22 kEUR",
    margin: "31%",
    plannedDays: 80,
    doneDays: 30,
    period: "Mars 2026 - Juil. 2026",
    temperature: "OK planning",
    tone: "green" as BadgeTone,
    riskLabel: "OK planning",
    riskTone: "green" as BadgeTone,
    poles: ["Design des vulnerabilites"],
    nextMilestone: "Tests acteurs",
    nextMilestoneDate: "S22"
  },
  {
    id: "mauges-ideo",
    name: "AO CCAS NANTES",
    client: "Nantes Metropole",
    type: "CLIENT",
    manager: "Tom Eade",
    progress: 31,
    budget: "16 kEUR",
    consumed: "8 kEUR",
    margin: "27%",
    plannedDays: 28,
    doneDays: 9,
    period: "Fev. 2026 - Juin 2026",
    temperature: "A valider",
    tone: "yellow" as BadgeTone,
    riskLabel: "A valider",
    riskTone: "yellow" as BadgeTone,
    poles: ["Strategie a impact"],
    nextMilestone: "COPIL",
    nextMilestoneDate: "S19"
  },
  {
    id: "samoa-one-wall",
    name: "SAMOA Atelier Récif",
    client: "SAMOA",
    type: "CLIENT",
    manager: "Élise Brohan",
    progress: 67,
    budget: "6 kEUR",
    consumed: "4 kEUR",
    margin: "20%",
    plannedDays: 18,
    doneDays: 12,
    period: "Mai 2026 - Juin 2026",
    temperature: "OK planning",
    tone: "green" as BadgeTone,
    riskLabel: "OK planning",
    riskTone: "green" as BadgeTone,
    poles: ["UX/UI responsable"],
    nextMilestone: "Validation finale",
    nextMilestoneDate: "S26"
  },
  {
    id: "vie-agence",
    name: "Vie d'agence",
    client: "Sensipode",
    type: "INTERNAL_ADMIN",
    manager: "Olivia Richard",
    progress: 40,
    budget: "Interne",
    consumed: "31 j",
    margin: "n/a",
    plannedDays: 96,
    doneDays: 38,
    period: "Janv. 2026 - Dec. 2026",
    temperature: "Interne",
    tone: "neutral" as BadgeTone,
    riskLabel: "Interne",
    riskTone: "neutral" as BadgeTone,
    poles: ["Strategie a impact"],
    nextMilestone: "Rituels agence",
    nextMilestoneDate: "S20"
  },
  {
    id: "nuoma-ia",
    name: "SIGMA - NUOMA parcours iA",
    client: "Nuoma",
    type: "CLIENT",
    manager: "Simon Boussard",
    progress: 18,
    budget: "12 kEUR",
    consumed: "5 kEUR",
    margin: "15%",
    plannedDays: 24,
    doneDays: 4,
    period: "Juin 2026 - Aout 2026",
    temperature: "Risque budget",
    tone: "red" as BadgeTone,
    riskLabel: "Risque budget",
    riskTone: "red" as BadgeTone,
    poles: ["Innovation et experimentation"],
    nextMilestone: "Cadrage IA",
    nextMilestoneDate: "S27"
  },
  {
    id: "nm-services-lot-1",
    name: "NM Services - lot 1",
    client: "Nantes Métropole",
    type: "CLIENT",
    manager: "Denis Charrier",
    progress: 44,
    budget: "10 043 EUR",
    consumed: "4 800 EUR",
    margin: "21%",
    plannedDays: 31,
    doneDays: 14,
    period: "Mars 2026 - Juin 2026",
    temperature: "OK planning",
    tone: "green" as BadgeTone,
    riskLabel: "OK planning",
    riskTone: "green" as BadgeTone,
    poles: ["UX/UI responsable"],
    nextMilestone: "Lot cadrage",
    nextMilestoneDate: "S18"
  },
  {
    id: "cher-2",
    name: "CHER [/2]",
    client: "Département du Cher",
    type: "CLIENT",
    manager: "Vincent Pujos",
    progress: 57,
    budget: "17 325 EUR",
    consumed: "9 100 EUR",
    margin: "18%",
    plannedDays: 33,
    doneDays: 19,
    period: "Mai 2026 - Juil. 2026",
    temperature: "Négo",
    tone: "orange" as BadgeTone,
    riskLabel: "Négo",
    riskTone: "orange" as BadgeTone,
    poles: ["Stratégie à impact"],
    nextMilestone: "Accord cadre",
    nextMilestoneDate: "S25"
  }
];

const legacyProjectPlanning = [
  {
    projectId: "refonte-parcours-usagers",
    status: "En cours",
    estimate: "84 kEUR",
    rest: "-7,3 j",
    weeks: [0, 0, 1, 2, 3, 4, 5, 5, 4, 6, 6, 5, 3, 2, 2, 1],
    team: [
      { name: "Clara Tortorici", role: "CP", weekly: [0, 0, 0.5, 1, 1, 1.5, 2, 2, 1.5, 2, 2, 1.5, 1, 0.5, 0.5, 0] },
      { name: "Camille Bechet", role: "UX/UI", weekly: [0, 0, 0.5, 1, 2, 2.5, 3, 3, 2.5, 3, 3, 2.5, 1.5, 1.5, 1, 1] }
    ],
    phases: [
      { name: "Cadrage", from: "S3", to: "S6", tasks: ["Ateliers", "Synthese besoins"], milestone: "Cadrage valide" },
      { name: "Prototype", from: "S7", to: "S12", tasks: ["Wireframes", "Tests usagers"], milestone: "Prototype teste" },
      { name: "Iteration", from: "S13", to: "S16", tasks: ["UI", "Restitution"], milestone: "Livrable final" }
    ]
  },
  {
    projectId: "lab-inclusion-numerique",
    status: "En cours",
    estimate: "Interne",
    rest: "16 j",
    weeks: [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 1],
    team: [{ name: "Simon Boussard", role: "Lead", weekly: [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 1] }],
    phases: [
      { name: "Exploration", from: "S6", to: "S9", tasks: ["Veille", "Hypotheses"], milestone: "Axes choisis" },
      { name: "Experimentation", from: "S10", to: "S14", tasks: ["Prototype", "Tests"], milestone: "Note d'experimentation" }
    ]
  },
  {
    projectId: "diagnostic-accessibilite-service",
    status: "En cours",
    estimate: "42 kEUR",
    rest: "8,5 j",
    weeks: [2, 2, 3, 3, 2, 2, 1, 1, 0.5, 0.5, 0, 0, 0, 0, 0, 0],
    team: [{ name: "Camille Sechet", role: "UX", weekly: [2, 2, 3, 3, 2, 2, 1, 1, 0.5, 0.5, 0, 0, 0, 0, 0, 0] }],
    phases: [
      { name: "Audit", from: "S1", to: "S4", tasks: ["Analyse", "Entretiens"], milestone: "Diagnostic partage" },
      { name: "Restitution", from: "S5", to: "S8", tasks: ["Rapport", "Comite"], milestone: "Restitution direction" }
    ]
  }
];

export const people = teamPeople.map((person) =>
  createPerson(
    person.id,
    person.name,
    person.initials,
    person.role,
    Array.from(person.poles),
    person.contract,
    person.nonWorkingDays,
    person.load,
    person.target,
    person.availability,
    person.skills,
    person.canLeadProject,
    person.teamStatus,
    person.contractStatus
  )
);

function createPerson(
  id: string,
  name: string,
  initials: string,
  role: string,
  poles: string[],
  contract: string,
  nonWorkingDays: string,
  load: number,
  target: string,
  availability: string,
  skills: string,
  canLeadProject: boolean,
  teamStatus: string,
  contractStatus: string
) {
  const planned = `${Math.max(45, Math.min(88, load - 12))}%`;
  const done = `${Math.max(42, Math.min(82, load - 17))}%`;
  const gapValue = load > 90 ? -5 : load < 70 ? 3 : -2;
  const gap = `${gapValue > 0 ? "+" : ""}${gapValue}%`;

  return {
    id,
    name,
    initials,
    role,
    poles,
    contract,
    nonWorkingDays,
    target,
    planned,
    done,
    gap,
    load,
    skills,
    canLeadProject,
    teamStatus,
    contractStatus,
    periods: {
      week: { label: "Semaine 42", planned, done, gap, load, availability: load > 95 ? "Surcharge" : "Disponible" },
      month: {
        label: "Octobre 2026",
        planned: `${Math.max(45, load - 16)}%`,
        done: `${Math.max(42, load - 20)}%`,
        gap,
        load: Math.max(45, load - 6),
        availability: load > 95 ? "1 j de tension" : "Capacité OK"
      },
      year: {
        label: "Année 2026",
        planned: `${Math.max(45, load - 22)}%`,
        done: `${Math.max(42, load - 25)}%`,
        gap: gapValue > 0 ? "+2%" : "-3%",
        load: Math.max(45, load - 12),
        availability: "Vue annuelle"
      }
    },
    availability,
    projects: getAssignedProjects(name, load)
  };
}

function getAssignedProjects(name: string, load: number) {
  const direct = personProjectAssignments[name];
  const folded = foldName(name);
  const normalized = Object.entries(personProjectAssignments).find(([person]) => foldName(person) === folded)?.[1];

  const projectsForPerson = direct ?? normalized ?? ["Aucun projet attribué"];
  const chiffrageAssignments = getChiffrageAssignments(name);

  return Array.from(new Set([...chiffrageAssignments, ...projectsForPerson]))
    .map(formatAssignedProjectLabel)
    .slice(0, load > 90 ? 8 : 6);
}

function foldName(value: string) {
  return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
}

function applyChiffrageProjectOverrides(project: (typeof importedProjects)[number]) {
  return {
    ...project,
    ...(projectOverridesById[project.id] ?? {})
  };
}

function mergeExportedProjects(sourceProjects: typeof importedProjects) {
  const sourceByQuoteNumber = new Map(sourceProjects.map((project) => [project.quoteNumber, project]));
  const mergedProjects = sourceProjects.map((project) => {
    const exportedProject = exportedProjectsList.find((candidate) => candidate.quoteNumber && candidate.quoteNumber === project.quoteNumber);

    if (!exportedProject || exportedProject.quoteNumber === "D26003") {
      return applyDefaultStateFromSentProjects(project);
    }

    return applyDefaultStateFromSentProjects({
      ...project,
      ...exportedProject,
      id: project.id
    });
  });
  const newExportedProjects = exportedProjectsList.filter(
    (project) => project.quoteNumber && !sourceByQuoteNumber.has(project.quoteNumber)
  );

  return [...mergedProjects, ...newExportedProjects];
}

function applyDefaultStateFromSentProjects(project: (typeof importedProjects)[number]) {
  if (project.quoteNumber && sentQuoteNumbers.has(project.quoteNumber)) {
    return project;
  }

  return {
    ...project,
    defaultState: "Fini" as const
  };
}

function mergeExportedPlanning(appProjects: typeof importedProjects, sourcePlanning: typeof importedProjectPlanning) {
  const projectByQuoteNumber = new Map(appProjects.map((project) => [project.quoteNumber, project]));
  const sourcePlanningByProjectId = new Map(sourcePlanning.map((planning) => [planning.projectId, planning]));
  const remappedExportedPlanning = exportedPlanningList
    .map((planning) => {
      const exportedProject = exportedProjectsList.find((project) => project.id === planning.projectId);
      const appProject = exportedProject?.quoteNumber ? projectByQuoteNumber.get(exportedProject.quoteNumber) : undefined;

      if (!appProject || exportedProject?.quoteNumber === "D26003") {
        return undefined;
      }

      return {
        ...planning,
        projectId: appProject.id
      };
    })
    .filter((planning): planning is (typeof importedProjectPlanning)[number] => Boolean(planning));
  const remappedByProjectId = new Map(remappedExportedPlanning.map((planning) => [planning.projectId, planning]));
  const mergedPlanning = appProjects.map((project) => remappedByProjectId.get(project.id) ?? sourcePlanningByProjectId.get(project.id));

  return mergedPlanning.filter((planning): planning is (typeof importedProjectPlanning)[number] => Boolean(planning));
}

function getChiffrageAssignments(name: string) {
  const folded = foldName(name);

  const chiffrageAssignments = Object.entries(chiffragePlanningOverrides)
    .filter(([, planning]) => planning.team.some((member) => foldName(member.name) === folded))
    .map(([projectId]) => projectOverridesById[projectId]?.name)
    .filter((projectName): projectName is string => Boolean(projectName));
  const exportAssignments = exportedPlanningList
    .filter((planning) => planning.team.some((member) => foldName(member.name) === folded))
    .map((planning) => exportedProjectsList.find((project) => project.id === planning.projectId)?.name)
    .filter((projectName): projectName is string => Boolean(projectName));

  return [...chiffrageAssignments, ...exportAssignments];
}

function formatAssignedProjectLabel(projectName: string) {
  const project = projects.find((candidate) => foldName(candidate.name) === foldName(projectName));

  if (!project) {
    return projectName;
  }

  return `${project.client} - ${project.name}`;
}

export const invoices = [
  {
    project: "IMDEO Gestion intervention 2",
    client: "IMDEO",
    label: "Facturation lot intervention",
    amount: "9 315 EUR",
    dueDate: "Mars 2026",
    status: "Signé",
    tone: "green" as BadgeTone,
    schedule: [0, 0, 5513, 3803, 0, 0, 0, 0, 0, 0, 0, 0]
  },
  {
    project: "HEPPNER",
    client: "Sigma Informatique",
    label: "Accompagnement UX-UI",
    amount: "67 770 EUR",
    dueDate: "Mai 2026",
    status: "Signé",
    tone: "green" as BadgeTone,
    schedule: [0, 2600, 12635, 4655, 5500, 5500, 5500, 5500, 8160, 5300, 6920, 0]
  },
  {
    project: "INTM - SNCF",
    client: "INTM SNCF",
    label: "Parcours et GRU",
    amount: "72 930 EUR",
    dueDate: "Juin 2026",
    status: "Signé",
    tone: "green" as BadgeTone,
    schedule: [0, 5850, 5850, 7215, 7215, 3120, 8580, 4290, 2340, 8580, 6630, 7800]
  },
  {
    project: "AO CCAS NANTES",
    client: "Nantes Métropole",
    label: "AO - Design de service",
    amount: "29 000 EUR",
    dueDate: "Juillet 2026",
    status: "Négo",
    tone: "orange" as BadgeTone,
    schedule: [0, 0, 0, 0, 0, 16800, 0, 0, 0, 6200, 6000, 0]
  },
  {
    project: "SIGMA - NUOMA parcours iA",
    client: "Sigma",
    label: "Parcours IA",
    amount: "13 175 EUR",
    dueDate: "Avril 2026",
    status: "Signé",
    tone: "green" as BadgeTone,
    schedule: [0, 2550, 1275, 425, 0, 1275, 1275, 1275, 1275, 1275, 1275, 1275]
  }
];

export const imports = [
  {
    source: "Conges Google Sheets",
    scope: "Presences, teletravail, absences",
    lastSync: "Aujourd'hui 08:12",
    status: "OK",
    tone: "green" as BadgeTone
  },
  {
    source: "Exports PDF",
    scope: "Vue agence, vue projet, facturation",
    lastSync: "Local uniquement",
    status: "Prepare",
    tone: "blue" as BadgeTone
  },
  {
    source: "SensiServer2",
    scope: "Sauvegardes, pieces jointes",
    lastSync: "Apres MVP",
    status: "En attente",
    tone: "neutral" as BadgeTone
  }
];
