import { useMemo, useState } from "react";
import Image from "next/image";
import type { PredictionTileController } from "@/features/predictions/hooks/use-prediction-tile-controller";
import { predictionTitleFont } from "@/features/predictions/components/tiles/prediction-tile-fonts";
import styles from "@/features/predictions/styles/predictions.module.css";
import type { PredictionCard } from "@/types/predictions";

type LegacyNamesPredictionTileProps = {
  card: PredictionCard;
  controller: PredictionTileController;
  disabled?: boolean;
  showSubmitButton?: boolean;
};

export function LegacyNamesPredictionTile({
  card,
  controller,
  disabled,
  showSubmitButton,
}: LegacyNamesPredictionTileProps) {
  const nameFields = card.fields.slice(0, 6);
  const [modalOpen, setModalOpen] = useState(false);
  const [localNames, setLocalNames] = useState<string[]>([]);

  const enteredNames = useMemo(
    () =>
      nameFields
        .map((field) => controller.draftValues.find((value) => value.fieldId === field.id)?.valueText ?? "")
        .map((value) => value.trim())
        .filter((value) => value.length > 0),
    [controller.draftValues, nameFields],
  );

  const summary = enteredNames.length > 0 ? enteredNames.join(", ") : "Entrez vos idées...";
  const totalPoints = nameFields.reduce((sum, field) => sum + field.points, 0);

  if (nameFields.length === 0) {
    return null;
  }

  const openModal = () => {
    setLocalNames(
      nameFields.map(
        (field) => controller.draftValues.find((value) => value.fieldId === field.id)?.valueText ?? "",
      ),
    );
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
  };

  const saveNames = () => {
    nameFields.forEach((field, index) => {
      controller.setText(field.id, localNames[index]?.trim() ?? "");
    });
    setModalOpen(false);
  };

  return (
    <>
      <article className={`${styles.tile} ${styles.legacyMiniTile} ${styles.legacyNamesTile}`}>
        <div className={styles.legacyMiniHeader}>
          <h3 className={`${predictionTitleFont.className} ${styles.legacyNamesTitleCentered}`}>Prénom(s) ?</h3>
          <Image
            src="/images/pictos/bebe-fille.png"
            alt=""
            width={2154}
            height={1984}
            className={styles.legacyNamesTopBaby}
          />
        </div>

        <button
          type="button"
          className={`${styles.namesLauncher} ${enteredNames.length > 0 ? styles.namesLauncherFilled : ""}`}
          onClick={openModal}
        >
          <span>{summary}</span>
        </button>

        <div className={styles.legacyNamesHelper}>
          Gagnez :<br />
          {nameFields[0] ? <>{nameFields[0].points} Points le principal&nbsp;!</> : null}
          {nameFields[1] ? <><br />{nameFields[1].points} points un secondaire&nbsp;!</> : null}
        </div>

        <Image
          src="/images/pictos/jouet-bebe.png"
          alt=""
          width={44}
          height={44}
          className={styles.legacyNamesToy}
        />

        <div className={styles.legacyMiniFooter}>
          {showSubmitButton ? (
            <button
              className={`btn btn-primary ${styles.legacyMiniButton}`}
              onClick={() => void controller.submit()}
              disabled={controller.saving || disabled}
              type="button"
            >
              {controller.saving ? "Validation..." : "Valider mon pronostic"}
            </button>
          ) : null}
          {controller.dirty ? (
            <span className={styles.dirty}>Modifications non enregistrees</span>
          ) : null}
          {controller.successMessage ? <p className={styles.success}>{controller.successMessage}</p> : null}
          {controller.errorMessage ? <p className={styles.error}>{controller.errorMessage}</p> : null}
        </div>
      </article>

      {modalOpen ? (
        <div className={styles.predictionModalBackdrop} onClick={closeModal}>
          <div className={styles.predictionModal} onClick={(event) => event.stopPropagation()}>
            <div className={styles.predictionModalHeader}>
              <div>
                <h3 className={predictionTitleFont.className}>Prenom(s)</h3>
                <p>Ajoutez jusqu&apos;a {nameFields.length} prenoms. Le premier reste obligatoire.</p>
              </div>
              <button
                type="button"
                className={styles.predictionModalClose}
                aria-label="Fermer"
                onClick={closeModal}
              >
                ×
              </button>
            </div>

            <div className={styles.predictionModalGrid}>
              {nameFields.map((field, index) => (
                <label key={field.id} className={styles.predictionModalField}>
                  <span>Prenom {index + 1}</span>
                  <input
                    type="text"
                    value={localNames[index] ?? ""}
                    placeholder={index === 0 ? "Ex: Laura" : "Autre idee..."}
                    onChange={(event) => {
                      const nextValues = [...localNames];
                      nextValues[index] = event.target.value;
                      setLocalNames(nextValues);
                    }}
                  />
                </label>
              ))}
            </div>

            <div className={styles.predictionModalActions}>
              <button type="button" className="btn btn-soft" onClick={closeModal}>
                Annuler
              </button>
              <button type="button" className="btn btn-primary" onClick={saveNames}>
                Valider mes prenoms
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}