import React, { useContext, useEffect, useState } from "react";
import {
  Box,
  Divider,
  FormControl,
  FormLabel,
  Heading,
  Input,
  Select,
  Textarea,
  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 } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import FormInputMain from "../../Components/FormInputMain";
import {
  useGetContactQuery,
  useUpdateContactMutation,
} from "../../Services/contact.service";
import FullscreenLoaders from "../../Components/Loaders/FullscreenLoaders";
import ToastBox from "../../Components/ToastBox";

export const addSponser = yup.object().shape({
  phoneNumber: yup
    .string()
    .required("Phone Number is required"),
    // .matches(
    //   /^\+?[1-9]\d{1,14}$/,
    //   "Phone Number must include a valid ISD code and be in E.164 format"
    // ),
  emailAddress: yup
    .string()
    .required("E-mail ID is required")
    .matches(
      /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
      "Invalid email address"
    ),
  websiteUrl: yup
    .string()
    .required("Website URL is required")
    .matches(
      /^(https?:\/\/)?([\w.-]+)+(:\d+)?(\/[\w.-]*)*\/?$/,
      "Invalid URL format"
    ),
});

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

const Contact = () => {
  const toast = useToast();
  const navigate = useNavigate();
  const [form, setForm] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  // const { sponser, setSponser } = useContext(GlobalStateContext);
  const {
    control,
    reset,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(addSponser),
    // mode: all
  });

  console.log(errors);
  
  const {
    data: contact,
    isLoading: contactLoading,
    error,
  } = useGetContactQuery();
  const [updateContact] = useUpdateContactMutation();

  useEffect(() => {
    if (contact) {
      reset({
        phoneNumber: contact?.data[0]?.phoneNumber,
        emailAddress: contact?.data[0]?.emailAddress,
        websiteUrl: contact?.data[0]?.websiteUrl,
      });
    }
  }, [contact, reset]);

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

  const formFields = [
    {
      label: "Phone Number",
      placeHolder: " ",
      name: "phoneNumber",
      type: "text",
      isRequired: true,
      section:"",
      // value: contact?.phoneNumber || "",
    },
    {
      label: "E-mail ID",
      name: "emailAddress",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section:"",
      // value: contact?.emailAddress || "",
    },
    {
      label: "Website URL",
      name: "websiteUrl",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section:"",
      // value: contact?.websiteUrl || "",
    },
  ];

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

  const onSubmit = async (data) => {
    setIsLoading(true);
    try {
      const res = await updateContact(data);
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setIsLoading(false);
      }
    } catch (error) {
      console.log(error);

      setIsLoading(false);
    }
  };

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={14}>
      <FormInputMain
        groupedFields={groupedFields}
        control={control}
        errors={errors}
        onSubmit={handleSubmit(onSubmit)}
        btnLoading={isLoading}
      />
    </Box>
  );
};

export default Contact;
