'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Typography,
  Box,
  Link,
  Button,
  Stack,
  Container,
  Paper,
  Alert,
  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 } from '../utils/constants';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { useRuntimeConfig } from '@/hooks/useRuntimeConfig';

export default function DriverForgotPasswordEmailView() {
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const { isConfigReady } = useRuntimeConfig();
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const [showErrorMessage, setShowErrorMessage] = useState(false);
  const sendResetPassword = useDriverStore((state) => state.sendResetPassword); 
  
  const formik = useFormik({
    initialValues: { email: '' },
    validationSchema: validationSchemas.email,
        onSubmit: async (values) => {
      setShowSuccessMessage(false);
      setShowErrorMessage(false);
      
      try {
        const response = await sendResetPassword({ email: values.email }); 
        if (response && response.toLowerCase().includes('password reset email sent successfully')) {
          setShowSuccessMessage(true);
          setTimeout(() => {
            router.push('/auth/jwt/login');
          }, 3000);
        } else {
          setShowErrorMessage(true);
        }
      } catch (error: any) {
        enqueueSnackbar(error?.message || ERROR_MESSAGES.default, { 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" sx={{ maxWidth: 700 }}>
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, p: 10 }}>
        <Typography variant="h4" sx={{ color: 'primary.main', textAlign: 'center', fontWeight: 'bold' }}>
          Mot de passe oublié - 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 votre adresse email pour recevoir un code
              </Typography>
            </Box>

            <ConditionalComponent isValid={showSuccessMessage}>
              <Alert severity="success" sx={{ mt: 1 }}>
                Vous allez recevoir un email pour réinitialiser votre mot de passe. Veuillez vérifier votre boîte mail.
              </Alert>
            </ConditionalComponent>
            
            <ConditionalComponent isValid={showErrorMessage}>
              <Alert severity="error" sx={{ mt: 1 }}>
                Une erreur est survenue. Réessayez l&apos;envoi d&apos;email.
              </Alert>
            </ConditionalComponent>
                
            <form onSubmit={formik.handleSubmit}>
              <Stack spacing={3}>
                <FormField
                  isReadOnly={false}
                  field={ForgotPasswordFormData.email[0]}
                  value={formik.values.email}
                  onChange={(name, value) => formik.setFieldValue(name, value)}
                  onBlur={formik.handleBlur}
                />

                <Stack direction="row" spacing={2} justifyContent="space-between" alignItems="center">
                  <Link
                    component="button"
                    type="button"
                    variant="body2"
                    onClick={() => router.push('/auth/jwt/login')}
                    sx={{
                      color: 'primary.main',
                      textDecoration: 'none',
                      '&:hover': { textDecoration: 'underline' }
                    }}
                  >
                    {BUTTON_TEXTS.backToLogin}
                  </Link>
                  <Button
                    type="submit"
                    variant="contained"
                    size="large"
                    disabled={formik.isSubmitting}
                    sx={{ minWidth: 200 }}
                  >
                    Envoyer le code
                  </Button>
                </Stack>
              </Stack>
            </form>
          </Stack>
        </Paper>
      </Box>
    </Container>
  );
}