export const legalRepresentativeRoleValues = [
  "president",
  "co_president",
  "secretaire_general",
  "directeur_gerant",
] as const;

export type LegalRepresentativeRole = typeof legalRepresentativeRoleValues[number];

export const governanceMemberRoleValues = [
  "tresorier",
  "tresorier_adjoint",
  "secretaire",
  "secretaire_adjoint",
  "administrateur",
  "charge_de_mission_referent",
  "adherent_benevole",
] as const;

export type GovernanceMemberRole = typeof governanceMemberRoleValues[number];

export const legalRepresentativeRoleLabels: Record<LegalRepresentativeRole, string> = {
  president: "Président",
  co_president: "Co-président",
  secretaire_general: "Secrétaire Général",
  directeur_gerant: "Directeur / Gérant",
};

export const governanceMemberRoleLabels: Record<GovernanceMemberRole, string> = {
  tresorier: "Trésorier",
  tresorier_adjoint: "Trésorier adjoint",
  secretaire: "Secrétaire",
  secretaire_adjoint: "Secrétaire adjoint",
  administrateur: "Membre du conseil d'administration / Administrateur",
  charge_de_mission_referent: "Chargé de mission / Référent",
  adherent_benevole: "Simple adhérent / Bénévole",
};

export const legalRepresentativeRoleOptions = legalRepresentativeRoleValues.map((value) => ({
  value,
  label: legalRepresentativeRoleLabels[value],
}));

export const governanceMemberRoleOptions = governanceMemberRoleValues.map((value) => ({
  value,
  label: governanceMemberRoleLabels[value],
}));

function normalizeRoleKey(value: string | null | undefined) {
  return String(value || "")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "");
}

export function normalizeLegalRepresentativeRole(value: string | null | undefined): LegalRepresentativeRole {
  const normalized = normalizeRoleKey(value);
  switch (normalized) {
    case "president":
    case "presidente":
      return "president";
    case "co_president":
    case "copresident":
    case "co_presidente":
      return "co_president";
    case "secretaire_general":
      return "secretaire_general";
    case "directeur":
    case "gerant":
    case "directeur_gerant":
      return "directeur_gerant";
    default:
      return "president";
  }
}

export function normalizeGovernanceMemberRole(value: string | null | undefined): GovernanceMemberRole {
  const normalized = normalizeRoleKey(value);
  switch (normalized) {
    case "tresorier":
      return "tresorier";
    case "tresorier_adjoint":
      return "tresorier_adjoint";
    case "secretaire":
      return "secretaire";
    case "secretaire_adjoint":
      return "secretaire_adjoint";
    case "administrateur":
    case "membre_du_conseil_d_administration_administrateur":
      return "administrateur";
    case "charge_de_mission":
    case "referent":
    case "charge_de_mission_referent":
      return "charge_de_mission_referent";
    default:
      return "adherent_benevole";
  }
}

export type GovernancePerson = {
  nom: string;
  prenom: string;
  email?: string | null;
  telephone?: string | null;
  fonction: string;
};

export type AssociationGovernance = {
  representantLegal: GovernancePerson | null;
  membres: GovernancePerson[];
};

export function createEmptyGovernancePerson(fonction = ""): GovernancePerson {
  return {
    nom: "",
    prenom: "",
    email: "",
    telephone: "",
    fonction,
  };
}

export function parseAssociationGovernance(value: string | null | undefined): AssociationGovernance {
  if (!value) {
    return { representantLegal: null, membres: [] };
  }

  try {
    const parsed = JSON.parse(value) as Partial<AssociationGovernance>;
    const normalizePerson = (person: any): GovernancePerson | null => {
      if (!person || typeof person !== "object") return null;
      return {
        nom: typeof person.nom === "string" ? person.nom : "",
        prenom: typeof person.prenom === "string" ? person.prenom : "",
        email: typeof person.email === "string" ? person.email : "",
        telephone: typeof person.telephone === "string" ? person.telephone : "",
        fonction: typeof person.fonction === "string" ? person.fonction : "",
      };
    };

    return {
      representantLegal: normalizePerson(parsed.representantLegal),
      membres: Array.isArray(parsed.membres)
        ? parsed.membres.map(normalizePerson).filter(Boolean) as GovernancePerson[]
        : [],
    };
  } catch {
    return { representantLegal: null, membres: [] };
  }
}

export function serializeAssociationGovernance(
  governance: AssociationGovernance | null | undefined
) {
  if (!governance?.representantLegal) return null;
  return JSON.stringify(governance);
}

export function buildDisplayName(person: GovernancePerson | null | undefined) {
  if (!person) return "";
  return [person.prenom?.trim(), person.nom?.trim()].filter(Boolean).join(" ").trim();
}

export function sanitizeGovernance(governance: AssociationGovernance): AssociationGovernance {
  const trimPerson = (
    person: GovernancePerson | null,
    roleNormalizer?: (value: string | null | undefined) => string
  ): GovernancePerson | null => {
    if (!person) return null;
    const normalized: GovernancePerson = {
      nom: person.nom.trim(),
      prenom: person.prenom.trim(),
      email: person.email?.trim() || "",
      telephone: person.telephone?.trim() || "",
      fonction: roleNormalizer ? roleNormalizer(person.fonction) : person.fonction.trim(),
    };

    if (!normalized.nom && !normalized.prenom && !normalized.email && !normalized.telephone && !normalized.fonction) {
      return null;
    }

    return normalized;
  };

  return {
    representantLegal: trimPerson(governance.representantLegal, normalizeLegalRepresentativeRole),
    membres: governance.membres
      .map((member) => trimPerson(member, normalizeGovernanceMemberRole))
      .filter((member): member is GovernancePerson => Boolean(member)),
  };
}
