"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  getCurrentProjectId,
  PROJECT_CHANGED_EVENT,
  setCurrentProjectId,
} from "@/lib/auth";
import { getMyProjects } from "@/lib/projects-client";
import type { ProjectSummary } from "@/types/projects";
import styles from "@/features/predictions/styles/predictions.module.css";

type ProjectSwitcherProps = {
  showCreateAction?: boolean;
  className?: string;
  onProjectChanged?: (projectId: string) => void;
};

export function ProjectSwitcher({
  showCreateAction = false,
  className,
  onProjectChanged,
}: ProjectSwitcherProps) {
  const [projects, setProjects] = useState<ProjectSummary[]>([]);
  const [currentProjectId, setCurrentProjectIdState] = useState<string | null>(
    getCurrentProjectId(),
  );
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState("");
  const onProjectChangedRef = useRef(onProjectChanged);

  useEffect(() => {
    onProjectChangedRef.current = onProjectChanged;
  }, [onProjectChanged]);

  const currentProject = useMemo(
    () => projects.find((project) => project.id === currentProjectId) ?? null,
    [currentProjectId, projects],
  );

  const selectProject = useCallback(
    (projectId: string) => {
      setCurrentProjectId(projectId);
      setCurrentProjectIdState(projectId);
      onProjectChangedRef.current?.(projectId);
    },
    [],
  );

  const reloadProjects = useCallback(() => {
    setLoading(true);
    setMessage("");

    getMyProjects()
      .then((loadedProjects) => {
        setProjects(loadedProjects);

        if (loadedProjects.length === 0) {
          setCurrentProjectIdState(null);
          setCurrentProjectId(null);
          return;
        }

        const savedProjectId = getCurrentProjectId();
        const preferredId = savedProjectId;

        const targetProject =
          loadedProjects.find((project) => project.id === preferredId) ?? loadedProjects[0];

        if (!targetProject) {
          return;
        }

        if (targetProject.id !== savedProjectId) {
          selectProject(targetProject.id);
        } else {
          setCurrentProjectIdState(targetProject.id);
        }
      })
      .catch((error) => {
        setMessage(error instanceof Error ? error.message : "Impossible de charger les projets");
      })
      .finally(() => {
        setLoading(false);
      });
  }, [selectProject]);

  useEffect(() => {
    reloadProjects();
  }, [reloadProjects]);

  useEffect(() => {
    const handleProjectChange = (event: Event) => {
      const customEvent = event as CustomEvent<{ projectId?: string | null }>;
      const nextProjectId = customEvent.detail?.projectId ?? null;
      setCurrentProjectIdState(nextProjectId);
    };

    window.addEventListener(PROJECT_CHANGED_EVENT, handleProjectChange as EventListener);
    return () => {
      window.removeEventListener(PROJECT_CHANGED_EVENT, handleProjectChange as EventListener);
    };
  }, []);

  if (loading) {
    return (
      <div className={`${styles.projectSwitcher} ${className ?? ""}`.trim()}>
        <span className={styles.projectSwitcherMeta}>Chargement des projets...</span>
      </div>
    );
  }

  if (message) {
    return (
      <div className={`${styles.projectSwitcher} ${className ?? ""}`.trim()}>
        <span className={styles.projectSwitcherError}>{message}</span>
      </div>
    );
  }

  if (projects.length === 0) {
    return (
      <div className={`${styles.projectSwitcher} ${className ?? ""}`.trim()}>
        <span className={styles.projectSwitcherMeta}>Aucun projet disponible</span>
        {showCreateAction ? (
          <Link className="btn btn-soft" href="/admin/projects/new">
            Creer un projet
          </Link>
        ) : null}
      </div>
    );
  }

  return (
    <div className={`${styles.projectSwitcher} ${className ?? ""}`.trim()}>
      <label htmlFor="projectSwitcher" className={styles.projectSwitcherLabel}>Projet actif</label>
      <select
        id="projectSwitcher"
        className={styles.projectSwitcherSelect}
        value={currentProjectId ?? ""}
        onChange={(event) => {
          const nextProjectId = event.target.value;
          if (!nextProjectId || nextProjectId === currentProjectId) {
            return;
          }

          selectProject(nextProjectId);
        }}
      >
        {projects.map((project) => (
          <option key={project.id} value={project.id}>
            {project.name} ({project.babyCount} bebe{project.babyCount > 1 ? "s" : ""})
          </option>
        ))}
      </select>
      {currentProject ? (
        <span className={styles.projectSwitcherMeta}>
          {currentProject.status === "OPEN"
            ? "Ouvert"
            : currentProject.status === "CLOSED"
              ? "Cloture"
              : currentProject.status === "FINALIZED"
                ? "Finalise"
                : "Brouillon"}
        </span>
      ) : null}
      {showCreateAction ? (
        <Link className="btn btn-soft" href="/admin/projects/new">
          Nouveau projet
        </Link>
      ) : null}
    </div>
  );
}
