import { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Box, CircularProgress, Button } from '@mui/material';
import { PageWrapper } from '../PageWrapper';
import { CardContainer } from '@/components/CardContainer';
import SocialMediaList from './socialMedia/SocialMediaList';
import SocialEditForm from './socialMedia/SocialEditForm';
import SocialMediaMenu, {
  type SocialChoice,
} from './socialMedia/SocialMediaMenu';
import { useApi } from '@/hooks/useApi';
import {
  sendEmailCode,
  confirmEmailCode,
  changeEmail,
} from '../../api/settingsApi';
import { type EmailAccount } from '../../types/settingsType';
import { useToast } from '@harmony/kit';
import { useProfile } from '../../hooks/useProfile';

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

  const [isEditing, setIsEditing] = useState(false);
  const [emailInput, setEmailInput] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [email, setEmail] = useState<EmailAccount[]>([]);
  const [emailError, setEmailError] = useState<string | undefined>();
  const [verificationCodeError, setVerificationCodeError] = useState<
    string | undefined
  >();
  const [isCodeSent, setIsCodeSent] = useState(false);
  const [buttonState, setButtonState] = useState<'default' | 'counting'>(
    'default',
  );
  const [isVerified, setIsVerified] = useState(false);

  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 isBusy = useMemo(
    () => isSendingCode || isConfirming || isChangingEmail,
    [isSendingCode, isConfirming, isChangingEmail],
  );

  const isSubmitting = isConfirming || isChangingEmail;
  useEffect(() => {
    const loadProfile = async () => {
      const profileData = await refetchProfile();
      if (!profileData) return;

      if (profileData?.success) {
        const { email } = profileData;
        if (!email) return;
        setEmail([
          {
            email,
            provider: email.includes('@gmail.') ? 'google' : 'email',
            time: '',
          },
        ]);
      } else {
        toast({ message: profileData.message, severity: 'error' });
      }
    };
    void loadProfile();
  }, [refetchProfile, toast]);

  const resetState = () => {
    setEmailInput('');
    setVerificationCode('');
    setEmailError(undefined);
    setVerificationCodeError(undefined);
    setIsCodeSent(false);
    setButtonState('default');
    setIsVerified(false);
  };

  const startEmailEdit = () => {
    resetState();
    setIsEditing(true);
  };

  const buttonLabel = email.length
    ? t('settingForm.editEmailOrGoogle')
    : t('settingForm.addEmailOrSocialButton');

  const validateEmail = (value: string) => {
    if (!value) {
      setEmailError(t('settingForm.thisFieldIsRequired'));
      return false;
    }
    const ok = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value);
    if (!ok) {
      setEmailError(t('settingForm.emailIsInvalid'));
      return false;
    }
    setEmailError(undefined);
    return true;
  };

  const handleSendCode = async () => {
    if (!validateEmail(emailInput)) return;
    const sendCodeData = await executeSendCode({ email: emailInput });
    if (!sendCodeData) return;

    if (sendCodeData.success) {
      toast({
        message: t('settingForm.verificationCodeSent'),
        severity: 'success',
      });
      setIsCodeSent(true);
      setButtonState('counting');
    } else {
      toast({
        message: sendCodeData.message || t('settingForm.error'),
        severity: 'error',
      });
    }
  };

  const handleVerifyClick = async () => {
    if (!verificationCode || verificationCode.length < 4) {
      setVerificationCodeError(t('settingForm.verificationCodeRequired'));
      return;
    }
    setVerificationCodeError(undefined);

    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;
    }

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

    if (changeEmailData.success) {
      setEmail([
        {
          email: emailInput,
          provider: emailInput.includes('@gmail.') ? 'google' : 'email',
          time: t('settingForm.justNow'),
        },
      ]);
      setIsVerified(true);
      toast({
        message: t('settingForm.emailChangedSuccessfully'),
        severity: 'success',
      });
      setIsEditing(false);
      refetchProfile({ force: true });
    } else {
      toast({
        message: changeEmailData.message || t('settingForm.error'),
        severity: 'error',
      });
    }
  };

  const handleBlur = (field: 'email' | 'verificationCode') => {
    if (field === 'email') validateEmail(emailInput);
    if (field === 'verificationCode') {
      if (!verificationCode || verificationCode.length < 4) {
        setVerificationCodeError(t('settingForm.verificationCodeRequired'));
      } else {
        setVerificationCodeError(undefined);
      }
    }
  };

  const onMenuSelect = (choice: SocialChoice) => {
    if (choice === 'email') {
      startEmailEdit();
      return;
    }
    if (choice === 'google') {
      toast({
        message: t('settingForm.googleLinkComingSoon'),
        severity: 'info',
      });
    }
  };

  const rejectButton = () => {
    setIsEditing(false);
    setIsCodeSent(false);
  };

  return (
    <PageWrapper>
      <CardContainer
        title={t('settingForm.titleSocial')}
        subtitle={''}
        highlighted={isEditing}
        action={
          isEditing ? (
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button
                type="button"
                variant="text"
                onClick={rejectButton}
                size="large"
                sx={{
                  color: 'primary.main',
                  textTransform: 'none',
                  width: { xs: '100%', sm: 'auto' },
                }}
              >
                {t('settingForm.rejectButton')}
              </Button>
              <Button
                type="submit"
                form="emailForm"
                size="large"
                variant="outlined"
                sx={{
                  borderRadius: 1,
                  bgcolor: 'primary.main',
                  color: 'primary.contrastText',
                  whiteSpace: 'nowrap',
                  textTransform: 'none',
                }}
                disabled={isSubmitting}
              >
                {isSubmitting ? (
                  <CircularProgress size={24} color="inherit" />
                ) : (
                  t('settingForm.saveButton')
                )}
              </Button>
            </Box>
          ) : (
            <SocialMediaMenu
              t={t}
              onSelect={onMenuSelect}
              buttonLabel={buttonLabel}
            />
          )
        }
      >
        {isLoadingProfile ? (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              p: 4,
              minHeight: '150px',
            }}
          >
            <CircularProgress />
          </Box>
        ) : isEditing ? (
          <Box
            component="form"
            id="emailForm"
            noValidate
            onSubmit={(e) => {
              e.preventDefault();
              e.stopPropagation();
              if (!isBusy) void handleVerifyClick();
            }}
          >
            <SocialEditForm
              email={emailInput}
              setEmail={setEmailInput}
              emails={email.map((e) => ({ address: e.email }))}
              verificationCode={verificationCode}
              setVerificationCode={setVerificationCode}
              isVerified={isVerified}
              isVerifying={isBusy}
              isSendingCode={isSendingCode}
              isCodeSent={isCodeSent}
              setIsCodeSent={setIsCodeSent}
              buttonState={buttonState}
              setButtonState={setButtonState}
              handleSendCode={handleSendCode}
              handleVerifyClick={handleVerifyClick}
              handleBlur={handleBlur}
              emailError={emailError}
              verificationCodeError={verificationCodeError}
            />
          </Box>
        ) : (
          <SocialMediaList emailList={email} />
        )}
      </CardContainer>
    </PageWrapper>
  );
}
