"use client";

import { useEffect, useMemo, useState } from "react";
import Modal from "@/components/elements/Modal";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import ExpertiseSelector from "./step1/ExpertiseSelector";
import AppearanceColorSelect from "@/components/models/AppearanceColorSelect";
import useAxios from "@/hooks/useAxios";
import { IExpertise } from "@/types/types";
import { ProjectRoleForm } from "@/contexts/ProjectFormContext";
import {
  EYE_COLOR_OPTIONS,
  HAIR_COLOR_OPTIONS,
} from "@/lib/appearanceOptions";
import { toggleBtnClass } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import {
  PROJECT_FIELD_CLASS,
  PROJECT_TOGGLE_BTN,
  PROJECT_TOGGLE_ROW,
} from "@/lib/projectFormStyles";
import { useTranslation } from "react-i18next";
import { isModelExpertise } from "@/lib/isModelExpertise";
import { validateMinMaxPairs } from "@/lib/rangeValidation";

type RoleModalProps = {
  isOpen: boolean;
  onClose: () => void;
  onSave: (role: ProjectRoleForm) => void;
};

function RangeField({
  label,
  min,
  max,
  onMinChange,
  onMaxChange,
  minPlaceholder,
  maxPlaceholder,
}: {
  label: string;
  min: string;
  max: string;
  onMinChange: (v: string) => void;
  onMaxChange: (v: string) => void;
  minPlaceholder: string;
  maxPlaceholder: string;
}) {
  return (
    <div className="w-full">
      <p className="mb-1 text-center text-xs font-semibold text-neutral-500">
        {label}
      </p>
      <div className={cn(PROJECT_TOGGLE_ROW, "mt-0 grid-cols-2")}>
        <RoundedInput
          type="number"
          className={cn("text-xs", PROJECT_FIELD_CLASS)}
          placeholder={minPlaceholder}
          value={min}
          onChange={(e) => onMinChange(e.target.value)}
        />
        <RoundedInput
          type="number"
          className={cn("text-xs", PROJECT_FIELD_CLASS)}
          placeholder={maxPlaceholder}
          value={max}
          onChange={(e) => onMaxChange(e.target.value)}
        />
      </div>
    </div>
  );
}

export default function RoleModal({ isOpen, onClose, onSave }: RoleModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [expertiseList, setExpertiseList] = useState<IExpertise[] | null>(null);
  const [expertise, setExpertise] = useState("");
  const [subExpertise, setSubExpertise] = useState<string[]>([]);
  const [numberOfPerson, setNumberOfPerson] = useState("");
  const [heightMin, setHeightMin] = useState("");
  const [heightMax, setHeightMax] = useState("");
  const [weightMin, setWeightMin] = useState("");
  const [weightMax, setWeightMax] = useState("");
  const [sizeMin, setSizeMin] = useState("");
  const [sizeMax, setSizeMax] = useState("");
  const [eyeColor, setEyeColor] = useState("");
  const [hairColor, setHairColor] = useState("");
  const [portfolioRequired, setPortfolioRequired] = useState(false);
  const [error, setError] = useState("");

  const isModel = useMemo(() => isModelExpertise(expertise), [expertise]);

  useEffect(() => {
    if (!isOpen) return;
    const fetchData = async () => {
      try {
        const response = await request<{ expertises: IExpertise[] }>(
          "GET",
          "/expertise"
        );
        setExpertiseList(response?.expertises || null);
      } catch (err) {
        console.log(err);
      }
    };
    void fetchData();
  }, [isOpen, request]);

  useEffect(() => {
    if (!isOpen) {
      setExpertise("");
      setSubExpertise([]);
      setNumberOfPerson("");
      setHeightMin("");
      setHeightMax("");
      setWeightMin("");
      setWeightMax("");
      setSizeMin("");
      setSizeMax("");
      setEyeColor("");
      setHairColor("");
      setPortfolioRequired(false);
      setError("");
    }
  }, [isOpen]);

  const handleSave = () => {
    if (!expertise) {
      setError(t("projects.newProject.validation.expertiseRequired"));
      return;
    }
    const subList =
      expertiseList?.find((item) => item.expertise === expertise)
        ?.sub_expertise ?? [];
    if (subList.length > 0 && !subExpertise.length) {
      setError(t("projects.newProject.validation.subExpertiseRequired"));
      return;
    }
    if (!numberOfPerson || Number(numberOfPerson) < 1) {
      setError(t("projects.newProject.validation.headcountRequired"));
      return;
    }
    if (
      validateMinMaxPairs([
        { min: heightMin, max: heightMax },
        { min: weightMin, max: weightMax },
        { min: sizeMin, max: sizeMax },
      ])
    ) {
      setError(t("filters.maxMustBeGreater"));
      return;
    }
    const roleId =
      typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
        ? crypto.randomUUID()
        : `role-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
    onSave({
      id: roleId,
      expertise,
      subExpertise,
      numberOfPerson,
      heightMin,
      heightMax,
      weightMin,
      weightMax,
      sizeMin,
      sizeMax,
      eyeColor,
      hairColor,
      portfolioRequired,
    });
    onClose();
  };

  const dummyFormik = {
    values: { expertise, subExpertise },
    setFieldValue: (field: string, value: string | string[]) => {
      if (field === "expertise") setExpertise(String(value));
      if (field === "subExpertise") setSubExpertise(value as string[]);
    },
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      height="fit"
      elevated
      panelClassName="max-h-[90vh] overflow-y-auto"
    >
      <div className="flex w-full flex-col items-center gap-3 pb-4 text-sm">
        <h3 className="text-base font-bold">
          {t("projects.newProject.selectRole")}
        </h3>

        <ExpertiseSelector
          expertiseList={expertiseList}
          expertise={expertise}
          setExpertise={setExpertise}
          subExpertise={subExpertise}
          setSubExpertise={setSubExpertise}
          setFieldValue={dummyFormik.setFieldValue}
          formik={dummyFormik}
        />

        {isModel ? (
          <div className="mt-2 w-full space-y-3 border-t border-neutral-200 pt-3 dark:border-neutral-700">
            <RangeField
              label={t("filters.heightCm")}
              min={heightMin}
              max={heightMax}
              onMinChange={setHeightMin}
              onMaxChange={setHeightMax}
              minPlaceholder={t("filters.min")}
              maxPlaceholder={t("filters.max")}
            />
            <RangeField
              label={t("filters.weightKg")}
              min={weightMin}
              max={weightMax}
              onMinChange={setWeightMin}
              onMaxChange={setWeightMax}
              minPlaceholder={t("filters.min")}
              maxPlaceholder={t("filters.max")}
            />
            <RangeField
              label={t("filters.size")}
              min={sizeMin}
              max={sizeMax}
              onMinChange={setSizeMin}
              onMaxChange={setSizeMax}
              minPlaceholder={t("filters.min")}
              maxPlaceholder={t("filters.max")}
            />
            <AppearanceColorSelect
              label={t("filters.hairColor")}
              placeholder={t("filters.selectHairColor")}
              value={hairColor}
              options={HAIR_COLOR_OPTIONS}
              onChange={setHairColor}
              className="max-w-full"
            />
            <AppearanceColorSelect
              label={t("filters.eyeColor")}
              placeholder={t("filters.selectEyeColor")}
              value={eyeColor}
              options={EYE_COLOR_OPTIONS}
              onChange={setEyeColor}
              className="max-w-full"
            />
          </div>
        ) : null}

        <RoundedInput
          type="number"
          min={1}
          className={cn("mt-2 w-full text-xs", PROJECT_FIELD_CLASS)}
          placeholder={t("projects.newProject.fields.headcountRequired")}
          value={numberOfPerson}
          onChange={(e) => setNumberOfPerson(e.target.value)}
        />

        <div className="mt-2 w-full">
          <p className="mb-2 text-center text-xs font-semibold text-neutral-500">
            {t("projects.newProject.fields.portfolioRequired")}
          </p>
          <div className={cn(PROJECT_TOGGLE_ROW, "mt-0 grid-cols-2")}>
            <RoundedButton
              type="button"
              className={cn(
                toggleBtnClass(portfolioRequired),
                PROJECT_TOGGLE_BTN,
                "!max-w-none"
              )}
              onClick={() => setPortfolioRequired(true)}
            >
              {t("projects.newProject.portfolioNeeded")}
            </RoundedButton>
            <RoundedButton
              type="button"
              className={cn(
                toggleBtnClass(!portfolioRequired),
                PROJECT_TOGGLE_BTN,
                "!max-w-none"
              )}
              onClick={() => setPortfolioRequired(false)}
            >
              {t("projects.newProject.portfolioNotNeeded")}
            </RoundedButton>
          </div>
        </div>

        {error ? <p className="text-red-500">{error}</p> : null}

        <RoundedButton
          type="button"
          variant="primary"
          className="mt-2 px-8 py-2"
          onClick={handleSave}
        >
          {t("projects.newProject.registerRole")}
        </RoundedButton>
      </div>
    </Modal>
  );
}
