"use client"
import FormTitle from "@/components/ui/form-title";
import useResponsive from "@/hooks/useResponsive";
import { useRouter } from "next/navigation";
import { LAYOUT_SETTING, OPTION_LOGIN, PaymentMethod, POSITION_PROFILE } from "@/lib/appConstant";
import { getAuthInfo, getIsMobileApp } from "@/lib/redux/features/auth";
import { getAccountType, getIsCancelAccount, getLayoutSettingAll, getLayoutViewPage, getPageMargin, getPasswordPolicy, getShowSubscriptionStatus, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import StorageHelper from "@/lib/storeHelper";
import { STORAGE_KEYS } from "@/types/common";
import Button from "@mui/material/Button";
import { Col, Row } from "antd";
import { useTranslations } from "next-intl";
import React, { useEffect } from "react";
import { makeStyles } from "tss-react/mui";
import UserAccountSettingForm from "./user-account-setting-form";
import { setShowBanner } from "@/lib/redux/features/layout";
import UserCardForm from "./user-card";
import UserCancelAccount from "./user-cancel-account";
import { getIsAcountLoading, getUserInfo, loadAccount } from "@/lib/redux/features/account";
import LoadingSpinner from "../ui/loading-spinner";
import AppLoading from "../ui/loading";
import AppButton from "../ui/button/app-button";

type MakeStylesType = {
  below768: boolean;
  pageMargin: any;
};


const useStyle = makeStyles<MakeStylesType>()((theme, { below768, pageMargin }) => {
  return (
    {
      root: {
        width: '100%',
        backgroundColor: 'white',
        // minHeight: below768 ? '72.5vh' : '70.6vh'
        // marginBottom: '2rem'
      },
      titleUserProfile: {
        marginBottom: below768 ? '0px' : '2rem',
        marginTop: below768 ? '0px' : '2rem'
      },
      fullWidth: {
        width: '100%'
      },
      button: {
        backgroundColor: '#00B27B',
        width: '100%'
      },
      titleUserCard: {
        margin: '1rem 0'
      },
      grid: {
        marginLeft: below768 ? 20 : pageMargin.left,
        marginRight: below768 ? 20 : pageMargin.right,
        width: 'auto'
      }
    }
  );
});
const AppProfilePage = () => {
  const dispatch = useAppDispatch();
  const router = useRouter();
  // const below1024 = useMedia('(max-width: 1024px)');
  const t = useTranslations("");
  const { below768, getBelow768 } = useResponsive();


  const layoutViewPage = useAppSelector(getLayoutViewPage);
  const layoutSettingAll = useAppSelector(getLayoutSettingAll);
  const strictPassword = useAppSelector(getPasswordPolicy);
  const accountDetail = useAppSelector(getUserInfo);
  const accountType = useAppSelector(getAccountType);
  const viewSettings = useAppSelector(getViewSettings);
  const allowCancelAccount = useAppSelector(getIsCancelAccount);
  const isMobileApp = useAppSelector(getIsMobileApp);
  const pageMargin = useAppSelector(getPageMargin);
  const authUser = useAppSelector(getAuthInfo);
  const isLoading = useAppSelector(getIsAcountLoading);

  const showSubscriptionStatus = useAppSelector(getShowSubscriptionStatus);
  const servicePath = StorageHelper.getSessionItem(STORAGE_KEYS.servicePath) || '';
  const currentDomain = StorageHelper.getSessionItem(STORAGE_KEYS.domain) || '';
  const userStore = !servicePath || servicePath === '' ? currentDomain : servicePath;
  const isAuthen = StorageHelper.getLocalObject(userStore);
  const isToken = StorageHelper.getCookie(userStore);
  const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
  
  const below1024 = getBelow768(1024);
  const { classes } = useStyle({ below768, pageMargin });

  // useEffect(() => {
  //   if ((!isToken && !isAuthen) || isMobileApp) {
  //     router.push(`${servicePath ? '/'+servicePath : ''}/`);
  //   }
  // }, [isAuthen, isToken, isMobileApp]);

  const getJustifyContent = (positionProfileUser: number) => {
    switch (positionProfileUser) {
      case POSITION_PROFILE.LEFT:
        return 'start';
      case POSITION_PROFILE.MIDDLE:
        return 'center';
      case POSITION_PROFILE.RIGHT:
        return 'end';
      default:
        return 'start';
    }
  };
  
  useEffect(() => {
      if (authUser && authUser.id) {
        console.log('authUser: ', authUser.id);
        dispatch(loadAccount());
      }
  }, [authUser]);

  if (isMegreLayout) {
    return (
      <div className={classes.root} >
        <Row justify={getJustifyContent(layoutSettingAll.positionProfileUser)} className={classes.grid}>
          {
            isLoading && <AppLoading/>
          }
          <Col span={below1024 ? 24 : 12}>
            <Row gutter={1} >
              <Col span={24}>
                <h4 className={classes.titleUserProfile}>
                  {t('title.userProfile')}
                </h4>
              </Col>
              <Col span={24}>
                {
                  accountDetail &&
                  <UserAccountSettingForm accountDetail={accountDetail} />
                }
              </Col>
              {
                (showSubscriptionStatus && viewSettings.paymentGateway !== PaymentMethod.GAKKEN_ID)
                  ? <Col span={24} className={classes.titleUserCard}>
                    <FormTitle>
                      {t('title.userCard')}
                    </FormTitle>
                    <UserCardForm />
                  </Col>
                  : null
              }
              {
                accountType === OPTION_LOGIN.GAKKEN_ID &&
                <>
                  <Col span={24} style={{ margin: '10px 0px' }}><hr/></Col>
                  <Col span={24} className={classes.fullWidth}>
                    {/* <FormTitle>
                      <TranslateMessage id="title.gakkenProfile" />
                    </FormTitle> */}
                    <AppButton
                      className="w-full mt-[10px] mb-[10px]"
                      // variant='contained'
                      color="megre"
                      type='button'
                      onClick={() => { window.open(`${process.env.NEXT_PUBLIC_GAKKEN_LINK}/my-page`)}}
                    >
                      {t('title.gotoGakkenPage')}
                    </AppButton>
                  </Col>
                </>
              }
              {
                allowCancelAccount &&
                <Col span={24}>
                  {/* <h4>
                    <TranslateMessage id="title.cancelAccount" />
                  </h4> */}
                  <UserCancelAccount isMegreLayout={isMegreLayout} />
                </Col>
              }
            </Row>
          </Col>
        </Row>
      </div>
    );
  } else {
    return (
      <div className="card">
        <div className="card-body" style={{ width: below768 ? '100%' : '50%' }}>
          <FormTitle>
            {t('title.userProfile')}
          </FormTitle>
          {
            isLoading && <AppLoading/>
          }
          {
            accountDetail &&
            <UserAccountSettingForm accountDetail={accountDetail}/>
          }
          {
            accountType === OPTION_LOGIN.GAKKEN_ID &&
            <React.Fragment>
              <FormTitle className="mt-5">
                {t('title.gakkenProfile')}
              </FormTitle>
              <AppButton
                className='btn btn-info mr-1'
                type='button'
                onClick={() => { window.open(`${process.env.NEXT_PUBLIC_GAKKEN_LINK}/my-page`) }}
                style={{ marginTop: '10px', marginBottom: '10px' }}
              >
                {t('title.gotoGakkenPage')}
              </AppButton>
            </React.Fragment>
          }
          {
            (showSubscriptionStatus && viewSettings.paymentGateway !== PaymentMethod.GAKKEN_ID)
              ? <React.Fragment>
                <FormTitle>
                  {t('title.userCard')}
                </FormTitle>
                <UserCardForm />
              </React.Fragment>
              : null
          }
          {
            allowCancelAccount &&
            <React.Fragment>
              <FormTitle>
                {t('title.cancelAccount')}
              </FormTitle>
              <UserCancelAccount />
            </React.Fragment>
          }
        </div>
      </div>
    );
  }
}

export default AppProfilePage;
