import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  CircularProgress,
  useTheme,
  useMediaQuery,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { CardContainer } from '@/components/CardContainer';
import { PageWrapper } from '../PageWrapper';
import { PasswordDialog } from './PasswordDialog';
import { useApi } from '@/hooks/useApi';
import { addPassword, changePassword } from '../../api/settingsApi';
import { containsNumber } from '@/utils/regexes/containsNumber';
import { least8Chars } from '@/utils/regexes/least8Chars';
import { hasUpperAndLowerLetter } from '@/utils/regexes/hasUpperAndLowerLetter';
import { containsSymbol } from '@/utils/regexes/containsSymbol';
import { useToast } from '@rkheftan/harmony-ui';
import { useProfile } from '../../hooks/useProfile';

export function PasswordSecurity() {
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'));
  const { t } = useTranslation('setting');

  const [open, setOpen] = useState(false);
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [currentPassword, setCurrentPassword] = useState('');
  const [showValidation, setShowValidation] = useState(false);
  const [changePasswordUI, setChangePasswordUI] = useState(false);

  const hasNumber = containsNumber(password);
  const hasMinLength = least8Chars(password);
  const hasUpperAndLower = hasUpperAndLowerLetter(password);
  const hasSpecialChar = containsSymbol(password);
  const validPassword =
    hasNumber && hasMinLength && hasUpperAndLower && hasSpecialChar;

  const matchPassword = password === confirmPassword;
  const showToast = useToast();

  const { isLoadingProfile, refetchProfile } = useProfile();

  const { loading: isAdding, execute: executeAddPassword } =
    useApi(addPassword);

  const { loading: isChanging, execute: executeChangePassword } =
    useApi(changePassword);

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

      if (!profileData) return;

      if (profileData.success) {
        setChangePasswordUI(profileData.hasPassword || false);
      } else {
        showToast({
          message: profileData.message || t('message.serverError'),
          severity: 'error',
        });
      }
    };

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

  useEffect(() => {
    if (password) {
      setShowValidation(!validPassword);
    } else {
      setShowValidation(false);
    }
  }, [password, validPassword]);

  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  const handlePasswordSubmit = async () => {
    if (!matchPassword) {
      showToast({
        message: t('securityForm.notCompatibility'),
        severity: 'error',
      });
      return;
    }
    if (changePasswordUI) {
      const changeData = await executeChangePassword({
        oldPassword: currentPassword,
        newPassword: password,
      });

      if (!changeData) return;

      if (!changeData.success) {
        showToast({
          message: changeData?.message || t('securityForm.error'),
          severity: 'error',
        });
        return;
      }
    } else {
      const addData = await executeAddPassword({ newPassword: password });

      if (!addData) return;

      if (!addData.success) {
        showToast({
          message: addData?.message || t('securityForm.error'),
          severity: 'error',
        });
        return;
      }
    }
    showToast({
      message: changePasswordUI
        ? t('securityForm.passwordChanged')
        : t('securityForm.passwordAdded'),
      severity: 'success',
    });
    if (!changePasswordUI) {
      setChangePasswordUI(true);
    }
    setOpen(false);
    setPassword('');
    setConfirmPassword('');
    setCurrentPassword('');
  };

  return (
    <PageWrapper>
      <CardContainer
        title={t('securityForm.password')}
        subtitle={t('securityForm.determinePassword')}
        action={
          <Button
            variant="contained"
            onClick={handleOpen}
            size="medium"
            sx={{ flexShrink: 0, flexGrow: 0, width: 'auto' }}
          >
            {changePasswordUI
              ? t('securityForm.changePassword')
              : t('securityForm.addPassword')}
          </Button>
        }
      >
        {isLoadingProfile ? (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              p: 4,
              minHeight: '120px',
            }}
          >
            <CircularProgress />
          </Box>
        ) : (
          <Box sx={{ px: 4, py: 2 }}>
            {changePasswordUI ? (
              <Box>
                <Typography variant="h6">
                  {t('securityForm.activePassword')}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  {t('securityForm.lastChange')}
                </Typography>
              </Box>
            ) : (
              <Typography
                variant="body1"
                color="text.secondary"
                sx={{ textAlign: 'center', py: 4 }}
              >
                {t('securityForm.notDeterminedPassword')}
              </Typography>
            )}

            <PasswordDialog
              open={open}
              fullScreen={fullScreen}
              handleClose={handleClose}
              password={password}
              setPassword={setPassword}
              confirmPassword={confirmPassword}
              setConfirmPassword={setConfirmPassword}
              currentPassword={currentPassword}
              setCurrentPassword={setCurrentPassword}
              showValidation={showValidation}
              validPassword={validPassword}
              matchPassword={matchPassword}
              loading={isAdding || isChanging}
              handleSubmit={handlePasswordSubmit}
              changePassword={changePasswordUI}
              hasMinLength={hasMinLength}
              hasNumber={hasNumber}
              hasUpperAndLower={hasUpperAndLower}
              hasSpecialChar={hasSpecialChar}
            />
          </Box>
        )}
      </CardContainer>
    </PageWrapper>
  );
}
