import React, { useState, useCallback, memo } from 'react';
import { useAuth } from '../../hooks/useAuth';
import { LoginCredentials, ValidationErrors } from '../../types/auth.types';
import { validateEmail, validatePassword } from '../../utils/validation';
import { LoadingSpinner } from '../common/LoadingSpinner';
import styled from 'styled-components';

const FormContainer = styled.form`
  max-width: 400px;
  margin: 0 auto;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
`;

const Input = styled.input`
  width: 100%;
  padding: 0.75rem;
  margin-bottom: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  &:focus {
    outline: none;
    border-color: #0066cc;
    box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.2);
  }
`;

const Button = styled.button`
  width: 100%;
  padding: 0.75rem;
  background-color: #0066cc;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  
  &:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
  }

  &:focus {
    outline: none;
    box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.2);
  }
`;

const ErrorMessage = styled.div`
  color: #dc3545;
  margin-bottom: 1rem;
  font-size: 0.875rem;
`;

export const LoginForm: React.FC = memo(() => {
  const { login, isLoading, error, clearError } = useAuth();
  const [credentials, setCredentials] = useState<LoginCredentials>({
    email: '',
    password: '',
  });
  const [validationErrors, setValidationErrors] = useState<ValidationErrors>({});

  const validateForm = useCallback((): boolean => {
    const errors: ValidationErrors = {};
    if (!validateEmail(credentials.email)) {
      errors.email = 'Please enter a valid email address';
    }
    if (!validatePassword(credentials.password)) {
      errors.password = 'Password must be at least 8 characters long';
    }
    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  }, [credentials]);

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setCredentials(prev => ({ ...prev, [name]: value }));
    clearError();
  }, [clearError]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;
    
    try {
      await login(credentials);
    } catch (error) {
      // Error is handled by AuthProvider
    }
  };

  return (
    <FormContainer onSubmit={handleSubmit} noValidate>
      <Input
        type="email"
        name="email"
        value={credentials.email}
        onChange={handleChange}
        placeholder="Email"
        aria-label="Email"
        aria-invalid={!!validationErrors.email}
        disabled={isLoading}
      />
      {validationErrors.email && (
        <ErrorMessage role="alert">{validationErrors.email}</ErrorMessage>
      )}

      <Input
        type="password"
        name="password"
        value={credentials.password}
        onChange={handleChange}
        placeholder="Password"
        aria-label="Password"
        aria-invalid={!!validationErrors.password}
        disabled={isLoading}
      />
      {validationErrors.password && (
        <ErrorMessage role="alert">{validationErrors.password}</ErrorMessage>
      )}

      {error && <ErrorMessage role="alert">{error}</ErrorMessage>}

      <Button type="submit" disabled={isLoading}>
        {isLoading ? <LoadingSpinner /> : 'Login'}
      </Button>
    </FormContainer>
  );
});

LoginForm.displayName = 'LoginForm';