"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, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

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

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

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

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

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

  const handleSelect = (
    featureId: string,
    value: boolean,
    title: string | undefined
  ) => {
    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">{t("billboards.createTitle")}</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>{t("billboards.form.has")}</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>{t("billboards.form.hasNot")}</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" variant="primary" className="mt-4 h-9 w-32">
        {t("billboards.submitContinue")}
      </RoundedButton>
    </form>
  );
};

export default Step3;
