import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Card, message, Alert } from 'antd';
import { MailOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import api from '../../utils/api';
import { commonStyles } from '../../theme';

function Login() {
  const navigate = useNavigate();
  const location = useLocation();
  const [showConfirmationBanner, setShowConfirmationBanner] = useState(false);

  useEffect(() => {
    const params = new URLSearchParams(location.search);
    if (params.get('registered') === 'true') {
      setShowConfirmationBanner(true);
    }
  }, [location]);

  const onFinish = async (values) => {
    try {
      const response = await api.post('/auth/login', values);
      localStorage.setItem('token', response.data.access_token);
      message.success('Login successful');
      navigate('/');
    } catch (error) {
      message.error('Login failed: ' + (error.response?.data?.detail || 'Unknown error'));
    }
  };

  return (
    <Card title="Login" style={{ maxWidth: 400, margin: '0 auto', ...commonStyles.cardGray }}>
      {showConfirmationBanner && (
        <Alert
          message="Registration Successful"
          description="An email has been sent to your email address with instructions to confirm your account."
          type="success"
          showIcon
          closable
          onClose={() => setShowConfirmationBanner(false)}
          style={{ marginBottom: '16px' }}
        />
      )}
      <Form
        name="login"
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
      >
        <Form.Item
          name="email"
          rules={[
            { required: true, message: 'Please input your email!' },
            { type: 'email', message: 'Please enter a valid email!' }
          ]}
        >
          <Input prefix={<MailOutlined />} placeholder="Email" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="Password" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block>
            Login
          </Button>
        </Form.Item>

        <Form.Item>
          <Link to="/forgot-password">Forgot Password?</Link>
        </Form.Item>

        <Form.Item>
          <Link to="/register">Don't have an account? Register</Link>
        </Form.Item>
      </Form>
    </Card>
  );
}

export default Login;
