'use client';

import React 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 } from '../utils/constants';
import PasswordStrengthIndicator from '@/shared/sections/staff/profil/password/components/password-strength-indicator';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { useRuntimeConfig } from '@/hooks/useRuntimeConfig';

export default function DriverForgotPasswordResetView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { enqueueSnackbar } = useSnackbar();
  const { isConfigReady } = useRuntimeConfig();
  const email = searchParams.get('email') || '';
  const operationHash = searchParams.get('operationHash') || '';

  const confirmUserPassword = useDriverStore(state => state.confirmUserPassword); 

  const formik = useFormik({
    initialValues: { newPassword: '', confirmPassword: '' },
    validationSchema: validationSchemas.newPassword,
    onSubmit: async (values) => {
      try {
        if (email && operationHash) {
          const response = await confirmUserPassword({
            email,
            operationHash,
            password: values.newPassword,
          });

          if (response) {
            enqueueSnackbar(SUCCESS_MESSAGES.passwordReset, { variant: 'success' });
            router.push('/auth/jwt/login');
          } else {
            enqueueSnackbar(ERROR_MESSAGES.default, { variant: 'error' });
          }
        } else {
          enqueueSnackbar("Email ou opération absents dans l'URL.", { variant: 'error' });
        }
      } 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' }}>
          Nouveau mot de passe - 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">
                Définissez votre nouveau mot de passe
              </Typography>
            </Box>

            <form onSubmit={formik.handleSubmit}>
              <Stack spacing={3}>
                {ForgotPasswordFormData.newPassword.map((field) => (
                  <Box key={field.name}>
                    <FormField
                      isReadOnly={false}
                      field={{ ...field, showPassword: true }}
                      value={formik.values[field.name as 'newPassword' | 'confirmPassword']}
                      onChange={(name, value) => formik.setFieldValue(name, value)}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched[field.name as 'newPassword' | 'confirmPassword'] &&
                        formik.errors[field.name as 'newPassword' | 'confirmPassword']
                          ? formik.errors[field.name as 'newPassword' | 'confirmPassword']
                          : undefined
                      }
                    />
                    <ConditionalComponent isValid={field.name === 'newPassword' && Boolean(formik.values.newPassword)}>
                      <PasswordStrengthIndicator password={formik.values.newPassword} />
                    </ConditionalComponent>
                  </Box>
                ))}

                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
                  <Button
                    type="submit"
                    variant="contained"
                    size="large"
                    disabled={formik.isSubmitting}
                    sx={{ minWidth: 200 }}
                  >
                    Réinitialiser le mot de passe
                  </Button>
                </Box>
              </Stack>
            </form>
          </Stack>
        </Paper>
      </Box>
    </Container>
  );
}
