import React, { useCallback, useEffect, useState } from "react";

import { useDispatch, useSelector } from "react-redux";

import Spotlight from "@enact/spotlight";

import TButtonTab from "../../../components/TButtonTab/TButtonTab";
import TPopUp from "../../../components/TPopUp/TPopUp";
import { $L } from "../../../utils/helperMethods";
import css from "./CheckOutTerms.module.less";

export default function CheckOutTerms() {
  const dispatch = useDispatch();
  const termsData = useSelector((state) => state.home.termsData);
  const introTermsData = termsData?.data?.terms.filter(
    (item) => item.trmsTpCd === "MST00401" || item.trmsTpCd === "MST00402"
  );
  const [selectedTab, setSelectedTab] = useState(0);
  const [currentTerms, setCurrentTerms] = useState(null);

  const handleTermsClick = useCallback(({ index }) => {
    setSelectedTab(index);
    if (index === 0) {
      setCurrentTerms(
        introTermsData.filter((item) => item.trmsTpCd === "MST00401")[0]
      );
    } else {
      setCurrentTerms(
        introTermsData.filter((item) => item.trmsTpCd === "MST00402")[0]
      );
    }
  }, []);

  useEffect(() => {
    handleTermsClick(0);
    Spotlight.focus("tab-0");
  }, [introTermsData, dispatch]);

  const description =
    $L(`Check out more LIVE SHOWS and enjoy Shopping via your TV \n at Shop Time’s special prices by agreeing to the LG TV
  Shopping Terms and Conditions`);

  const checkOut = [$L("Terms of Purchase"), $L("Privacy Policy")];
  return (
    <TPopUp
      kind="checkoutTermsPopup"
      open={true}
      hasButton
      hasText
      text={description}
      button1Text={$L("AGREE")}
      button2Text={$L("DO NOT AGREE")}
    >
      <TButtonTab
        className={css.tTab}
        contents={checkOut}
        onItemClick={handleTermsClick}
        selectedIndex={selectedTab && selectedTab}
      />
      <div
        className={css.termsInfo}
        dangerouslySetInnerHTML={{
          __html: currentTerms && currentTerms.trmsCntt,
        }}
      />
    </TPopUp>
  );
}
