"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { ProjectFormData, useProjectForm } from "@/contexts/ProjectFormContext";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import LocationSelector from "./step1/LocationSelector";

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

  const validationSchema = useMemo(
    () =>
      Yup.object({
        cityId: Yup.string().required(
          t("projects.newProject.validation.cityRequired")
        ),
        stateId: Yup.string().required(
          t("projects.newProject.validation.stateRequired")
        ),
        markerCoordinate: Yup.array()
          .of(Yup.number())
          .min(2, t("projects.newProject.validation.mapRequired")),
        neighborhood: Yup.string(),
        address: Yup.string(),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      cityId: formData.cityId || "",
      stateId: formData.stateId || "",
      markerCoordinate: formData.markerCoordinate || [],
      neighborhood: formData.neighborhood || "",
      address: formData.address || "",
    },
    enableReinitialize: true,
    validationSchema,
    onSubmit: (values) => {
      nextStep(values);
    },
  });

  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>
      <p className="mb-2 text-center text-xs text-neutral-500">
        {t("projects.newProject.locationStepHint")}
      </p>
      <LocationSelector formik={formik} />
      <RoundedButton type="submit" variant="primary" className="mt-4 px-8 py-2">
        {t("projects.newProject.submitContinue")}
      </RoundedButton>
    </form>
  );
};

export default Step2;
