import React, { useCallback } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { TextField, Button, Box, Typography, Alert, CircularProgress } from '@mui/material';
import { useAddLeadMutation } from '../../store/api/leadApi';
import { LeadFormData } from '../../types/lead';
import { sanitizeInput } from '../../utils/sanitization';
import ErrorBoundary from '../common/ErrorBoundary';

const LeadForm: React.FC = React.memo(() => {
  const { 
    control, 
    handleSubmit, 
    reset, 
    formState: { errors, isSubmitting } 
  } = useForm<LeadFormData>({ 
    mode: 'onBlur',
    defaultValues: {
      name: '',
      email: '',
      source: ''
    }
  });

  const [addLead, { isLoading, error }] = useAddLeadMutation();

  const onSubmit = useCallback(async (data: LeadFormData) => {
    try {
      const sanitizedData = {
        ...data,
        name: sanitizeInput(data.name),
        email: sanitizeInput(data.email.toLowerCase()),
        source: data.source ? sanitizeInput(data.source) : 'direct'
      };
      await addLead(sanitizedData).unwrap();
      reset();
    } catch (err) {
      console.error('Failed to add lead:', err);
    }
  }, [addLead, reset]);

  return (
    <ErrorBoundary fallback={<Alert severity="error">Form error occurred</Alert>}>
      <Box 
        component="form" 
        onSubmit={handleSubmit(onSubmit)} 
        sx={{ 
          maxWidth: 600,
          p: 3,
          boxShadow: 1,
          borderRadius: 1
        }}
        aria-label="lead submission form"
      >
        <Typography variant="h6" gutterBottom component="h2">
          Add New Lead
        </Typography>

        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            Failed to add lead. Please try again.
          </Alert>
        )}

        <Controller
          name="name"
          control={control}
          rules={{ 
            required: 'Name is required',
            minLength: { value: 2, message: 'Name must be at least 2 characters' },
            maxLength: { value: 50, message: 'Name must not exceed 50 characters' }
          }}
          render={({ field }) => (
            <TextField
              {...field}
              label="Name"
              fullWidth
              margin="normal"
              error={!!errors.name}
              helperText={errors.name?.message}
              disabled={isLoading}
              inputProps={{ 
                'aria-label': 'lead name',
                maxLength: 50
              }}
            />
          )}
        />

        <Controller
          name="email"
          control={control}
          rules={{ 
            required: 'Email is required',
            pattern: {
              value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
              message: 'Invalid email address'
            },
            maxLength: { value: 100, message: 'Email must not exceed 100 characters' }
          }}
          render={({ field }) => (
            <TextField
              {...field}
              label="Email"
              type="email"
              fullWidth
              margin="normal"
              error={!!errors.email}
              helperText={errors.email?.message}
              disabled={isLoading}
              inputProps={{ 
                'aria-label': 'lead email',
                maxLength: 100
              }}
            />
          )}
        />

        <Button
          type="submit"
          variant="contained"
          color="primary"
          disabled={isLoading || isSubmitting}
          sx={{ mt: 2 }}
          startIcon={isLoading && <CircularProgress size={20} />}
        >
          {isLoading ? 'Adding...' : 'Add Lead'}
        </Button>
      </Box>
    </ErrorBoundary>
  );
});

LeadForm.displayName = 'LeadForm';

export default LeadForm;