import {
    Modal,
    ModalOverlay,
    ModalContent,
    ModalHeader,
    ModalFooter,
    ModalBody,
    ModalCloseButton,
    Button,
    Text,
    Box,
    Badge,
    Select,
    HStack,
    Input,
    useToast,
  } from '@chakra-ui/react'
import NormalTable from '../../Components/DataTable/NormalTable'
import { generateSerialNumber } from '../../Constants/Constants';
import { useGetInvestorsQuery } from '../../Services/investor.details.service';
import { useEffect, useState } from 'react';
import { TABLE_PAGINATION } from '../../Constants/Paginations';
import Pagination from '../../Components/Pagination';
import { AddIcon } from '@chakra-ui/icons';
import { useGetFawateerInvestorsQuery } from '../../Services/fawateer.request.service';
import ToastBox from '../../Components/ToastBox';

const SelectInvestorModal = ({ isOpen, setValue, onClose, setId}) => {
  const toast = useToast()
  // =========================== [Use State] ============================= 
  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
 
 // Debounce the search term to avoid making a request on every keystroke
 useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 500); // Adjust delay as needed
    return () => {
      clearTimeout(handler);
    };
  }, [searchTerm]);

  const {
    data: investorDetails,
    isLoading: investorDetailsLoading,
    error,
  } = useGetFawateerInvestorsQuery({
    page: debouncedSearchTerm ? undefined : currentPage,  // Omit pagination for search
    size: debouncedSearchTerm ? undefined : pageSize,     // Omit pagination for search
    search: debouncedSearchTerm,
  },
  {
    skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
  }
);

const [ selectedRadio, setSelectedRadio] = useState([])
const [ selectedInvestor, setSelectorInvestor] = useState(null)

const handleCheckboxChange = (id) => {
  
    setSelectedRadio([id]); 
    const investor = investorDetails?.data?.rows?.find((item)=> item?.id === id)
    setSelectorInvestor(investor) 
    setId(investor?.principal_xid)
    // setValue("investorName",`${selectedInvestor?.firstName} ${selectedInvestor?.lastName}`)
    // setValue("clientId",selectedInvestor?.clientReference_id)
    return
  };

  const handleAdd = () => {
    if(selectedRadio?.length === 0){
    toast({
     render: () => (
       <ToastBox status={'info'} message={"Please Select Investor"} />
     ),
   });
   return
 }
    setValue("investorName",`${selectedInvestor?.firstName} ${selectedInvestor?.lastName}`)
    setValue("clientId",selectedInvestor?.clientReference_id)
    return onClose()
  }



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


    const extractedArray = investorDetails?.data?.rows?.map((item, idx) => ({
        id: item?.id,
        "Sr No": (
          <Text
          w={'24px'}
            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?.firstName}
            </Text>
          </Box>
        ),
        "Last Name": (
          <Box w={"70px"} isTruncated={true}>
            <Text as={"span"} color={"teal.900"}>
              {item?.lastName}
            </Text>
          </Box>
        ),
        "Phone Number": (
          <Box w={"auto"} isTruncated={true}>
            <Text as={"span"} color={"teal.900"}>
              {item?.phoneNumber}
            </Text>
          </Box>
        ),
        "E-mail ID": (
          <Box w={"auto"} isTruncated={true}>
            <Text as={"span"} color={"teal.900"}>
              {item?.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>
        ),
        "Approval Status": (
        <Box w={"auto"} isTruncated={true}>
          <Badge
            fontWeight={"700"}
            textTransform={"none"}
            colorScheme={item.ioStatus ? "red" : "purple"}
            px={2}
            py={0.5}
          >
            Approved
          </Badge>
        </Box>
        ),
      }));


      const handleClose = () => {
        setSelectorInvestor(null)
        handleClose()
      }

  return (
    <Modal
        isCentered
        onClose={onClose}
        isOpen={isOpen}
        motionPreset='scale'
      >
        <ModalOverlay />
      <ModalContent maxW={1200}>
          <ModalHeader fontSize={'md'}>View Investor's</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            {/* <Lorem count={2} /> */}

            <HStack
          display={"flex"}
          justifyContent={"space-between"}
          ps={1}
          pe={1}
          pb={4}
          spacing="24px"
        >
          <Input
            mt={1}
            type="search"
            width={300}
            placeholder="Search..."
            size="sm"
            rounded="sm"
            focusBorderColor="green.500"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
           <Button leftIcon={<AddIcon/>} fontSize={'xs'} colorScheme='forestGreen' size={'sm'} rounded={'sm'}  onClick={handleAdd}>
              Select Investor
            </Button>

          </HStack>


      {investorDetailsLoading?"Loaading":<NormalTable
        // centered={true}
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={investorDetailsLoading}



        handleCheckboxChange={handleCheckboxChange}
        setSelectedRadio={setSelectedRadio}
        selectedRadio={selectedRadio}
        showRadioButton={true}
        radio={true}
      />}

          </ModalBody>
        </ModalContent>
      </Modal>
  )
}

export default SelectInvestorModal