"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useBillboardForm } from "@/contexts/BillboardFormContext";
import useAxios from "@/hooks/useAxios";
import { useEffect, useState } from "react";

export interface IFeatureFetch {
  title?: string;
  value: boolean;
  _id: string;
}

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

const Step3 = ({ nextStep }: { nextStep: () => void }) => {
  const { formData, updateForm } = useBillboardForm();
  const { request } = useAxios();
  const [features, setFeatures] = useState<IFeatureFetch[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await request<{ features: IFeatureFetch[] }>(
          "GET",
          "/advertising/features"
        );
        setFeatures(response.features);
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);

  const formik = useFormik({
    initialValues: {
      selectedFeatures: formData.selectedFeatures || [],
    },
    validationSchema,
    onSubmit: (values) => {
      updateForm(values);
      nextStep();
    },
    enableReinitialize: true, // اضافه کردن این برای همگام‌سازی initialValues با formData
  });

  const handleSelect = (
    featureId: string,
    value: boolean,
    title: string | undefined
  ) => {
    // به‌روزرسانی ویژگی انتخاب‌شده در Formik
    formik.setFieldValue("selectedFeatures", [
      ...formik.values.selectedFeatures.filter(
        (feature) => feature._id !== featureId
      ),
      { _id: featureId, value, title: title },
    ]);
  };

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex flex-col gap-4 w-full items-center text-sm"
    >
      <h6 className="font-bold text-xl mb-2">ثبت بیلبورد</h6>

      <div className="flex flex-col w-full gap-3">
        {features.map((feature: IFeatureFetch) => {
          const isSelected = formik.values.selectedFeatures.some(
            (featureItem) =>
              featureItem._id === feature._id && featureItem.value === true
          );
          const isDeselected = formik.values.selectedFeatures.some(
            (featureItem) =>
              featureItem._id === feature._id && featureItem.value === false
          );
          return (
            <div
              key={feature._id}
              className="flex justify-between items-center w-full p-4 border-b border-gray-300"
            >
              <span className="text-lg">{feature.title}</span>
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name={`feature-${feature._id}`}
                    value="true"
                    checked={isSelected}
                    onChange={() =>
                      handleSelect(feature._id, true, feature?.title)
                    }
                    className="hidden"
                  />
                  <span>دارد</span>
                  <div
                    className={`w-6 h-6 border-2 rounded-full flex items-center justify-center border-green-500`}
                  >
                    {isSelected && (
                      <svg
                        width="20"
                        height="20"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#01A168"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="M20 6L9 17l-5-5" />
                      </svg>
                    )}
                  </div>
                </label>

                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name={`feature-${feature._id}`}
                    value="false"
                    checked={isDeselected}
                    onChange={() =>
                      handleSelect(feature._id, false, feature?.title)
                    }
                    className="hidden"
                  />
                  <span>ندارد</span>
                  <div
                    className={`w-6 h-6 border-2 rounded-full flex items-center justify-center border-red-500`}
                  >
                    {isDeselected && (
                      <svg
                        width="20"
                        height="20"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#FF0000"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="M20 6L9 17l-5-5" />
                      </svg>
                    )}
                  </div>
                </label>
              </div>
            </div>
          );
        })}
      </div>

      {formik.touched.selectedFeatures &&
        formik.errors.selectedFeatures &&
        typeof formik.errors.selectedFeatures === "string" && (
          <p className="text-red-500">{formik.errors.selectedFeatures}</p>
        )}
      <RoundedButton type="submit" className="w-32 rounded h-9 mt-4">
        ثبت و ادامه
      </RoundedButton>
    </form>
  );
};

export default Step3;
