import { Box, Button } from "@chakra-ui/react";
import React, { useContext, useEffect } from "react";

import { useNavigate, useParams } from "react-router-dom";
import { useForm } from "react-hook-form";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import DataTable from "../../../Components/DataTable/DataTable";
import FormInputView from "../../../Components/FormInputView";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import { useGetIOByIdQuery } from "../../../Services/io.service";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { formatDate } from "../../Master/Sponser/Sponsers";
import { formatCurrency } from "../../../Components/CurrencyInput";
import { removeTrailingZeros } from "../../../Constants/Constants";

const schema = yup.object().shape({
  investmentNameEnglish: yup
    .string()
    .required("IO name in English is required")
    .min(3, "IO name in English must be at least 3 characters long")
    .max(50, "IO name in English must be at most 50 characters long"),

  investmentNameArabic: yup
    .string()
    .required("IO name in Arabic is required")
    .min(3, "IO name in Arabic must be at least 3 characters long")
    .max(50, "IO name in Arabic must be at most 50 characters long"),

  descriptionEnglish: yup
    .string()
    .required("Description in English is required")
    .min(10, "Description in English must be at least 10 characters long")
    .max(500, "Description in English must be at most 500 characters long"),

  descriptionArabic: yup
    .string()
    .required("Description in Arabic is required")
    .min(10, "Description in Arabic must be at least 10 characters long")
    .max(500, "Description in Arabic must be at most 500 characters long"),

  goalAmount: yup
    .number()
    .required("Goal amount is required")
    .positive("Goal amount must be a positive number")
    .min(1, "Goal amount must be at least 1"),

  closingDate: yup
    .date()
    .required("Closing date is required")
    .min(new Date(), "Closing date cannot be in the past"),

  holdingPeriod: yup
    .number()
    .required("Holding period is required")
    .positive("Holding period must be a positive number"),

  // minInvestmentAmount: yup
  //   .number()
  //   .required("Minimum investment is required")
  //   .positive("Minimum investment must be a positive number")
  //   .min(1, "Minimum investment must be at least 1"),

  ISIN: yup.string(),

  InvestmentDetails: yup.string(),

  comment: yup.string(),

  expectedReturn: yup
    .number()
    .required("Expected return is required")
    .positive("Expected return must be a positive number")
    .min(0.01, "Expected return must be at least 0.01"),
});
  
const ViewIOdetails = () => {
  const navigate = useNavigate();
  const params = useParams();
  const id = params?.id;
  const { IODetails, setIODetails } = useContext(GlobalStateContext);

  const {
    data: IObyID,
    isLoading: IObyIDisLoading,
    error: IObyIDerror,
  } = useGetIOByIdQuery(id, { skip: !id });

  // ======================[ Validator filter ]
  const {
    control,
    reset,
    setValue,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });
  useEffect(() => {
    setIODetails({
      ...IObyID?.data,
    });
    if (IObyID?.data) {
      reset({
        investmentNameEnglish: IObyID?.data?.investmentNameEnglish,
        investmentNameArabic: IObyID?.data?.investmentNameArabic,
        descriptionEnglish: IObyID?.data?.descriptionEnglish,
        descriptionArabic: IObyID?.data?.descriptionArabic,
        goalAmount: removeTrailingZeros(IObyID?.data?.goalAmount),
        closingDate: IObyID?.data?.closingDate,
        holdingPeriod: IObyID?.dpata?.holdingPeriod,
        ISIN: IObyID?.data?.ISIN,
        comment: IObyID?.data?.comment,
        expectedReturn: IObyID?.data?.expectedReturn,
        investmentType_xid: IObyID?.data?.investmentType_xid,
        InvestmentDetails: IObyID?.data?.InvestmentDetails,
        minInvestmentAmount: IObyID?.data?.minInvestmentAmount,
      });
    }
  }, [id, IObyID]);

  const minInvestmentById = IObyID?.data?.minInvestmentAmt?.map(({minInvestmentAmt, country, currencyCode, id})=>{
    return{
      id:id,
      country: country?.countryName,
      value: removeTrailingZeros(minInvestmentAmt),
      logo: country?.flagIcon,
      curr: currencyCode,
    }
  })


  console.log();
  

  //=======================[ Editor ]
  const formFields = [
    {
      label: "IO Name",
      value: IObyID?.data?.investmentNameEnglish
        ? IObyID?.data?.investmentNameEnglish
        : "---",
      name: "investmentNameEnglish",
      type: "text",
      section: " ",
      width: "49%",
      isRequired: true,
    },
    {
      label: "IO Name (Arabic)",
      name: "investmentNameArabic",
      type: "text",
      value: IObyID?.data?.investmentNameArabic
        ? IObyID?.data?.investmentNameArabic
        : "---",
      isRequired: true,
      arabic: true,
      section: " ",
      width: "49%",
    },
    {
      label: "Description",
      name: "descriptionEnglish",
      value: IObyID?.data?.descriptionEnglish
        ? IObyID?.data?.descriptionEnglish
        : "---",
      type: "textarea",
      isRequired: true,
      section: " ",
      width: "49%",
    },
    {
      label: "Description (Arabic)",
      name: "descriptionArabic", 
      value: IObyID?.data?.descriptionArabic
        ? IObyID?.data?.descriptionArabic
        : "---",
      type: "textarea",
      isRequired: true,
      arabic: true,
      section: " ",
      width: "49%",
    },

    {
      label: "Holding Period",
      name: "holdingPeriod",
      value: IObyID?.data?.holdingPeriod ? IObyID?.data?.holdingPeriod : "---",
      type: "text",
      isRequired: true,
      placeHolder: "1Y",
      section: " ",
      width: "49%",
    },
    {
      label: "Holding Period (Arabic)",
      name: "holdingPeriodArabic",
      value: IObyID?.data?.holdingPeriodArabic ? IObyID?.data?.holdingPeriodArabic : "---",
      type: "text",
      isRequired: true,
      arabic: true,
      placeHolder: "1Y",
      section: " ",
      width: "49%",
    },



    {
      label: "Expected Return",
      placeHolder: "$00.00",
      name: "expectedReturn",
      type: "number",
      isRequired: true,
      value: IObyID?.data?.expectedReturn
        ? IObyID?.data?.expectedReturn
        : "---",
      section: " ",
      width: "49%",
    }, 

    {
      label: "Expected Return (Arabic)",
      name: "expectedReturnArabic",
      placeHolder: "$00.00",
      type: "number",
      isRequired: true,
      arabic: true,
      value: IObyID?.data?.expectedReturnArabic
        ? IObyID?.data?.expectedReturnArabic
        : "---",
      section: " ",
      width: "49%",
    }, 




    {
      label: "Investment Type",
      placeHolder: "Select option",
      value: IObyID?.data?.investmentType?.investmentTypeName
        ? IObyID?.data?.investmentType?.investmentTypeName
        : "---",
      name: "investmentType_xid",
      type: "select",
      isRequired: true,
      section: " ",
      width: "32.3%",
    },
    {
      label: "Sponsor Name",
      placeHolder: "Select option",
      name: "sponsor_xid",
      type: "select",
      // options: sponserNameOption,
      value: IObyID?.data?.sponsor?.sponsorName ? IObyID?.data?.sponsor?.sponsorName : "---",
      section: " ",
      isRequired: true,
      width: "32.3%",
    },

    {
      label: "Goal Amount",
      placeHolder: "$00.00",
      value: IObyID?.data?.goalAmount?parseFloat(IObyID?.data?.goalAmount||0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : "---",
      
      name: "goalAmount",
      type: "number",
      isRequired: true,
      arabic:true,
      section: " ",
      width: "32.3%",
    },
    {
      label: "Closing Date",
      name: "closingDate",
      type: "date",
      isRequired: true,
      value: IObyID?.data?.closingDate
        ? formatDate(IObyID?.data?.closingDate)
        : "---",
      section: " ",
      width: "32.3%",
    },
    {
      label: "ISIN",
      placeHolder: "$00.00",
      name: "ISIN",
      value: IObyID?.data?.ISIN ? IObyID?.data?.ISIN : "---",
      type: "number",
      section: " ",
      width: "32.3%",
      align:"right"
    },
    {
      label: "Investment Details",
      placeHolder: "",
      name: "InvestmentDetails",
      value: IObyID?.data?.InvestmentDetails
        ? IObyID?.data?.InvestmentDetails
        : "---",
      type: "text",
      section: " ",
      width: "32.3%",
    },
    
    {
      label: "Minimum Investment",
      placeHolder: "Enter comment here",
      name: "table",
      type: "table",
      section: " ",
      width: "100%",
      isRequired: true,
      value: minInvestmentById,
    },

    {
      label: "Comment",
      placeHolder: "Enter comment here",
      name: "comment",
      type: "textarea",
      value: IObyID?.data?.comment ? IObyID?.data?.comment : "---",
      section: " ",
      width: "100%",
    },
  ];

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

  if (!IObyID?.data) {
    return <FullscreenLoaders height={'70vh'} />;
  }

  return (
    <Box position={"relative"}>
      <Button
        position={"absolute"}
        top={"-62px"}
        right={0}
        onClick={() => navigate(`/create-io/${params?.id}`)}
        ps={4}
        pe={4}
        colorScheme="forestGreen"
        rounded={"sm"}
        size={"xs"}
      >
        Edit IO
      </Button>
      <FormInputView  groupedFields={groupedFields} />{" "}
    </Box>
  );
};

export default ViewIOdetails;
