import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import { Box, Button, Text, useToast } from "@chakra-ui/react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useNavigate, useParams } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import FormInputMain from "../../../Components/FormInputMain";
import ToastBox from "../../../Components/ToastBox";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import SwitchButton from "../../../Components/SwitchButton";
import DummyComponent from "../../../Components/DummyComponent";
import {
  useCreateSponserMutation,
  useGetSponserByIdQuery,
  useUpdateSponserMutation,
} from "../../../Services/io.service";
import { ArrowBackIcon } from "@chakra-ui/icons";
// ======================= [validation] =========================

export const addSponser = yup.object().shape({
  sponsorName: yup
  .string()
  .required("Sponsor Name is required")
  .min(3, "Sponsor Name must be at least 3 characters long")
  .max(50, "Sponsor Name cannot exceed 50 characters")
  .matches(/^[^\d]+$/, "Sponsor Name cannot contain numbers"),

  sponsorNameArabic: yup
    .string()
    .required("Sponser name in arabic is required"),
  email: yup.string().email("Invalid email address").notRequired(),
  //   .test("emailValidity", "Email address is invalid", async function (value) {
  //     if (!value) {
  //         return true; // Allow if the field is empty
  //     }
  //     return await checkEmailValidity(value);
  // }),
});

// ==================== [debounce] ========================

export function debounce(func, delay) {
  let debounceTimer;
  return function (...args) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => func.apply(this, args), delay);
  };
}

const AddSponser = () => {
  const toast = useToast();
  const params = useParams();
  const navigate = useNavigate();
  const id = params?.id;

  // =====================[useState]=======================

  const [isLoadingBtn, setIsLoadingBtn] = useState(false);
  const [alert, setAlert] = useState(false);
  const [form, setForm] = useState();
  const [isSwitchOn, setIsSwitchOn] = useState(true);

  const [createSponser] = useCreateSponserMutation();
  const [updateSponser] = useUpdateSponserMutation();

  // Fetch sponsor data only if id exists
  const {
    data: sponserByIdData,
    error,
    isLoading,
  } = useGetSponserByIdQuery(id, { skip: !id });

  // ======================== [validators] ===========================

  const {
    control,
    watch,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: yupResolver(addSponser),
  });

  // ========================== [useEffect] ================================

  useEffect(() => {
    if (sponserByIdData?.data) {
      reset({
        sponsorName: sponserByIdData?.data?.sponsorName,
        sponsorNameArabic: sponserByIdData?.data?.sponsorNameArabic,
        email: sponserByIdData?.data?.email,
      });
      setIsSwitchOn(sponserByIdData?.data?.isActive);
      console.log(sponserByIdData?.data?.isActive);
    }
  }, [sponserByIdData, reset]);

  // console.log(isSwitchOn);

  if (false) {
    return <FullscreenLoaders />;
  }

  // ============================ [API]===============================

  const handleConfirm = async () => {
    setIsLoadingBtn(true);
    const id = params?.id;
    if (id) {
      try {
        const formData = {
          ...form,
          isActive: isSwitchOn,
        };
        // Remove email field if it's an empty string
        if (formData.email === "") {
          delete formData.email;
        }
        await updateSponser({ data: formData, id }).then((response) => {
          if (response?.data?.statusCode) {
            toast({
              render: () => <ToastBox message={response?.data?.message} />,
            });

            setIsLoadingBtn(false);
            setAlert(false);
            navigate("/sponser");
          } else if (response?.error?.status === 400) {
            toast({
              render: () => (
                <ToastBox
                  message={response?.error?.data?.message}
                  status={"error"}
                />
              ),
            });

            setIsLoadingBtn(false);
            setAlert(false);
          }
        });
      } catch (error) {
        console.log(error);
        setIsLoadingBtn(false);
        navigate("/sponser");
      }
    } else {
      try {
        const formData = {
          ...form,
          isActive: isSwitchOn,
        };
        await createSponser(formData).then((response) => {
          console.log(response);
          if (response?.data?.statusCode === 201) {
            toast({
              render: () => <ToastBox message={response?.data?.message} />,
            });

            setIsLoadingBtn(false);
            navigate("/sponser");
          } else if (response?.error?.status === 400) {
            toast({
              render: () => (
                <ToastBox
                  message={response?.error?.data?.message}
                  status={"error"}
                />
              ),
            });

            setIsLoadingBtn(false);
            setAlert(false);
          }
        });
      } catch (error) {
        console.log(error);

        setIsLoadingBtn(false);
        navigate("/sponser");
      }
    }
  };

  // ====================== [Update  Form Object] =========================

  const formFields = [
    {
      label: "Sponsor name (English)",
      placeHolder: " ",
      name: "sponsorName",
      type: "text",
      isRequired: true,
      section: "",
      maxLength: 50,
      helperText: `Maximum length should be 50 characters. You have entered ${
        watch()?.sponsorName?.length || 0
      } characters.`,
    },
    {
      label: "Sponsor name (Arabic)",
      name: "sponsorNameArabic",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "",
      arabic: true,
      right: true,
      maxLength: 55,
      helperText: `Maximum length should be 55 characters. You have entered ${
        watch()?.sponsorNameArabic?.length || 0
      } characters.`,
    },
    {
      label: "Email address",
      name: "email",
      placeHolder: " ",
      type: "email",
      // isRequired: true,
      section: "",
    },
  ];

  // ==================== [Create Form Object] =======================

  const formEditFields = [
    {
      label: "Sponsor name",
      placeHolder: " ",
      name: "sponsorName",
      type: "text",
      isRequired: true,
      section: "",
      maxLength: 55,
      helperText: `Maximum length should be 55 characters. You have entered ${
        watch()?.sponsorName?.length || 0
      } characters.`,
    },
    {
      label: "Sponsor name (Arabic)",
      name: "sponsorNameArabic",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "",
      arabic: true,
      maxLength: 55,
      helperText: `Maximum length should be 55 characters. You have entered ${
        watch()?.sponsorNameArabic?.length || 0
      } characters.`,
    },
    {
      label: "Email address",
      name: "email",
      placeHolder: " ",
      type: "email",
      // isRequired: true,
      section: "",
    },
  ];

  // ====================== [Group Create Fields] =========================

  const groupedEditFields = formEditFields.reduce((groups, field) => {
    const { section } = field;
    if (!groups[section]) {
      groups[section] = [];
    }
    groups[section].push(field);
    return groups;
  }, {});

  // ====================== [Group Update Fields] =======================

  const groupedFields = formFields.reduce((groups, field) => {
    const { section } = field;
    if (!groups[section]) {
      groups[section] = [];
    }
    groups[section].push(field);
    return groups;
  }, {});

  // ==================== [On Submit] ========================

  const onSubmit = async (data) => {
    if (Object.keys(errors).length === 0) {
      setForm(data);
      setAlert(true);
    }
  };

  return isLoading ? (
    <FullscreenLoaders />
  ) : (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={14}>
      {/* =====================  [Switch Button] ======================== */}
      <Box display={"flex"} justifyContent={"space-between"} alignItems={"center"} mt={5} px={4}>
        <Text fontSize={"sm"} mb={0}  onClick={() => navigate(-1)} cursor={"pointer"}>
          <ArrowBackIcon fontSize={"xl"} me={2} />{params?.id ? "Edit Details" : "Add Details"}
        </Text>
        <SwitchButton isSwitchOn={isSwitchOn} setIsSwitchOn={setIsSwitchOn} />
      </Box>

      {/* ====================== [Form Input] ====================== */}

      <FormInputMain
        groupedFields={params?.id ? groupedEditFields : groupedFields}
        control={control}
        errors={errors}
        onSubmit={handleSubmit(onSubmit)}
        submitTitle={params?.id ? "Update" : "Submit"}
      ></FormInputMain>

      {/* ======================= [Modal] =========================== */}

      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleConfirm}
        message={id ? "Are you sure you want to update this?" : "Are you sure you want to add this?"}
        isLoading={isLoadingBtn}
      />

      {/* <DummyComponent /> */}
    </Box>
  );
};

export default AddSponser;
