"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import { ProjectFormData, useProjectForm } from "@/contexts/ProjectFormContext";
import {
  PROJECT_FIELD_CLASS,
  PROJECT_FIELD_ERROR_CLASS,
} from "@/lib/projectFormStyles";
import { useFormik } from "formik";
import { useMemo } from "react";
import * as Yup from "yup";
import { useTranslation } from "react-i18next";
import GenderSelection from "./step1/GenderSelection";
import { isMaxGreaterThanMin } from "@/lib/rangeValidation";

const Step1 = ({
  nextStep,
}: {
  nextStep: (values: Partial<ProjectFormData>) => void;
}) => {
  const { t } = useTranslation("common");
  const { formData } = useProjectForm();

  const validationSchema = useMemo(
    () =>
      Yup.object({
        projTitle: Yup.string().required(
          t("projects.newProject.validation.titleRequired")
        ),
        description: Yup.string().required(
          t("projects.newProject.validation.descriptionRequired")
        ),
        gender: Yup.string(),
        ageMin: Yup.string(),
        ageMax: Yup.string().test(
          "max-gt-min",
          t("filters.maxMustBeGreater"),
          function (value) {
            return isMaxGreaterThanMin(this.parent.ageMin || "", value || "");
          }
        ),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      projTitle: formData.projTitle || "",
      description: formData.description || "",
      gender: formData.gender || "",
      ageMin: formData.ageMin || "",
      ageMax: formData.ageMax || "",
    },
    enableReinitialize: true,
    validationSchema,
    onSubmit: (values) => {
      nextStep({
        ...values,
        age:
          values.ageMin || values.ageMax
            ? `${values.ageMin || ""}-${values.ageMax || ""}`
            : "",
      });
    },
  });

  const fieldClass = (touched?: boolean, error?: string) =>
    `mt-2 max-w-full text-xs ${
      touched && error ? PROJECT_FIELD_ERROR_CLASS : PROJECT_FIELD_CLASS
    }`;

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex w-full flex-col items-center gap-2 text-sm"
    >
      <h6 className="mb-2 text-xl font-bold">{t("projects.newProject.title")}</h6>

      <RoundedInput
        className={fieldClass(formik.touched.projTitle, formik.errors.projTitle)}
        type="text"
        placeholder={t("projects.newProject.fields.projectTitle")}
        {...formik.getFieldProps("projTitle")}
      />
      {formik.touched.projTitle && formik.errors.projTitle && (
        <p className="text-red-500">{formik.errors.projTitle}</p>
      )}

      <textarea
        className={`mt-2 h-28 w-full rounded-3xl bg-secondary-light p-4 font-medium dark:bg-secondary-dark ${
          formik.touched.description && formik.errors.description
            ? PROJECT_FIELD_ERROR_CLASS
            : PROJECT_FIELD_CLASS
        }`}
        placeholder={t("projects.newProject.fields.description")}
        {...formik.getFieldProps("description")}
      />
      {formik.touched.description && formik.errors.description && (
        <p className="text-red-500">{formik.errors.description}</p>
      )}

      <hr className="my-2 w-full" />
      <p className="text-xs font-semibold text-neutral-500">
        {t("projects.newProject.fields.genderOptional")}
      </p>
      <GenderSelection
        selectedGender={formik.values.gender}
        setSelectedGender={(gender) => formik.setFieldValue("gender", gender)}
        setFieldValue={formik.setFieldValue}
      />

      <hr className="my-2 w-full" />
      <p className="text-xs font-semibold text-neutral-500">
        {t("projects.newProject.fields.ageRangeOptional")}
      </p>
      <div className="grid w-full grid-cols-2 gap-2">
        <RoundedInput
          type="number"
          className={`text-xs ${PROJECT_FIELD_CLASS}`}
          placeholder={t("projects.newProject.fields.ageMin")}
          {...formik.getFieldProps("ageMin")}
        />
        <RoundedInput
          type="number"
          className={`text-xs ${PROJECT_FIELD_CLASS}`}
          placeholder={t("projects.newProject.fields.ageMax")}
          {...formik.getFieldProps("ageMax")}
        />
      </div>
      {formik.touched.ageMax && formik.errors.ageMax && (
        <p className="text-red-500">{formik.errors.ageMax}</p>
      )}

      <RoundedButton type="submit" variant="primary" className="mt-4 px-8 py-2">
        {t("projects.newProject.submitContinue")}
      </RoundedButton>
    </form>
  );
};

export default Step1;
