'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  Typography,
  Box,
  Link, 
  Button,
  Stack,
  Container,
  Paper,
} from '@mui/material';
import { useFormik } from 'formik';
import { LockReset } from '@mui/icons-material';
import { useSnackbar } from 'notistack';
import FormField from '@/shared/components/form/form-field';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { ForgotPasswordFormData } from '../utils/forgot-password-form-fields';
import { validationSchemas } from '../utils/validation-schemas';
import { SUCCESS_MESSAGES, ERROR_MESSAGES, BUTTON_TEXTS, TIMER_DURATION, INFO_MESSAGES } from '../utils/constants';
import { useDriverStore } from '@/shared/api/stores/driverStore';

export default function DriverForgotPasswordVerifyView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { enqueueSnackbar } = useSnackbar();
  const [timer, setTimer] = useState(TIMER_DURATION);
  const [email, setEmail] = useState('');
  const [operationHash, setOperationHash] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [isLoadingOtp, setIsLoadingOtp] = useState(true);

  const confirmOtp = useDriverStore((state) => state.confirmOtp);
  const sendResetPassword = useDriverStore((state) => state.sendResetPassword);
  const getOtpByUsername = useDriverStore((state) => state.getOtpByUsername);
  useEffect(() => {
    const storedEmail = localStorage.getItem('EmailForResetPassword');
    const storedHash = localStorage.getItem('operationHash');

    if (storedEmail && storedHash) {
      setEmail(storedEmail);
      setOperationHash(storedHash);
      // Récupérer les informations OTP pour calculer l'expiration
      const fetchOtpInfo = async () => {
        try {
          const otpData = await getOtpByUsername(storedEmail);
          if (otpData && otpData.generationDate) {
            // Calculer l'expiration (5 minutes après la génération)
            const generationDate = new Date(otpData.generationDate);
            const expirationDate = new Date(generationDate.getTime() + 5 * 60 * 1000); // +5 minutes
            const now = new Date();
            
            // Calculer le temps restant en secondes
            const timeRemaining = Math.max(0, Math.floor((expirationDate.getTime() - now.getTime()) / 1000));
            setTimer(timeRemaining);
          }
        } catch (error) {
          console.error('Erreur lors de la récupération des informations OTP:', error);
          // En cas d'erreur, utiliser la durée par défaut
          setTimer(TIMER_DURATION);
        } finally {
          setIsLoadingOtp(false);
        }
      };
      
      fetchOtpInfo();
    } else {
      setErrorMessage("Impossible de vérifier le code : informations manquantes.");
      setIsLoadingOtp(false);
    }
  }, [getOtpByUsername]);

  useEffect(() => {
    const interval = setInterval(() => {
      setTimer((prev) => (prev <= 1 ? 0 : prev - 1));
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  const formik = useFormik({
    initialValues: { code: '' },
    validationSchema: validationSchemas.code,
    onSubmit: async (values) => {
      try {
        const success = await confirmOtp({
          email,
          confirmationCode: values.code,
          operationHash,
        });

        if (success) {
          enqueueSnackbar(SUCCESS_MESSAGES.codeVerified, { variant: 'success' });
          router.push('/auth/driver/forgot-password/reset');
        } else {
          enqueueSnackbar(ERROR_MESSAGES.default, { variant: 'error' });
        }
      } catch (error: any) {
        enqueueSnackbar(error?.message || ERROR_MESSAGES.default, { variant: 'error' });
      }
    },
  });

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

  const handleResendCode = async () => {
    try {
      const response = await sendResetPassword({ email });
      if (response?.operationHash) {
        localStorage.setItem("operationHash", response.operationHash);
        setOperationHash(response.operationHash);
        
        // Récupérer les nouvelles informations OTP pour calculer l'expiration
        try {
          const otpData = await getOtpByUsername(email);
          if (otpData && otpData.generationDate) {
            // Calculer l'expiration (5 minutes après la génération)
            const generationDate = new Date(otpData.generationDate);
            const expirationDate = new Date(generationDate.getTime() + 5 * 60 * 1000); // +5 minutes
            const now = new Date();
            
            // Calculer le temps restant en secondes
            const timeRemaining = Math.max(0, Math.floor((expirationDate.getTime() - now.getTime()) / 1000));
            setTimer(timeRemaining);
          } else {
            setTimer(TIMER_DURATION);
          }
        } catch (error) {
          console.error('Erreur lors de la récupération des informations OTP:', error);
          setTimer(TIMER_DURATION);
        }
        
        enqueueSnackbar(SUCCESS_MESSAGES.codeResent, { variant: 'success' });
      } else {
        enqueueSnackbar(ERROR_MESSAGES.resendCode, { variant: 'error' });
      }
    } catch (error) {
      enqueueSnackbar(ERROR_MESSAGES.resendCode, { variant: 'error' });
    }
  };
  return (
    <Container maxWidth="sm" sx={{ maxWidth: 700 }}>
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, p: 10 }}>
        <Typography variant="h4" sx={{ color: 'primary.main', textAlign: 'center', fontWeight: 'bold' }}>
          Vérification du code - Chauffeur
        </Typography>

        <Paper elevation={0} sx={{ p: 4, borderRadius: 4, bgcolor: 'background.neutral' }}>
          <Stack spacing={3}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <LockReset sx={{ color: 'primary.main' }} />
              <Typography variant="subtitle1" color="text.secondary">
                Entrez le code reçu par email
              </Typography>
            </Box>
            <ConditionalComponent isValid={!isLoadingOtp && timer === 0}>
              <Box sx={{ p: 2, borderRadius: 2, bgcolor: 'error.lighter', textAlign: 'center' }}>
                <Typography variant="body2" color="error.dark">
                  Le code de vérification a expiré. Veuillez demander un nouveau code.
                </Typography>
              </Box>
            </ConditionalComponent>

            <form onSubmit={formik.handleSubmit}>
              <Stack spacing={3}>
                <FormField
                  isReadOnly={!isLoadingOtp && timer === 0}
                  field={ForgotPasswordFormData.code[0]}
                  value={formik.values.code}
                  onChange={(name, value) => formik.setFieldValue(name, value)}
                  onBlur={formik.handleBlur}
                />

                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Button
                    variant="text"
                    size="small"
                    onClick={handleResendCode}
                    disabled={!isLoadingOtp && timer > 0}
                    sx={{ color: 'primary.main', textTransform: 'none' }}
                  >
                    {BUTTON_TEXTS.resendCode}
                  </Button>
                  <ConditionalComponent isValid={!isLoadingOtp && timer > 0}>
                    <Typography variant="caption" color="text.secondary">
                      Temps restant: {formatTime(timer)}
                    </Typography>
                  </ConditionalComponent>
                </Box>

                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
                  <Button
                    type="submit"
                    variant="contained"
                    size="large"
                    disabled={formik.isSubmitting || (!isLoadingOtp && timer === 0)}
                    sx={{ minWidth: 200 }}
                  >
                    Vérifier le code
                  </Button>
                </Box>
              </Stack>
            </form>
          </Stack>
        </Paper>
      </Box>
    </Container>
  );
}