"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useBillboardForm } from "@/contexts/BillboardFormContext";
import { useMemo, useState } from "react";
import { Service } from "@/types/types";
import ServiceItem from "@/components/main/Services/ServiceItem";
import AddServiceModal from "@/components/main/Services/AddServiceModal";
import { useTranslation } from "react-i18next";

const Step2 = ({ nextStep }: { nextStep: () => void }) => {
  const { t } = useTranslation("common");
  const { formData, updateForm } = useBillboardForm();
  const [isModalOpen, setModalOpen] = useState(false);

  const validationSchema = useMemo(
    () =>
      Yup.object({
        services: Yup.array().min(1, t("billboards.form.validation.minServices")),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      services: formData.services || [],
    },
    validationSchema,
    onSubmit: (values) => {
      updateForm(values);
      nextStep();
    },
  });

  const services = formik.values.services;

  const handleAddService = (newService: Service) => {
    formik.setFieldValue("services", [...services, newService]);
  };

  const handleDeleteService = (id: string) => {
    formik.setFieldValue(
      "services",
      services.filter((service) => service.id !== id)
    );
  };

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex flex-col gap-2 w-full items-center text-sm pb-28"
    >
      <h6 className="font-bold text-xl mb-2">{t("billboards.createTitle")}</h6>
      <div className="gap-4 min-h-96 w-full">
        {services.map((service) => (
          <ServiceItem
            onDelete={handleDeleteService}
            key={service.id}
            service={service}
          />
        ))}
      </div>
      <hr className="w-full" />
      <div className="sticky bottom-[calc(5.5rem+env(safe-area-inset-bottom))] z-20 flex w-full justify-center gap-4 bg-background/95 py-3 backdrop-blur-sm">
        <RoundedButton type="submit" variant="primary" className="h-9 w-32">
          {t("billboards.submitContinue")}
        </RoundedButton>
        <RoundedButton
          onClick={() => setModalOpen(true)}
          className="!text-[#0066FF] !border-[#0066FF] w-32 h-9"
          type="button"
        >
          {t("billboards.add")}
        </RoundedButton>
      </div>
      {isModalOpen && (
        <AddServiceModal
          onClose={() => setModalOpen(false)}
          onAdd={handleAddService}
          isModalOpen={isModalOpen}
        />
      )}
    </form>
  );
};

export default Step2;
