import React, { useState } from 'react';
import { TextField, Button, Box, Alert, Stack } from '@mui/material';
import { EmailCredentials } from '../../services/auth/authService';
import { logger } from '../../debugConfig';

interface EmailSignupFormProps {
  role: 'email_teacher' | 'email_student';
  onSubmit: (
    credentials: EmailCredentials,
    displayName: string
  ) => Promise<void>;
}

export const EmailSignupForm: React.FC<EmailSignupFormProps> = ({
  role,
  onSubmit,
}) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const validateForm = () => {
    if (!email || !password || !confirmPassword || !displayName) {
      return 'All fields are required';
    }
    if (password !== confirmPassword) {
      return 'Passwords do not match';
    }
    if (password.length < 6) {
      return 'Password must be at least 6 characters';
    }
    if (!email.includes('@')) {
      return 'Please enter a valid email address';
    }
    return null;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const validationError = validateForm();
    if (validationError) {
      setError(validationError);
      return;
    }

    setError(null);
    setIsLoading(true);

    try {
      logger.debug('email-signup-form', '🔄 Submitting signup form', {
        email,
        role,
        hasDisplayName: !!displayName,
      });

      await onSubmit({ email, password, role }, displayName);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'An error occurred during signup'
      );
      logger.error(
        'email-signup-form',
        '❌ Signup form submission failed',
        err
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Box component="form" onSubmit={handleSubmit} noValidate>
      <Stack spacing={2}>
        <TextField
          required
          fullWidth
          id="displayName"
          label="Display Name"
          name="displayName"
          autoComplete="name"
          value={displayName}
          onChange={(e) => setDisplayName(e.target.value)}
          autoFocus
        />

        <TextField
          required
          fullWidth
          id="email"
          label="Email Address"
          name="email"
          autoComplete="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />

        <TextField
          required
          fullWidth
          name="password"
          label="Password"
          type="password"
          id="password"
          autoComplete="new-password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />

        <TextField
          required
          fullWidth
          name="confirmPassword"
          label="Confirm Password"
          type="password"
          id="confirmPassword"
          autoComplete="new-password"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
        />

        {error && <Alert severity="error">{error}</Alert>}

        <Button
          type="submit"
          fullWidth
          variant="contained"
          disabled={
            isLoading || !email || !password || !confirmPassword || !displayName
          }
        >
          {isLoading ? 'Signing up...' : 'Sign Up'}
        </Button>
      </Stack>
    </Box>
  );
};
