"use client";

import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
  authenticatedFetch,
  clearSession,
  getApiUrl,
  loadSession,
  setCurrentProjectId,
} from "@/lib/auth";
import { cloneProject, createProject, getMyProjects } from "@/lib/projects-client";
import type { ProjectStatus, ProjectSummary } from "@/types/projects";
import { ProjectPhotoModal } from "@/features/predictions/components/project-photo-modal";
import predictionStyles from "@/features/predictions/styles/predictions.module.css";
import styles from "./page.module.css";

type UserListItem = {
  id: string;
  username: string;
  displayName: string | null;
  role: "ADMIN" | "FAMILY";
};

type WizardMode = "CREATE" | "CLONE";

const legacyCards = [
  { code: "legacy_weight", label: "Poids" },
  { code: "legacy_sex", label: "Sexe" },
  { code: "legacy_names", label: "Prenoms" },
  { code: "legacy_head", label: "Perimetre cranien" },
  { code: "legacy_height", label: "Taille" },
] as const;

function normalizeBabyNickname(label: string, index: number) {
  const trimmed = label.trim();
  return trimmed.length >= 2 ? trimmed : `Bebe ${index + 1}`;
}

function buildProjectName(babyLabels: string[], babyCount: number) {
  const labels = babyLabels
    .slice(0, babyCount)
    .map((label, index) => normalizeBabyNickname(label, index));

  if (labels.length === 1) {
    return `Concours ${labels[0]}`;
  }

  if (labels.length === 2) {
    return `Concours ${labels[0]} & ${labels[1]}`;
  }

  return `Concours ${labels.slice(0, -1).join(", ")} & ${labels.at(-1)}`;
}

function statusLabel(status: ProjectStatus) {
  if (status === "OPEN") {
    return "Ouvert";
  }

  if (status === "CLOSED") {
    return "Cloture";
  }

  if (status === "FINALIZED") {
    return "Finalise";
  }

  return "Brouillon";
}

type ChoiceButtonProps = {
  label: string;
  meta: string;
  active: boolean;
  onToggle: () => void;
};

function ChoiceButton({ label, meta, active, onToggle }: Readonly<ChoiceButtonProps>) {
  return (
    <button
      type="button"
      className={`${styles.choiceButton} ${active ? styles.choiceButtonActive : ""}`}
      onClick={onToggle}
      aria-pressed={active}
    >
      <span className={styles.choiceIndicator} aria-hidden="true" />
      <span className={styles.choiceLabel}>{label}</span>
      <span className={styles.choiceMeta}>{meta}</span>
    </button>
  );
}

export default function NewProjectWizardPage() {
  const router = useRouter();
  const submitLockRef = useRef(false);
  const [ready, setReady] = useState(false);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  const [mode, setMode] = useState<WizardMode>("CREATE");
  const [stepIndex, setStepIndex] = useState(0);

  const [projects, setProjects] = useState<ProjectSummary[]>([]);
  const [users, setUsers] = useState<UserListItem[]>([]);

  const [description, setDescription] = useState("");
  const [babyCount, setBabyCount] = useState(1);
  const [status] = useState<ProjectStatus>("OPEN");
  const [babyLabels, setBabyLabels] = useState<string[]>(["Bebe 1"]);
  const [enabledLegacyCodes, setEnabledLegacyCodes] = useState<string[]>(legacyCards.map((card) => card.code));
  const [selectedParticipantIds, setSelectedParticipantIds] = useState<string[]>([]);

  const [cloneSourceProjectId, setCloneSourceProjectId] = useState("");
  const [cloneName, setCloneName] = useState("");
  const [cloneDescription, setCloneDescription] = useState("");
  const [cloneIncludeParticipants, setCloneIncludeParticipants] = useState(false);

  const [createdProject, setCreatedProject] = useState<ProjectSummary | null>(null);
  const [photoModalOpen, setPhotoModalOpen] = useState(false);

  const participantUsers = useMemo(
    () => users.filter((user) => user.role === "FAMILY"),
    [users],
  );

  const generatedProjectName = useMemo(() => {
    return buildProjectName(babyLabels, babyCount);
  }, [babyCount, babyLabels]);

  const totalSteps = mode === "CREATE" ? 7 : 2;

  useEffect(() => {
    const session = loadSession();

    if (!session) {
      router.replace("/");
      return;
    }

    if (session.user.role !== "ADMIN") {
      router.replace("/predictions");
      return;
    }

    Promise.all([
      getMyProjects(),
      authenticatedFetch(getApiUrl(), "/users").then(async (response) => {
        const payload = (await response.json()) as UserListItem[] | { message?: string };

        if (!response.ok || !Array.isArray(payload)) {
          throw new Error((payload as { message?: string }).message ?? "Impossible de charger les utilisateurs");
        }

        return payload;
      }),
    ])
      .then(([loadedProjects, loadedUsers]) => {
        setProjects(loadedProjects);
        setUsers(loadedUsers);

        if (loadedProjects.length > 0) {
          const sourceId = loadedProjects[0].id;
          setCloneSourceProjectId(sourceId);
          setCloneName(`${loadedProjects[0].name} (copie)`);
        }
      })
      .catch((error) => {
        setMessage(error instanceof Error ? error.message : "Impossible de charger le wizard projet");
      })
      .finally(() => {
        setReady(true);
      });
  }, [router]);

  useEffect(() => {
    setBabyLabels((current) => {
      const next = [...current];
      const normalizedCount = Math.max(1, Math.min(3, babyCount));

      while (next.length < normalizedCount) {
        next.push(`Bebe ${next.length + 1}`);
      }

      return next.slice(0, normalizedCount);
    });
  }, [babyCount]);

  const canGoNext = useMemo(() => {
    if (mode === "CREATE") {
      if (stepIndex === 0) {
        return true;
      }

      if (stepIndex === 1) {
        return babyLabels.slice(0, babyCount).every((label) => label.trim().length >= 2);
      }

      if (stepIndex === 2) {
        return enabledLegacyCodes.length > 0;
      }

      return true;
    }

    if (stepIndex === 0) {
      return cloneSourceProjectId.length > 0;
    }

    return true;
  }, [babyCount, babyLabels, cloneSourceProjectId, enabledLegacyCodes.length, mode, stepIndex]);

  const onSubmitWizard = async () => {
    if (submitLockRef.current) {
      return;
    }

    submitLockRef.current = true;
    setLoading(true);
    setMessage("");

    try {
      if (mode === "CREATE") {
        const created = await createProject({
          name: generatedProjectName,
          description: description.trim() || undefined,
          babyCount,
          status,
          babyLabels: babyLabels.slice(0, babyCount).map((label) => label.trim()),
          enabledLegacyCardCodes: enabledLegacyCodes,
          participantUserIds: selectedParticipantIds,
        });

        setCurrentProjectId(created.id);
        setCreatedProject(created);
        setStepIndex(5); // step 5 = indices optionnel
        return;
      }

      const cloned = await cloneProject(cloneSourceProjectId, {
        name: cloneName.trim() || undefined,
        description: cloneDescription.trim() || undefined,
        includeParticipants: cloneIncludeParticipants,
      });

      setCurrentProjectId(cloned.id);
      setMessage(`Projet clone: ${cloned.name}`);
      router.push(`/admin?project=${cloned.id}`);
    } catch (error) {
      if (error instanceof Error && error.message.includes("Session")) {
        clearSession();
        router.replace("/");
        return;
      }

      setMessage(error instanceof Error ? error.message : "Impossible de finaliser le projet");
    } finally {
      submitLockRef.current = false;
      setLoading(false);
    }
  };

  if (!ready) {
    return (
      <main className={`app-shell ${styles.page}`}>
        <section className={`panel ${styles.panel}`}>
          <p>Chargement du wizard projet...</p>
        </section>
      </main>
    );
  }

  return (
    <main className={`app-shell ${styles.page}`}>
      <section className={`panel ${styles.header}`}>
        <div>
          <p className="mono">Le Juste Poids / Admin / Projets</p>
          <h1>Assistant de creation de projet</h1>
          <p>
            Configure ton concours en etapes: infos, bebes, tuiles et participants.
          </p>
        </div>
        <div className={styles.headerActions}>
          <Link className="btn btn-soft" href="/admin">
            Retour admin
          </Link>
        </div>
      </section>

      <section className={`panel ${styles.panel}`}>
        <div className={styles.modeSwitch}>
          <button
            type="button"
            className={`${styles.modeButton} ${mode === "CREATE" ? styles.modeButtonActive : ""}`}
            onClick={() => {
              setMode("CREATE");
              setStepIndex(0);
            }}
          >
            Nouveau projet guide
          </button>
          <button
            type="button"
            className={`${styles.modeButton} ${mode === "CLONE" ? styles.modeButtonActive : ""}`}
            onClick={() => {
              setMode("CLONE");
              setStepIndex(0);
            }}
          >
            Cloner un projet existant
          </button>
        </div>

        <div className={styles.stepHeader}>
          <span className={styles.stepPill}>Etape {stepIndex + 1} / {totalSteps}</span>
          <p className={styles.helpText}>
            {mode === "CREATE"
              ? "Configuration rapide du concours"
              : "Ideal pour separer famille et amis rapidement"}
          </p>
        </div>

        {mode === "CREATE" && stepIndex === 0 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Vous attendez combien de bebe ?</h3>
                <p>Choisissez simplement le nombre de bebes pour preparer les espaces de pronostic.</p>
              </div>
              <span className={predictionStyles.badge}>Demarrage</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody}`}>
            <div className={predictionStyles.optionIconsRow}>
              {[1, 2, 3].map((count) => {
                const active = babyCount === count;

                return (
                  <button
                    key={count}
                    type="button"
                    className={`${predictionStyles.optionIconBtn} ${styles.wizardCountBtn} ${active ? predictionStyles.optionIconBtnActive : ""}`}
                    onClick={() => setBabyCount(count)}
                    aria-pressed={active}
                  >
                    <span className={styles.countChoiceCircle}>{count}</span>
                    <span>{count === 1 ? "1 bebe" : `${count} bebes`}</span>
                  </button>
                );
              })}
            </div>
            <div className={styles.compactField}>
              <label htmlFor="projectDescription">Description</label>
              <input
                id="projectDescription"
                value={description}
                onChange={(event) => setDescription(event.target.value)}
                placeholder="Optionnel: concours famille proche, annonce de juillet..."
              />
            </div>
            </div>
          </article>
        ) : null}

        {mode === "CREATE" && stepIndex === 1 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Quels surnoms voulez-vous afficher pour bebe ?</h3>
                <p>Bubulle, Mini-nous, Petit haricot... gardez un nom doux et temporaire si vous voulez faire deviner le prenom.</p>
              </div>
              <span className={predictionStyles.badge}>Surnoms</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody} ${styles.formGrid}`}>
            {babyLabels.slice(0, babyCount).map((label, index) => (
              <div className="field" key={`baby-label-${index + 1}`}>
                <label htmlFor={`babyLabel-${index + 1}`}>Surnom / pseudo bebe {index + 1}</label>
                <input
                  id={`babyLabel-${index + 1}`}
                  value={label}
                  onChange={(event) => {
                    const value = event.target.value;
                    setBabyLabels((current) => {
                      const next = [...current];
                      next[index] = value;
                      return next;
                    });
                  }}
                  placeholder={index === 0 ? "Ex: Bubulle" : `Ex: Babychou ${index + 1}`}
                />
              </div>
            ))}
            </div>
          </article>
        ) : null}

        {mode === "CREATE" && stepIndex === 2 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Quels pronostics voulez-vous ouvrir ?</h3>
                <p>Selectionnez les categories a afficher aux proches dans le concours.</p>
              </div>
              <span className={predictionStyles.badge}>Cartes</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody} ${styles.selectionGrid}`}>
            {legacyCards.map((card) => {
              const checked = enabledLegacyCodes.includes(card.code);
              return (
                <ChoiceButton
                  key={card.code}
                  label={card.label}
                  meta={checked ? "Active" : "Touchez pour activer"}
                  active={checked}
                  onToggle={() => {
                    setEnabledLegacyCodes((current) => {
                      if (current.includes(card.code)) {
                        return current.filter((value) => value !== card.code);
                      }
                      return [...current, card.code];
                    });
                  }}
                />
              );
            })}
            </div>
          </article>
        ) : null}

        {mode === "CREATE" && stepIndex === 3 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Qui participe des le depart ?</h3>
                <p>Ajoutez les proches a pre-affecter maintenant. Vous pourrez toujours les gerer plus tard.</p>
              </div>
              <span className={predictionStyles.badge}>Participants</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody} ${styles.selectionGrid}`}>
            {participantUsers.map((user) => {
              const checked = selectedParticipantIds.includes(user.id);
              return (
                <ChoiceButton
                  key={user.id}
                  label={user.displayName ?? user.username}
                  meta={checked ? "Selectionne" : "Disponible"}
                  active={checked}
                  onToggle={() => {
                    setSelectedParticipantIds((current) => {
                      if (current.includes(user.id)) {
                        return current.filter((value) => value !== user.id);
                      }
                      return [...current, user.id];
                    });
                  }}
                />
              );
            })}
            {participantUsers.length === 0 ? <div className={styles.emptyState}>Aucun participant family disponible pour le moment.</div> : null}
            </div>
          </article>
        ) : null}

        {mode === "CREATE" && stepIndex === 4 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Verifier avant creation</h3>
                <p>Un dernier coup d&apos;oeil avant d&apos;ouvrir le concours.</p>
              </div>
              <span className={predictionStyles.badge}>Recap</span>
            </header>
            <div className={styles.summaryList}>
            <p><strong>Nom du projet</strong><span>{generatedProjectName}</span></p>
            <p><strong>Description</strong><span>{description || "-"}</span></p>
            <p><strong>Bebes</strong><span>{babyCount}</span></p>
            <p><strong>Statut</strong><span>{statusLabel(status)}</span></p>
            <p><strong>Surnoms bebe</strong><span>{babyLabels.slice(0, babyCount).map((label, index) => normalizeBabyNickname(label, index)).join(" / ")}</span></p>
            <p>
              <strong>Cartes actives</strong><span>{legacyCards
                .filter((card) => enabledLegacyCodes.includes(card.code))
                .map((card) => card.label)
                .join(", ")}
              </span>
            </p>
            <p><strong>Participants pre-affectes</strong><span>{selectedParticipantIds.length}</span></p>
            </div>
          </article>
        ) : null}

        {mode === "CREATE" && stepIndex === 5 && createdProject ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Configurer les indices de grossesse ?</h3>
                <p>Vous pouvez renseigner maintenant les informations parents et echo, ou le faire plus tard depuis l&apos;admin.</p>
              </div>
              <span className={predictionStyles.badge}>Optionnel</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody} ${styles.actionStack}`}>
              <button
                type="button"
                className="btn btn-primary"
                onClick={() => router.push(`/admin/projects/${createdProject.id}/indices`)}
              >
                Configurer les indices maintenant
              </button>
              <button
                type="button"
                className="btn btn-soft"
                onClick={() => setStepIndex(6)}
              >
                Passer pour l&apos;instant
              </button>
            </div>
          </article>
        ) : mode === "CREATE" && stepIndex === 6 && createdProject ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Photo du projet</h3>
                <p>Ajoutez une photo ou un avatar pour illustrer le concours dans la banniere.</p>
              </div>
              <span className={predictionStyles.badge}>Optionnel</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody} ${styles.photoStepBody}`}>
              {createdProject.projectImageUrl ? (
                <div className={styles.photoPreviewFilled} style={{ background: createdProject.projectBgColor ?? "var(--panel-warm)" }}>
                  <img src={`${getApiUrl()}${createdProject.projectImageUrl}`} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </div>
              ) : (
                <div className={styles.photoPreviewEmpty}>
                  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                    <rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" />
                    <polyline points="21 15 16 10 5 21" />
                  </svg>
                </div>
              )}
              <button type="button" className="btn btn-soft" onClick={() => setPhotoModalOpen(true)}>
                {createdProject.projectImageUrl ? "Modifier la photo" : "Ajouter une photo"}
              </button>
            </div>
          </article>
        ) : null}

        {mode === "CLONE" && stepIndex === 0 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Cloner un projet existant</h3>
                <p>Selectionnez une base existante puis ajustez le nom et la description si besoin.</p>
              </div>
              <span className={predictionStyles.badge}>Clone</span>
            </header>
            <div className={`${predictionStyles.tileBody} ${styles.wizardTileBody} ${styles.formGrid}`}>
            <div className="field">
              <label htmlFor="cloneSource">Projet source</label>
              <select
                id="cloneSource"
                value={cloneSourceProjectId}
                onChange={(event) => {
                  const sourceId = event.target.value;
                  setCloneSourceProjectId(sourceId);
                  const source = projects.find((project) => project.id === sourceId);
                  if (source) {
                    setCloneName(`${source.name} (copie)`);
                  }
                }}
              >
                <option value="">Choisir un projet</option>
                {projects.map((project) => (
                  <option key={project.id} value={project.id}>
                    {project.name}
                  </option>
                ))}
              </select>
            </div>
            <div className="field">
              <label htmlFor="cloneName">Nom du clone</label>
              <input
                id="cloneName"
                value={cloneName}
                onChange={(event) => setCloneName(event.target.value)}
              />
            </div>
            <div className="field">
              <label htmlFor="cloneDescription">Description du clone</label>
              <input
                id="cloneDescription"
                value={cloneDescription}
                onChange={(event) => setCloneDescription(event.target.value)}
                placeholder="Optionnel"
              />
            </div>
            <div className={styles.fullSpan}>
              <ChoiceButton
                label="Copier aussi les participants"
                meta={cloneIncludeParticipants ? "Active" : "Laisser desactive"}
                active={cloneIncludeParticipants}
                onToggle={() => setCloneIncludeParticipants((current) => !current)}
              />
            </div>
            </div>
          </article>
        ) : null}

        {mode === "CLONE" && stepIndex === 1 ? (
          <article className={`${predictionStyles.tile} ${styles.wizardTile}`}>
            <header className={predictionStyles.tileHeader}>
              <div>
                <h3>Verifier le clone</h3>
                <p>Confirmez les informations avant de dupliquer ce projet.</p>
              </div>
              <span className={predictionStyles.badge}>Recap</span>
            </header>
            <div className={styles.summaryList}>
            <p>
              <strong>Source</strong><span>{projects.find((project) => project.id === cloneSourceProjectId)?.name ?? "-"}</span>
            </p>
            <p><strong>Nouveau nom</strong><span>{cloneName || "(copie auto)"}</span></p>
            <p><strong>Description</strong><span>{cloneDescription || "(identique source)"}</span></p>
            <p>
              <strong>Participants</strong><span>{cloneIncludeParticipants ? "Copie activee" : "Non copies"}</span>
            </p>
            </div>
          </article>
        ) : null}

        <div className={styles.wizardActions}>
          <button
            type="button"
            className="btn btn-soft"
            onClick={() => setStepIndex((current) => Math.max(0, current - 1))}
            disabled={loading || stepIndex === 0 || stepIndex === 5 || stepIndex === 6}
          >
            Retour
          </button>
          {stepIndex === 5 ? null
          : stepIndex === 6 && createdProject ? (
            <button
              type="button"
              className="btn btn-primary"
              onClick={() => router.push(`/admin?project=${createdProject.id}`)}
            >
              Terminer
            </button>
          ) : mode === "CREATE" && stepIndex === 4 ? (
            <button
              type="button"
              className="btn btn-primary"
              onClick={() => { void onSubmitWizard(); }}
              disabled={loading || !canGoNext}
            >
              {loading ? "Creation..." : "Creer le projet"}
            </button>
          ) : stepIndex < totalSteps - 1 ? (
            <button
              type="button"
              className="btn btn-primary"
              onClick={() => setStepIndex((current) => Math.min(totalSteps - 1, current + 1))}
              disabled={loading || !canGoNext}
            >
              Continuer
            </button>
          ) : (
            <button
              type="button"
              className="btn btn-primary"
              onClick={() => { void onSubmitWizard(); }}
              disabled={loading || !canGoNext}
            >
              {loading ? "Clonage..." : "Cloner le projet"}
            </button>
          )}
        </div>

        {photoModalOpen && createdProject ? (
          <ProjectPhotoModal
            project={createdProject}
            onSuccess={(updated) => setCreatedProject(updated)}
            onClose={() => setPhotoModalOpen(false)}
          />
        ) : null}

        {message ? <p className={styles.message}>{message}</p> : null}
      </section>
    </main>
  );
}
