import Image from "next/image";
import styles from "@/features/predictions/styles/predictions.module.css";
import type { FieldRendererProps } from "./types";

const OPTION_ICONS: Record<string, string> = {
  fille: "/images/pictos/choix-fille.png",
  garcon: "/images/pictos/choix-garcon.png",
  garçon: "/images/pictos/choix-garcon.png",
};

export function SelectFieldRenderer({ card, draftValues, disabled, setText }: FieldRendererProps) {
  const hasOptionIcons = card.options.some(
    (option) => OPTION_ICONS[option.value.toLowerCase()] != null,
  );

  return (
    <div className={styles.fieldGrid}>
      {card.fields.map((field) => {
        const draft = draftValues.find((value) => value.fieldId === field.id);

        if (hasOptionIcons) {
          return (
            <div key={field.id} className={styles.optionIconsRow}>
              {card.options.map((option) => {
                const iconSrc = OPTION_ICONS[option.value.toLowerCase()];
                const isSelected = draft?.valueText === option.value;
                return (
                  <button
                    key={option.id}
                    type="button"
                    className={`${styles.optionIconBtn} ${isSelected ? styles.optionIconBtnActive : ""}`}
                    disabled={disabled}
                    onClick={() => setText(field.id, option.value)}
                  >
                    {iconSrc ? (
                      <Image src={iconSrc} alt={option.label} width={44} height={44} />
                    ) : null}
                    <span>{option.label}</span>
                  </button>
                );
              })}
            </div>
          );
        }

        return (
          <div key={field.id} className="field">
            <label htmlFor={`field-${field.id}`}>
              {field.label}
              {field.points > 0 ? ` (${field.points} pts)` : ""}
            </label>
            <select
              id={`field-${field.id}`}
              value={draft?.valueText ?? ""}
              disabled={disabled}
              onChange={(event) => setText(field.id, event.target.value)}
            >
              <option value="">Choisir...</option>
              {card.options.map((option) => (
                <option key={option.id} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        );
      })}
    </div>
  );
}
