import {
  Badge,
  Box,
  Divider,
  Icon,
  Tab,
  TabList,
  TabPanel,
  TabPanels,
  Tabs,
  Text,
} from "@chakra-ui/react";
import { useNavigate, useParams } from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import { useForm } from "react-hook-form"; // assuming react-hook-form is used
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import { ArrowBackIcon } from "@chakra-ui/icons";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import FormInputView from "../../../Components/FormInputView";
import ViewInvestorDetails from "./ViewInvestorDetails";
import { LuWallet } from "react-icons/lu";
import Transaction from "./Transaction";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import { useGetInvestorsDetailsByIdQuery } from "../../../Services/investor.details.service";
import BankDetails from "./BankDetails";
import Kyc from "./Kyc";

const ProfileView = () => {
  const navigate = useNavigate();
  const params = useParams();
  const {
    InvestorDetails,
    setViewInvestor,
    setTransaction,
    InvestorWallet,
    setInvestorWallet,
  } = useContext(GlobalStateContext);
  const { reset } = useForm(); // assuming react-hook-form

  const id = params?.id;

  const { data, isLoading, errors, refetch} = useGetInvestorsDetailsByIdQuery(id, {
    skip: !id,
  });


   // Use useEffect to refetch data when the component mounts
 useEffect(() => {
  refetch();
}, [refetch]);

  const foundObject = data?.data; 

  useEffect(() => {
    setViewInvestor(data?.data?.portfolio);
    setTransaction(data?.data?.transaction);
    setInvestorWallet(data?.data.wallet); 
  }, [data]);

  const formFields = [
    {
      label: "Client ID",
      value: foundObject?.clientReference_id,
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "First Name",
      value: foundObject?.firstName,
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },

    {
      label: "Last Name",
      value: foundObject?.lastName,
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "E-mail ID",
      value: foundObject?.emailAddress,
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "Phone Number",
      value: foundObject?.mobileNumber,
      type: "tel",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "Country",
      value: foundObject?.country ? foundObject?.country : "---",
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "Investment type",
      value: foundObject?.investorTypeName,
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    // {
    //   label: "Investor limit",
    //   value: foundObject?.investorLimit,
    //   type: "text",
    //   isRequired: true,
    //   section: "Personal Details",
    //   width: "32%",
    // },
    {
      label: "KYC Status",
      value: foundObject?.KYCStatus ? "Completed" : "Not complete",
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "Status",
      value: foundObject?.userStatus ? "Unban" : "Ban",
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "Default language",
      value: foundObject?.defaultLanguage_xid === 1 ? "English" : "Arabic",
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    {
      label: "App Notification",
      value: foundObject?.IsAppNotificationEnabled === true ? "Yes" : "No",
      type: "text",
      isRequired: true,
      section: "Personal Details",
      width: "32%",
    },
    // {
    //   label: "Account Name",
    //   value: foundObject?.accountName,
    //   type: "text",
    //   isRequired: true,
    //   section: "Bank Details",
    //   width: "32%",
    // },
    // {
    //   label: "Account No",
    //   value: foundObject?.accountNumber,
    //   type: "text",
    //   isRequired: true,
    //   section: "Bank Details",
    //   width: "32%",
    // },
    // {
    //   label: "IBAN",
    //   value: foundObject?.IBANnumber,
    //   type: "text",
    //   isRequired: true,
    //   section: "Bank Details",
    //   width: "32%",
    // },
    // {
    //   label: "SWIFT Code",
    //   value: foundObject?.swiftCode,
    //   type: "text",
    //   isRequired: true,
    //   section: "Bank Details",
    //   width: "32%",
    // },
    // {
    //   label: "Bank Name",
    //   value: foundObject?.bankName,
    //   type: "text",
    //   isRequired: true,
    //   section: "Bank Details",
    //   width: "32%",
    // },
    // {
    //   label: "Bank Address",
    //   value: foundObject?.bankAddress,
    //   type: "text",
    //   isRequired: true,
    //   section: "Bank Details",
    //   width: "32%",
    // },
  ];

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

  return isLoading ? (
    <FullscreenLoaders />
  ) : (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={14}>
      <Box
        pt={2}
        pb={2}
        pe={4}
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
      >
        <Text ps={2} as={"span"} fontSize={"sm"}>
          View Investor Details
        </Text>

        <Box
          display={"flex"}
          p={2}
          alignItems={"center"}
          gap={5}
          height={"auto"}
          width={"auto"}
          fontSize={"sm"}
          as="span"
          boxShadow={"lg"}
          rounded={"md"}
          bg={"#EAF2EC"}
        >
          <Icon color={"#004717"} boxSize={8} as={LuWallet} />

          <Box display={"flex"} flexDirection={"column"} as="span">
            <Text as={"span"} color={"#6F6F6F"} fontSize={"10px"}>
              Amount
            </Text>
            <Box
              as="span"
              gap={2}
              alignItems={"center"}
              fontSize={"sm"}
              display={"flex"}
            >
              <Text fontWeight={500} as={"span"}>
                {parseFloat(InvestorWallet?.WalletBalance_InUSD || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </Text>
              <Badge display={"flex"} alignItems={"center"}>
                {InvestorWallet?.currencyCode_USD}
              </Badge>
            </Box>
          </Box>

          <Box display={"flex"} flexDirection={"column"} as="span">
            <Text as={"span"} color={"#6F6F6F"} fontSize={"10px"}>
              Investor Currency
            </Text>
            <Box
              as="span"
              gap={2}
              alignItems={"center"}
              fontSize={"sm"}
              display={"flex"}
            >
              <Text fontWeight={500} as={"span"}>
                {parseFloat(InvestorWallet?.WalletBalance_InInvCur || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </Text>
              <Badge display={"flex"} alignItems={"center"}>
                {InvestorWallet?.currencyCode_InCur}
              </Badge>
            </Box>
          </Box>
        </Box>
      </Box>
      <Tabs mt={0}>
        <Box>
          <TabList alignItems={"center"}>
            <ArrowBackIcon
              onClick={() => navigate(-1)}
              cursor={"pointer"}
              me={3}
            />
            <Tab
              fontSize={"sm"}
              _selected={{
                color: "#004118",
                borderBottom: "2px solid #38a169",
              }}
            >
              View Details
            </Tab>
            <Tab
              // isDisabled={true}
              fontSize={"sm"}
              _selected={{
                color: "#004118",
                borderBottom: "2px solid #38a169",
              }}
            >
              Portfolio
            </Tab>
            <Tab
              // isDisabled={true}
              fontSize={"sm"}
              _selected={{
                color: "#004118",
                borderBottom: "2px solid #38a169",
              }}
            >
              Transaction
            </Tab>
            <Tab
              // isDisabled={true}
              fontSize={"sm"}
              _selected={{
                color: "#004118",
                borderBottom: "2px solid #38a169",
              }}
            >
              KYC
            </Tab>
          </TabList>
        </Box>
        <TabPanels>
          <TabPanel>
            <FormInputView width={"32%"} groupedFields={groupedFields} />
            <Divider/>
            <BankDetails />
          </TabPanel>
          <TabPanel>
            <ViewInvestorDetails />
          </TabPanel>
          <TabPanel>
            <Transaction />
          </TabPanel>
          <TabPanel>
            <Kyc />
          </TabPanel>
        </TabPanels>
      </Tabs>
    </Box>
  );
};

export default ProfileView;
