import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
// import ExpiryModal from "./components/expiry modal";
import Search from '../searchBar';
// import { figma, frankUniversity, linkedin } from "./brands-logo";
import ArrowDown from '../../assets/svg/arrowDown';
// import RenewModal from "./components/renew modal";
import useHeader from "../header/getHeaderDetails";
import OutsideAlerter from "../outsideEventChecker";
import FullPageLoader from "../fullPageLoader";
import deleteCookies from "./deleteCookies";
import { OutletContext } from "..";

const InstructorAccountSwitcher = ({
  generalData,
  onChange,
  affiliateList,
  setSearch,
  defaultAffiliate,
  findText,
}) => {
  // const [expiryFlow, setExpiryFlow] = useState();
  const [switchValue, setSwitchValue] = useState('affiliates');
  const [selectedValue, setSelectedValue] = useState(null);
  const { handleSetDefaultAffiliate, setDefaultAffiliateData } = useHeader();
  const [dropdown, setDropdown] = useState(false);
  const fallbackSelectionAttemptedRef = useRef(false);
  const getCookie = () => {
    const cookies = document.cookie;
    const cookieArray = cookies.split(";");
    let affiliateAccount = null;
    cookieArray?.forEach((cookieValue) => {
      const cookie = cookieValue?.trim();
      if (cookie.startsWith('affiliateAccount=')) {
        affiliateAccount = cookie.substring(
          'affiliateAccount='.length,
          cookie.length,
        );
      }
    });
    return affiliateAccount;
  };
  const setCookie = (id) => {
    const date = new Date();
    date.setDate(date.getDate() + 20);
    const expires = '; expires=' + date.toUTCString();
    const path = '; path=/';
    const domain = window.location.href.includes('localhost')
      ? 'localhost'
      : window.location.hostname?.includes('ca')
        ? '.learngual.ca'
        : '.learngual.com';
    document.cookie =
      'affiliateAccount=' + id + expires + path + '; domain=' + domain;
  };
  const cookieValue = getCookie();
  const usableDefaultAffiliateId = defaultAffiliate?.id ?? null;
  const handleSelection = useCallback(async (item) => {
    const res = await handleSetDefaultAffiliate({
      account: item?.id,
    });
    if (res?.data) {
      setCookie(item?.id);
      window.location.href = '/instructor/dashboard';
    }
  }, [handleSetDefaultAffiliate]);
  const handleSwitch = (value) => {
    if (selectedValue) {
      if (value === 2) {
        if (selectedValue) {
          setCookie(selectedValue?.id);
        }
      } else {
        if (cookieValue) {
          deleteCookies('affiliateAccount');
        }
      }
      window.location.href = '/instructor/dashboard';
    } else {
      if (value === 2) {
        setSwitchValue('affiliates');
      } else {
        setSwitchValue(null);
      }
    }
  };
  const { accountName, planState } = useContext(OutletContext);
  useEffect(() => {
    const activeAffiliateId = cookieValue ?? usableDefaultAffiliateId;
    if (activeAffiliateId) {
      setSwitchValue('affiliates');
      onChange({
        id: activeAffiliateId,
      });
    }
  }, [cookieValue, onChange, usableDefaultAffiliateId]);
  useEffect(() => {
    fallbackSelectionAttemptedRef.current = false;
  }, [generalData?.selectedAccount?.id]);
  useEffect(() => {
    if (fallbackSelectionAttemptedRef.current) return;
    if (cookieValue || usableDefaultAffiliateId || affiliateList?.length === 0) {
      return;
    }

    const fallbackAffiliate = affiliateList?.[0];
    if (!fallbackAffiliate?.id) return;

    fallbackSelectionAttemptedRef.current = true;
    handleSelection(fallbackAffiliate);
  }, [affiliateList, cookieValue, handleSelection, usableDefaultAffiliateId]);
  return (
    <>
      {setDefaultAffiliateData?.loading && (
        <FullPageLoader fixed hasBackground />
      )}
      {/* {expiryFlow === "renew" && (
        <RenewModal
          close={() => setExpiryFlow(null)}
          message="Oops, you have to renew your Instructor plan to continue to
            dashboard."
        />
       )} */}
      {/* {expiryFlow === "expiry" && (
        <ExpiryModal
          btnText="Renew Subscription"
          close={() => setExpiryFlow("renew")}
        >
          <ExpiryModalContent>
            <p className="title danger">
              Your subscription to Learngual Premium has expired
            </p>
            <p className="desc">
              Your students will no longer be able to access your courses after
            </p>
            <p className="sub_title danger">47h - 22m - 59s</p>
          </ExpiryModalContent>
        </ExpiryModal>
       )} */}
      <Container className="instructor_account_switcher">
        <div className="left">
          {switchValue !== 'affiliates' && <p>{accountName}</p>}
          {switchValue === 'affiliates' && (
            <OutsideAlerter handleClick={() => setDropdown(false)}>
              <AffiliatesDropDown>
                {!defaultAffiliate?.metadata?.organization_name ? (
                  <div
                    className="placeholder"
                    onClick={() => setDropdown(!dropdown)}
                  >
                    <p>{findText('Select affiliate')}</p>
                    <ArrowDown />
                  </div>
                ) : (
                  <div
                    className="selected"
                    onClick={() => setDropdown(!dropdown)}
                  >
                    <div>
                      <img src={defaultAffiliate?.profile_photo?.url} alt="" />
                      <p>{defaultAffiliate?.metadata?.organization_name}</p>
                    </div>
                    <ArrowDown />
                  </div>
                )}

                {dropdown && switchValue === 'affiliates' ? (
                  <AffiliatesDropDownWrapper>
                    <div className="search_wrapper">
                      <Search
                        placeholder={findText('Search affiliates')}
                        onSubmit={setSearch}
                      />
                    </div>
                    <ul>
                      {affiliateList?.map((item) => (
                        <li
                          key={item?.id}
                          onClick={() => {
                            handleSelection(item);
                          }}
                        >
                          <div className="left">
                            <img src={item?.image} alt="" />
                            <p>{item?.name}</p>
                          </div>
                          {item.count ? (
                            <span>{findText(item.count)}</span>
                          ) : null}
                        </li>
                      ))}
                    </ul>
                  </AffiliatesDropDownWrapper>
                ) : null}
              </AffiliatesDropDown>
            </OutsideAlerter>
          )}
        </div>
        {
          <div className="btn__wrapper">
            {(planState === 'ACTIVE' || planState === 'GRACE PERIOD') && (
              <button
                className={switchValue !== 'affiliates' ? 'active' : ''}
                onClick={() => handleSwitch(1)}
              >
                <span>{findText('Personal')}</span>
                <span className="circle"></span>
              </button>
            )}
            <button
              className={switchValue === 'affiliates' ? 'active' : ''}
              onClick={() => handleSwitch(2)}
            >
              <span>{findText('Affiliates')}</span>
              <span className="circle"></span>
            </button>
          </div>
        }
      </Container>
    </>
  );
};
const Container = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  width: 100%;
  background: #ffffff;
  border-radius: 25px;
  height: 60px;
  margin-bottom: 16px;

  .left {
    p {
      font-size: 20px;
      font-weight: 600;
      color: #00c2c2;
    }
  }

  .btn__wrapper {
    background: #dfe6e6;
    border-radius: 10px;
    overflow: hidden;
    display: flex;
    button {
      font-size: 14px;
      line-height: 30px;
      font-weight: 700;
      padding: 4px 15px;
      color: #4a4d4d;
      display: flex;
      align-items: center;
      gap: 10px;
      border: none;
      background: transparent;
      cursor: pointer;
      height: 40px;
      span {
        color: #4a4d4d;
      }
      .circle {
        width: 8px;
        height: 8px;
        display: inline-block;
        background-color: #febf10;
        border-radius: 50%;
      }
      &.active {
        background: #00c2c2;

        border-radius: 10px;
        span {
          color: white;
        }
      }
    }
  }
`;
const AffiliatesDropDown = styled.div`
  position: relative;
  .placeholder,
  .selected {
    display: flex;
    align-items: center;
    gap: 25px;
    cursor: pointer;
    svg {
      width: 24px;
      height: 24px;
      path {
        fill: #7c8080;
      }
    }
  }
  .placeholder {
    p {
      color: #7c8080;
      font-size: 16px;
      font-weight: 600;
      opacity: 0.8;
    }
  }
  .selected {
    > div {
      display: flex;
      align-items: center;
      gap: 10px;
      img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
      }
      p {
        color: #00c2c2;
        font-size: 20px;
        font-weight: 600;
        text-transform: capitalize;
      }
    }
  }
`;
const AffiliatesDropDownWrapper = styled.div`
  position: absolute;
  left: 40px;
  border-radius: 15px;
  border: 1px solid #c6cccc;
  background: #fff;
  box-shadow: 0px 10px 20px 0px rgba(139, 139, 139, 0.25);
  width: 351px;
  z-index: 69;
  padding: 20px;
  ul {
    list-style: none;
    height: 150px;
    overflow-y: auto;
    li {
      height: 50px;
      width: 100%;
      display: flex;
      align-items: center;
      border-top: 1px solid #f5f7f7;
      border-bottom: 1px solid #f5f7f7;
      cursor: pointer;

      &:first-child {
        border-top: none;
      }
      &:last-child {
        border-bottom: none;
      }

      > .left {
        display: flex;
        align-items: center;
        gap: 10px;
        flex: 1;
        p {
          color: #4a4d4d;
          font-size: 14px;
          font-weight: 600;
          text-transform: capitalize;
        }
        img {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          object-fit: cover;
        }
      }
      span {
        border-radius: 17px;
        background: #00c2c2;
        min-width: 26px;
        height: 26px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        text-align: center;
        font-size: 12px;
        font-weight: 700;
        padding: 0 10px;
      }
    }
  }
`;
const ExpiryModalContent = styled.div`
  padding-bottom: 30px;
  > .title {
    margin-bottom: 25px;
  }
  > .desc {
    margin: 10px;
  }
`;
export default InstructorAccountSwitcher;
