import React, { useContext, useEffect, useState } from "react";
import {
  Badge,
  Box,
  Button,
  Text,
  Tooltip,
  useToast,
} from "@chakra-ui/react";
import { useForm} from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useNavigate } from "react-router-dom";
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";
import NormalTable from "../../Components/DataTable/NormalTable";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import { useGetInvestorsQuery } from "../../Services/investor.details.service";
import { TABLE_PAGINATION } from "../../Constants/Paginations";
import { generateSerialNumber } from "../../Constants/Constants";
import { ViewIcon } from "@chakra-ui/icons";

export const notification = yup.object().shape({
  investmentNameEnglish: yup
    .string()
    .required("Investment Name is required"),
  ManualDate: yup
    .date()
    .required("Manual Date is required")
    .typeError("Invalid date format"),
  ManualTime: yup
    .string()
    .required("Manual Time is required")
    .matches(
      /^([01]\d|2[0-3]):?([0-5]\d)$/,
      "Invalid time format, must be in HH:mm"
    ),
  expectedReturn: yup
    .string()
    .required("Expected Return is required")
    .matches(
      /^[0-9]+(\.[0-9]{1,2})?$/,
      "Expected Return must be a valid number with up to 2 decimal places"
    ),
});



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

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

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


  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
  const {
    data: investorDetails,
    isLoading: investorDetailsLoading,
    // error,
  } = useGetInvestorsQuery({ page: currentPage, size: pageSize });
  console.log(investorDetails);


  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: "Investment Name",
      placeHolder: " ",
      name: "investmentNameEnglish",
      type: "text",
      isRequired: true,
      section: "Add Details",
      // value: contact?.phoneNumber || "",
    },
    {
      label: "Manual Date",
      name: "ManualDate",
      placeHolder: " ",
      type: "date",
      isRequired: true,
      section: "Add Details",
      // value: contact?.emailAddress || "",
    },
    {
      label: "Manual Time",
      name: "ManualTime",
      placeHolder: " ",
      type: "time",
      isRequired: true,
      section: "Add Details",
      // value: contact?.websiteUrl || "",
    },
    {
      label: "Expected Return",
      name: "expectedReturn",
      placeHolder: " ",
      type: "text",
      isRequired: true,
      section: "Add Details",
      // 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) => {

    const dataToPass = {
      ...data,
      principal_xid:selectedRadio
    }

    console.log(dataToPass);




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

      setIsLoading(false);
    }
  };


  console.log(selectedRadio);



  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Sr No",
    "Client ID",
    "First Name",
    "Last Name",
    "Country", 
    "Phone Number",
    "E-mail ID",
    "Type", 
    "KYC Status",
    // "Status",
  ];

  const extractedArray = investorDetails?.data?.rows?.map((item, idx) => ({
    id: item?.id,
    "Sr No": (
      <Text
      w={'24px'}
        justifyContent={"left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {/* {item.id} */}
        {generateSerialNumber(idx,currentPage, pageSize )}
        
      </Text>
    ),
    "Client ID": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.clientReference_id}
        </Text>
      </Box> 
    ),
    "First Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.firstName}
        </Text>
      </Box>
    ),
    "Last Name": (
      <Box w={"70px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.lastName}
        </Text>
      </Box>
    ),
    Country: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.country?.countryName}
        </Text>
      </Box>
    ),
    "Phone Number": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.mobileNumber}
        </Text>
      </Box>
    ),
    "E-mail ID": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.emailAddress}
        </Text>
      </Box>
    ),
    "Type": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} >
          <Badge color={"forestGreen.500"}  variant={'ghost'} fontWeight={"700"} px={2} py={0.5}>
            {item?.investor_type?.investorTypeName}
          </Badge>
        </Text>
      </Box>
    ),
    Status: (
    <Box w={"auto"} isTruncated={true}>
      <Badge
        fontWeight={"700"}
        textTransform={"none"}
        colorScheme={item.ioStatus ? "red" : "green"}
        px={2}
        py={0.5}
      >
        {item.ioStatus ? "Ban" : "Unban"}
      </Badge>
    </Box>
    ),
    "KYC Status": (
      <Box w={"auto"} display={'flex'} alignItems={'center'} isTruncated={true}>
        <Text
        as={'span'}
          fontWeight={"700"}
          textTransform={"none"}
          color={item.ioStatus ? "gray.500":item.kycStatus ? "blue.500" : "red.500"}
          px={2}
          py={0.5}
          variant={'solid'}

        >
          {item.KYCStatus ? "Completed" : "Not complete"}
        </Text>
      </Box>
    ),
  }));

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





      <NormalTable
        centered={true}
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        // isLoading={isLoading}
        setSelectedRadio={setSelectedRadio}
        selectedRadio={selectedRadio}
        showRadioButton={true}
      />
      </FormInputMain>
    </Box>
  );
};

export default Notification;
