import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { CardContainer } from '@/components/CardContainer';
import { PageWrapper } from '../PageWrapper';
import SocialMediaList from './socialMedia/SocialMediaList';
import SocialMediaMenu from './socialMedia/SocialMediaMenu';
import SocialMediaDialog from './socialMedia/SocialMediaDialog';
import useMediaQuery from '@mui/material/useMediaQuery';
import type { Theme } from '@mui/material/styles';
import { Box, CircularProgress } from '@mui/material';
import { useApi } from '@/hooks/useApi';
import {
  sendEmailCode,
  confirmEmailCode,
  changeEmail,
} from '../../api/settingsApi';
import { type EmailAccount } from '../../types/settingsType';
import { useToast } from '@rkheftan/harmony-ui';
import { useProfile } from '../../hooks/useProfile';

export function SocialMedia() {
  const { t } = useTranslation('setting');

  const [openDialog, setOpenDialog] = useState(false);
  const [emailInput, setEmailInput] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [dialogStep, setDialogStep] = useState<'enterEmail' | 'enterCode'>(
    'enterEmail',
  );
  const [emailList, setEmailList] = useState<EmailAccount[]>([]);
  const [formError, setFormError] = useState<string | null>(null);
  const toast = useToast();

  const { isLoadingProfile, refetchProfile } = useProfile();

  const { loading: isSendingCode, execute: executeSendCode } =
    useApi(sendEmailCode);

  const { loading: isConfirming, execute: executeConfirmCode } =
    useApi(confirmEmailCode);

  const { loading: isChangingEmail, execute: executeChangeEmail } =
    useApi(changeEmail);

  const fullScreen = useMediaQuery((theme: Theme) =>
    theme?.breakpoints.down('sm'),
  );
  const downMd = useMediaQuery((theme: Theme) => theme?.breakpoints.down('md'));
  const computedMaxWidth = (fullScreen ? 'xs' : downMd ? 'sm' : 'md') as
    | 'xs'
    | 'sm'
    | 'md'
    | 'lg'
    | 'xl';

  useEffect(() => {
    const loadProfile = async () => {
      const profileData = await refetchProfile();

      if (!profileData) return;

      if (profileData?.success) {
        const { email } = profileData;

        if (!email) return;

        setEmailList([
          {
            email,
            provider: email.includes('@gmail.') ? 'google' : 'email',
            time: '',
          },
        ]);
      } else {
        toast({
          message: profileData.message,
          severity: 'error',
        });
      }
    };

    loadProfile();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const resetDialog = () => {
    setOpenDialog(false);
    setEmailInput('');
    setVerificationCode('');
    setFormError(null);
    setDialogStep('enterEmail');
  };

  const handleSendCode = async () => {
    if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(emailInput)) {
      setFormError(t('settingForm.emailIsInvalid'));
      return;
    }
    setFormError(null);
    const sendCodeData = await executeSendCode({ email: emailInput });

    if (!sendCodeData) return;

    if (sendCodeData.success) {
      toast({
        message: t('settingForm.verificationCodeSent'),
        severity: 'success',
      });
      setDialogStep('enterCode');

      setTimeout(
        () => {
          resetDialog();
        },
        3 * 60 * 1000,
      );
    }
  };

  const handleConfirmAndChangeEmail = async () => {
    if (verificationCode.length < 4) {
      setFormError(t('settingForm.verificationCodeRequired'));
      return;
    }
    setFormError(null);
    const confirmData = await executeConfirmCode({
      email: emailInput,
      verifyCode: verificationCode,
    });

    if (!confirmData) return;

    if (!confirmData.success || !confirmData.confirm) {
      toast({
        message: confirmData.message || t('settingForm.error'),
        severity: 'error',
      });
      return;
    }

    if (emailList.length >= 1) {
      toast({
        message: t('settingForm.onlyOneAccountAllowed'),
        severity: 'error',
      });
      return;
    }

    const changeEmailData = await executeChangeEmail({ email: emailInput });
    if (!changeEmailData) return;

    if (changeEmailData.success) {
      setEmailList([
        {
          email: emailInput,
          provider: emailInput.includes('@gmail.') ? 'google' : 'email',
          time: t('settingForm.justNow'),
        },
      ]);

      toast({
        message: t('settingForm.emailChangedSuccessfully'),
        severity: 'success',
      });

      resetDialog();
      refetchProfile({ force: true });
    }
  };

  return (
    <PageWrapper>
      <CardContainer
        title={t('settingForm.titleSocial')}
        subtitle={t('settingForm.descriptionSocial')}
        action={
          <SocialMediaMenu t={t} onOpenDialog={() => setOpenDialog(true)} />
        }
      >
        {isLoadingProfile ? (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              p: 4,
              minHeight: '100px',
            }}
          >
            <CircularProgress />
          </Box>
        ) : (
          <SocialMediaList t={t} emailList={emailList} />
        )}
        <SocialMediaDialog
          open={openDialog}
          onClose={resetDialog}
          t={t}
          emailInput={emailInput}
          setEmailInput={setEmailInput}
          verificationCode={verificationCode}
          setVerificationCode={setVerificationCode}
          apiError={formError}
          isLoading={isSendingCode || isConfirming || isChangingEmail}
          dialogStep={dialogStep}
          onSendCode={handleSendCode}
          onConfirmEmail={handleConfirmAndChangeEmail}
          fullScreen={fullScreen}
          computedMaxWidth={computedMaxWidth}
        />
      </CardContainer>
    </PageWrapper>
  );
}
