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

function Register() {
  const navigate = useNavigate();

  const onFinish = async (values) => {
    try {
      await api.post('/auth/register', values);
      message.success('Registration successful, please check your email to confirm your account');
      navigate('/login?registered=true');
    } catch (error) {
      message.error('Registration failed: ' + (error.response?.data?.detail || 'Unknown error'));
    }
  };

  return (
    <Card title="Register" style={{ maxWidth: 400, margin: '0 auto', ...commonStyles.cardGray }}>
      <p>This is for existing Auburn Oil customers that do not have an online account.</p>
      <Form
        name="register"
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
      >
        <Form.Item
          name="account_number"
          rules={[{ required: true, message: 'Please input your account number!' }]}
        >
          <Input placeholder="Account Number" />
        </Form.Item>

        <Form.Item
          name="house_number"
          rules={[{ required: true, message: 'Please input your house number!' }]}
        >
          <Input prefix={<HomeOutlined />} placeholder="House Number" />
        </Form.Item>

        <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 placeholder="Password" />
        </Form.Item>

        <Form.Item
          name="confirm_password"
          rules={[
            { required: true, message: 'Please confirm your password!' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('The two passwords do not match!'));
              },
            }),
          ]}
        >
          <Input.Password placeholder="Confirm Password" />
        </Form.Item>

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

        <Form.Item>
          Already have an account? <Link to="/login">Login</Link>
        </Form.Item>
      </Form>
    </Card>
  );
}

export default Register;
