"use client";

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

const validationSchema = Yup.object({
  services: Yup.array().min(1, "حداقل یک خدمت یا کالا انتخاب کنید"),
});

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

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

  // لیست سرویس‌ها از فرمیک مقداردهی می‌شود
  const services = formik.values.services;

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

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

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex flex-col gap-2 w-full items-center text-sm"
    >
      <h6 className="font-bold text-xl mb-2">ثبت بیلبورد</h6>
      <div className="gap-4 min-h-96">
        {services.map((service) => (
          <ServiceItem
            onDelete={handleDeleteService}
            key={crypto.randomUUID()}
            service={service}
          />
        ))}
      </div>
      {/* {formik.touched.services && formik.errors.services && (
        <p className="text-red-500 text-xs">{formik.errors.services}</p>
      )} */}
      <hr />
      <div className="flex gap-4 mb-4 ">
        <RoundedButton type="submit" className="w-32 rounded h-9">
          ثبت و ادامه
        </RoundedButton>
        <RoundedButton
          onClick={() => setModalOpen(true)}
          className="!text-[#0066FF] !border-[#0066FF] w-32 h-9"
          type="button"
        >
          افزودن
        </RoundedButton>
      </div>
      {isModalOpen && (
        <AddServiceModal
          onClose={() => setModalOpen(false)}
          onAdd={handleAddService}
          isModalOpen={isModalOpen}
        />
      )}
    </form>
  );
};

export default Step2;
