import {
  buildAutodiagnosticPromptContext,
  createEmptyAutodiagnosticAnswers,
  managerialLevels,
  type AutodiagnosticAnswers,
  type AutodiagnosticResult,
  type ManagerialLevel,
} from "@/lib/autodiagnostic-shared";

export type OnboardingAnswers = {
  industrySector: string;
  department: string;
  jobTitle: string;
  managerialLevel: ManagerialLevel | "";
  companySize: string;
  companyContext: string;
  workMode: string;
};

export type ActionPlanObjective = {
  id: string;
  objectiveLabel: string;
  whatToDo: string;
  howAndWithWhom: string;
  when: string;
  successCriteria: string;
  pointOfAttention: string;
};

export type OnboardingState = {
  answers: OnboardingAnswers;
  promptContext: string;
  actionPlanPrompt: string;
  autodiagnosticAnswers: AutodiagnosticAnswers;
  autodiagnosticResult: AutodiagnosticResult | null;
  autodiagnosticPromptContext: string;
  onboardingCompleted: boolean;
  actionPlanCompleted: boolean;
  autodiagnosticCompleted: boolean;
  autodiagnosticResultAcknowledged: boolean;
};

export type OnboardingUpdateInput = {
  answers?: Partial<OnboardingAnswers>;
  actionPlanPrompt?: string;
  autodiagnosticAnswers?: Partial<AutodiagnosticAnswers>;
  autodiagnosticResult?: AutodiagnosticResult | null;
  autodiagnosticPromptContext?: string;
  completeOnboarding?: boolean;
  completeActionPlan?: boolean;
  completeAutodiagnostic?: boolean;
  acknowledgeAutodiagnosticResult?: boolean;
};

const ONE_YEAR_IN_SECONDS = 60 * 60 * 24 * 365;

export const ONBOARDING_VISITOR_COOKIE = "evol_onboarding_visitor";

export const emptyOnboardingAnswers = {
  industrySector: "",
  department: "",
  jobTitle: "",
  managerialLevel: "",
  companySize: "",
  companyContext: "",
  workMode: "",
} satisfies OnboardingAnswers;

export function createEmptyOnboardingState(): OnboardingState {
  return {
    answers: { ...emptyOnboardingAnswers },
    promptContext: "",
    actionPlanPrompt: "",
    autodiagnosticAnswers: createEmptyAutodiagnosticAnswers(),
    autodiagnosticResult: null,
    autodiagnosticPromptContext: "",
    onboardingCompleted: false,
    actionPlanCompleted: false,
    autodiagnosticCompleted: false,
    autodiagnosticResultAcknowledged: false,
  };
}

export function normalizeManagerialLevel(value: unknown): ManagerialLevel | "" {
  return typeof value === "string" &&
    managerialLevels.includes(value as ManagerialLevel)
    ? (value as ManagerialLevel)
    : "";
}

export function buildOnboardingPromptContext(answers: OnboardingAnswers) {
  const lines = [
    ["secteur_d_activite", answers.industrySector],
    ["departement", answers.department],
    ["fonction", answers.jobTitle],
    ["niveau_managerial", answers.managerialLevel],
    ["taille_entreprise", answers.companySize],
    ["contexte_entreprise", answers.companyContext],
    ["mode_de_travail", answers.workMode],
  ]
    .map(([label, value]) => [label, value.trim()] as const)
    .filter(([, value]) => value.length > 0)
    .map(([label, value]) => `- ${label}: ${value}`);

  return lines.length > 0 ? ["Variables utilisateur:", ...lines].join("\n") : "";
}

export function buildCombinedOnboardingPromptContext(state: OnboardingState) {
  const parts = [state.promptContext, state.autodiagnosticPromptContext]
    .map((part) => part.trim())
    .filter((part) => part.length > 0);

  return parts.join("\n\n");
}

export function isOnboardingComplete(answers: OnboardingAnswers) {
  return Object.values(answers).every((value) => value.trim().length > 0);
}

export function syncAutodiagnosticPromptContext(
  result: AutodiagnosticResult | null,
  currentPromptContext = "",
) {
  if (result) {
    return buildAutodiagnosticPromptContext(result);
  }

  return currentPromptContext.trim();
}

function createActionPlanObjectiveId() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }

  return `objectif-${Math.random().toString(36).slice(2, 10)}`;
}

export function createEmptyActionPlanObjective(): ActionPlanObjective {
  return {
    id: createActionPlanObjectiveId(),
    objectiveLabel: "",
    whatToDo: "",
    howAndWithWhom: "",
    when: "",
    successCriteria: "",
    pointOfAttention: "",
  };
}

export function createDefaultActionPlanObjectives() {
  return Array.from({ length: 3 }, () => createEmptyActionPlanObjective());
}

export function ensureMinimumActionPlanObjectives(
  objectives: ActionPlanObjective[],
) {
  const nextObjectives =
    objectives.length > 0 ? [...objectives] : createDefaultActionPlanObjectives();

  while (nextObjectives.length < 3) {
    nextObjectives.push(createEmptyActionPlanObjective());
  }

  return nextObjectives;
}

export function isActionPlanComplete(objectives: ActionPlanObjective[]) {
  return objectives.every((objective) =>
    [
      objective.whatToDo,
      objective.howAndWithWhom,
      objective.when,
      objective.successCriteria,
      objective.pointOfAttention,
      objective.objectiveLabel,
    ].every((value) => value.trim().length > 0),
  );
}

export function serializeActionPlanObjectives(
  objectives: ActionPlanObjective[],
) {
  const normalizeValue = (value: string) => value.replace(/\s+/g, " ").trim();

  const sanitizedObjectives = objectives.map((objective) => ({
    objectiveLabel: normalizeValue(objective.objectiveLabel),
    whatToDo: normalizeValue(objective.whatToDo),
    howAndWithWhom: normalizeValue(objective.howAndWithWhom),
    when: normalizeValue(objective.when),
    successCriteria: normalizeValue(objective.successCriteria),
    pointOfAttention: normalizeValue(objective.pointOfAttention),
  }));

  return [
    "Plan d'action",
    ...sanitizedObjectives.map((objective, index) =>
      [
        `Objectif ${index + 1}`,
        `Objectif: ${objective.objectiveLabel}`,
        `Ce que je dois faire pour y parvenir: ${objective.whatToDo}`,
        `Comment et avec qui: ${objective.howAndWithWhom}`,
        `Quand: ${objective.when}`,
        `Criteres de mesure: ${objective.successCriteria}`,
        `Point de vigilance: ${objective.pointOfAttention}`,
      ].join("\n"),
    ),
  ]
    .join("\n\n")
    .trim();
}

export function parseActionPlanPrompt(actionPlanPrompt: string) {
  const trimmedPrompt = actionPlanPrompt.trim();

  if (trimmedPrompt.length === 0) {
    return createDefaultActionPlanObjectives();
  }

  const matches = Array.from(
    trimmedPrompt.matchAll(
      /Objectif\s+\d+\s*\n([\s\S]*?)(?=\n\s*\nObjectif\s+\d+\s*\n|$)/g,
    ),
  );

  if (matches.length === 0) {
    return createDefaultActionPlanObjectives();
  }

  const objectives = matches.map((match) => {
    const block = match[1] ?? "";
    const lines = block.split("\n").map((line) => line.trim());

    const readValue = (label: string) => {
      const line = lines.find((currentLine) => currentLine.startsWith(label));
      return line ? line.slice(label.length).trim() : "";
    };

    const readAnyValue = (...labels: string[]) =>
      labels.map((label) => readValue(label)).find((value) => value.length > 0) ?? "";

    return {
      id: createActionPlanObjectiveId(),
      objectiveLabel: readValue("Objectif:"),
      whatToDo: readValue("Ce que je dois faire pour y parvenir:"),
      howAndWithWhom: readValue("Comment et avec qui:"),
      when: readValue("Quand:"),
      successCriteria: readAnyValue(
        "Criteres de mesure:",
        "CritÃ¨res de mesures:",
      ),
      pointOfAttention: readValue("Point de vigilance:"),
    } satisfies ActionPlanObjective;
  });

  return ensureMinimumActionPlanObjectives(objectives);
}

export function createOnboardingVisitorId() {
  return crypto.randomUUID();
}

export function getOnboardingVisitorCookieOptions() {
  return {
    httpOnly: true,
    sameSite: "lax" as const,
    secure: process.env.NODE_ENV === "production",
    path: "/",
    maxAge: ONE_YEAR_IN_SECONDS,
  };
}
