'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  Typography,
  Box,
  Link,
  Button,
  Stack,
  Container,
  Paper,
  CircularProgress,
} 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 { useCollaboratorStore } from '@/shared/api/stores/CollaboratorStore';
import { useRuntimeConfig } from '@/hooks/useRuntimeConfig';

export default function ForgotPasswordVerifyView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { enqueueSnackbar } = useSnackbar();
  const { isConfigReady } = useRuntimeConfig();
  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 = useCollaboratorStore((state) => state.confirmOtp);
  const sendResetPassword = useCollaboratorStore((state) => state.sendResetPassword);
  const getOtpByUsername = useCollaboratorStore((state) => state.getOtpByUsername);

  useEffect(() => {
    // Don't fetch data until config is ready
    if (!isConfigReady) {
      return;
    }

    const emailParam = searchParams.get('email') || '';
    const operationHashParam = searchParams.get('operationHash') || '';

    if (emailParam && operationHashParam) {
      setEmail(emailParam);
      setOperationHash(operationHashParam);

      const fetchOtpInfo = async () => {
        try {
          const otpData = await getOtpByUsername(emailParam);
          if (otpData && otpData.generationDate) {
            const generationDate = new Date(otpData.generationDate);
            const expirationDate = new Date(generationDate.getTime() + 5 * 60 * 1000);
            const now = new Date();
            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);
        } finally {
          setIsLoadingOtp(false);
        }
      };

      fetchOtpInfo();
    } else {
      setErrorMessage("Impossible de vérifier le code : informations manquantes dans l'URL.");
      setIsLoadingOtp(false);
    }
  }, [getOtpByUsername, searchParams, isConfigReady]);

  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/forgot-password/reset?email=${encodeURIComponent(email)}&operationHash=${operationHash}`);
        } 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) {
        setOperationHash(response.operationHash);

        // Recalcule du timer après renvoi
        try {
          const otpData = await getOtpByUsername(email);
          if (otpData && otpData.generationDate) {
            const generationDate = new Date(otpData.generationDate);
            const expirationDate = new Date(generationDate.getTime() + 5 * 60 * 1000);
            const now = new Date();
            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);
        }

        // Mettre à jour l'URL avec le nouvel operationHash
        try {
          const params = new URLSearchParams(window.location.search);
          params.set('operationHash', response.operationHash);
          router.replace(`${window.location.pathname}?${params.toString()}`);
        } catch {
          // no-op si URLSearchParams indisponible (sécurité)
        }

        enqueueSnackbar(SUCCESS_MESSAGES.codeResent, { variant: 'success' });
      } else {
        enqueueSnackbar(ERROR_MESSAGES.resendCode, { variant: 'error' });
      }
    } catch (error) {
      enqueueSnackbar(ERROR_MESSAGES.resendCode, { variant: 'error' });
    }
  };

  // Show loading spinner while config is initializing
  if (!isConfigReady) {
    return (
      <Container maxWidth="sm">
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '50vh' }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  return (
    <Container maxWidth="sm">
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, p: 3 }}>
        <Typography variant="h4" sx={{ color: 'primary.main', textAlign: 'center', fontWeight: 'bold' }}>
          Vérification du code
        </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>
  );
}