
import React, { useState, useEffect } from 'react';
import {
  Typography,
  Grid,
  Box,
  Paper,
  Link,
  Button,
} from '@mui/material';
import { useFormik } from 'formik';
import FormField from '@/shared/components/form/form-field';
import ActionButtons from '@/shared/components/form/buttons-action';
import FormContainer from '@/layouts/form/form-container';
import { LockReset as LockResetIcon } from '@mui/icons-material';
import { IPassword } from '@/shared/types/password';
import { PasswordFormData } from '../utils/Password-form-fields';
import { passwordValidationSchema, resetValidationSchemas } from '../utils/password-validations';
import PasswordStrengthIndicator from './password-strength-indicator';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';


interface PasswordFormProps {
  onSave: (values: IPassword) => void;
  onClose?: () => void;
  userEmail?: string;
}

type ResetStep = 'code' | 'newPassword';


export default function PasswordForm({ onSave, onClose, userEmail = '' }: PasswordFormProps) {
  const [isResetMode, setIsResetMode] = useState(false);
  const [resetStep, setResetStep] = useState<ResetStep>('code');
  const [timer, setTimer] = useState(120); // 2 minutes en secondes
  const [canResendCode, setCanResendCode] = useState(false);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (isResetMode && resetStep === 'code' && timer > 0) {
      interval = setInterval(() => {
        setTimer((prev) => {
          if (prev <= 1) {
            setCanResendCode(true);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isResetMode, resetStep, timer]);

  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  const passwordFormik = useFormik<IPassword>({
    initialValues: {
      code: '',
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
    validationSchema: passwordValidationSchema,
    onSubmit: (values) => {
      onSave(values);
      if (onClose) onClose();
    },
  });

  const resetFormik = useFormik({
    initialValues: {
      code: '',
      newPassword: '',
      confirmPassword: '',
    },
    validationSchema: resetValidationSchemas[resetStep],
    onSubmit: async (values) => {
      if (resetStep === 'code') {
        setResetStep('newPassword');
      } else {
        setIsResetMode(false);
        setResetStep('code');
        resetFormik.resetForm();
      }
    },
  });

  const handleResendCode = async () => {
    try {
      setTimer(120);
      setCanResendCode(false);
    } catch (error) {
      console.error('Erreur lors du renvoi du code:', error);
    }
  };

  const handleForgotPassword = async () => {
    try {
      setIsResetMode(true);
      setTimer(120);
      setCanResendCode(false);
    } catch (error) {
      console.error('Erreur lors de l\'envoi du code:', error);
    }
  };

  const renderResetForm = () => (
    <FormContainer titre="Réinitialisation du mot de passe" sx={{ alignItems: 'center' }} >
      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
        <Paper sx={{ p: 3, borderRadius: 3, width: '100%', maxWidth: 450,          bgcolor: (theme) => theme.palette.background.neutral }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
            <LockResetIcon sx={{ mr: 2, color: 'primary.main' }} />
            <Typography variant="body2" color="textSecondary">
              {resetStep === 'code' 
                ? "Entrez le code reçu par email"
                : "Définissez votre nouveau mot de passe"}
            </Typography>
          </Box>

          <form onSubmit={resetFormik.handleSubmit}>
            <Grid container spacing={2}>
              {resetStep === 'code' ? (
                <>
                  <Grid item xs={12}>
                    <FormField
                      isReadOnly={false}
                      field={{
                        name: 'code',
                        label: 'Code de confirmation',
                        type: 'text',
                        required: true,
                      }}
                      value={resetFormik.values.code}
                      onChange={(name, value) => resetFormik.setFieldValue(name, value)}
                      error={resetFormik.touched.code ? resetFormik.errors.code : undefined}
                      onBlur={resetFormik.handleBlur}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Box sx={{ 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      alignItems: 'center',
                      mt: 1,
                      mb: 2 
                    }}>
                      <Button
                        variant="text"
                        size="small"
                        onClick={handleResendCode}
                        disabled={timer > 0}
                        sx={{ 
                          color: 'primary.main',
                          textTransform: 'none',
                          minWidth: 'auto',
                          pl: 0
                        }}
                      >
                        Renvoyer
                      </Button>
                      <Typography variant="caption" color="textSecondary">
                        {timer > 0 && `Temps restant: ${formatTime(timer)}`}
                      </Typography>
                    </Box>
                  </Grid>
                </>
              ) : (
                <>
                  <Grid item xs={12}>
                    <FormField
                      isReadOnly={false}
                      field={{
                        name: 'newPassword',
                        label: 'Nouveau mot de passe',
                        type: 'password',
                        required: true,
                        showPassword: true,
                      }}
                      value={resetFormik.values.newPassword}
                      onChange={(name, value) => resetFormik.setFieldValue(name, value)}
                      error={resetFormik.touched.newPassword ? resetFormik.errors.newPassword : undefined}
                      onBlur={resetFormik.handleBlur}
                    />
                    <PasswordStrengthIndicator password={resetFormik.values.newPassword} />
                  </Grid>
                  <Grid item xs={12}>
                    <FormField
                      isReadOnly={false}
                      field={{
                        name: 'confirmPassword',
                        label: 'Confirmez le mot de passe',
                        type: 'password',
                        required: true,
                        showPassword: true,
                      }}
                      value={resetFormik.values.confirmPassword}
                      onChange={(name, value) => resetFormik.setFieldValue(name, value)}
                      error={resetFormik.touched.confirmPassword ? resetFormik.errors.confirmPassword : undefined}
                      onBlur={resetFormik.handleBlur}
                    />
                  </Grid>
                </>
              )}
              <Grid item xs={12}>
                <ActionButtons
                  onSave={resetFormik.submitForm}
                  onCancel={() => {
                    setIsResetMode(false);
                    setResetStep('code');
                    setTimer(0);
                    resetFormik.resetForm();
                  }}
                  mode="edit"
                />
              </Grid>
            </Grid>
          </form>
        </Paper>
      </Box>
    </FormContainer>
  );

  const renderMainForm = () => (
    <FormContainer titre="Réinitialiser Mot de passe"  sx={{ alignItems: 'center' }}>
      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
        <Paper sx={{ p: 3, borderRadius: 3, width: '100%', maxWidth: 450,  bgcolor: (theme) => theme.palette.background.neutral }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
            <LockResetIcon sx={{ mr: 2, color: 'primary.main' }} />
            <Typography variant="body2" color="textSecondary">
              Pour votre sécurité, utilisez un mot de passe fort
            </Typography>
          </Box>

          <form onSubmit={passwordFormik.handleSubmit}>
            <Grid container spacing={2}>
              {PasswordFormData.map((field) => (
                <Grid item xs={12} key={field.name}>
                 
                    <FormField
                    isReadOnly={false}
                    field={{...field, showPassword: true}}
                    value={passwordFormik.values[field.name]}
                    onChange={(name, value) => passwordFormik.setFieldValue(name, value)}
                    error={passwordFormik.touched[field.name] ? passwordFormik.errors[field.name] : undefined}
                    onBlur={passwordFormik.handleBlur}
                  />
                  <ConditionalComponent isValid={field.name === 'newPassword'}>
                    <PasswordStrengthIndicator password={passwordFormik.values.newPassword} />
                  </ConditionalComponent>
                </Grid>
                
              
              ))}

              <Grid item xs={12}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                  <Link
                    component="button"
                    type="button"
                    variant="body2"
                    onClick={handleForgotPassword}
                    sx={{ 
                      color: 'primary.main',
                      textDecoration: 'none',
                      '&:hover': {
                        textDecoration: 'underline',
                      }
                    }}
                  >
                    Mot de passe oublié ?
                  </Link>
                </Box>
                <ActionButtons
                  onSave={passwordFormik.submitForm}
                  onCancel={onClose || (() => {})}
                  mode="edit"
                />
              </Grid>
            </Grid>
          </form>
        </Paper>
      </Box>
    </FormContainer>
  );

  return isResetMode ? renderResetForm() : renderMainForm();
}