import { useState, useCallback, CSSProperties } from 'react';
import { Form, Input, Button, Card, Typography, Row, Col, DatePicker, Divider, Alert, Result, message } from 'antd';
import { MailOutlined, LockOutlined, PhoneOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { request } from '../api/client';
import { ROUTES } from '../router/routes.constant';
import dayjs, { Dayjs } from 'dayjs';

interface UserResponse {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
}

interface LoginResponse {
  user: UserResponse;
  access_token: string;
  token_type: string;
}

interface RegisterRequestBody {
  email: string;
  password: string;
  first_name: string;
  last_name: string;
  phone?: string | null;
  date_of_birth?: string | null;
  address?: string | null;
}

interface FormValues {
  first_name: string;
  last_name: string;
  email: string;
  password: string;
  confirm_password: string;
  phone?: string;
  date_of_birth?: Dayjs;
  street?: string;
  city?: string;
  state_value?: string;
  zip?: string;
}

export default function RegisterPage() {
  const [form] = Form.useForm<FormValues>();
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [registrationSuccess, setRegistrationSuccess] = useState<boolean>(false);
  const [membershipNumber, setMembershipNumber] = useState<string>('');
  const [registeredEmail, setRegisteredEmail] = useState<string>('');

  const validateAge = (_: unknown, value: Dayjs | null) => {
    if (!value) {
      return Promise.reject(new Error('Date of birth is required'));
    }
    const age = dayjs().diff(value, 'year');
    if (age < 13) {
      return Promise.reject(new Error('You must be at least 13 years old to register'));
    }
    return Promise.resolve();
  };

  const validatePasswordMatch = (_: unknown, value: string) => {
    if (!value || form.getFieldValue('password') === value) {
      return Promise.resolve();
    }
    return Promise.reject(new Error('Passwords do not match'));
  };

  const submitRegistration = useCallback(async () => {
    try {
      const formValues = await form.validateFields();
      setIsSubmitting(true);

      const addressParts = [
        formValues.street,
        formValues.city,
        formValues.state_value,
        formValues.zip
      ].filter(Boolean);

      const requestBody: RegisterRequestBody = {
        email: formValues.email,
        password: formValues.password,
        first_name: formValues.first_name,
        last_name: formValues.last_name,
        phone: formValues.phone || null,
        date_of_birth: formValues.date_of_birth ? formValues.date_of_birth.format('YYYY-MM-DD') : null,
        address: addressParts.length > 0 ? addressParts.join(', ') : null
      };

      const result = await request<LoginResponse>({
        method: 'POST',
        path: '/auth/register',
        body: requestBody
      });

      setRegisteredEmail(result.data.user.email);
      setRegistrationSuccess(true);
      setIsSubmitting(false);
      messageApi.success('Registration successful! Welcome to the library.');
    } catch (error) {
      setIsSubmitting(false);
      messageApi.error('Registration failed. Please check your information and try again.');
    }
  }, [form, messageApi]);

  const navigateToLogin = useCallback(() => {
    navigate(ROUTES.LOGIN);
  }, [navigate]);

  const navigateToCatalog = useCallback(() => {
    navigate(ROUTES.HOME);
  }, [navigate]);

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    background: '#f5f5f5',
    padding: '24px'
  };

  const cardStyle: CSSProperties = {
    width: '100%',
    maxWidth: '600px',
    borderRadius: '8px'
  };

  const headerStyle: CSSProperties = {
    textAlign: 'center',
    marginBottom: '24px'
  };

  const titleStyle: CSSProperties = {
    marginBottom: '8px'
  };

  const submitButtonStyle: CSSProperties = {
    marginTop: '16px'
  };

  const loginLinkContainerStyle: CSSProperties = {
    textAlign: 'center',
    marginTop: '16px'
  };

  const catalogLinkStyle: CSSProperties = {
    display: 'block',
    textAlign: 'center',
    marginTop: '8px'
  };

  const zipInputStyle: CSSProperties = {
    maxWidth: '200px'
  };

  const successInfoStyle: CSSProperties = {
    marginBottom: '16px'
  };

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <Card bordered style={cardStyle}>
        {!registrationSuccess ? (
          <>
            <div style={headerStyle}>
              <Typography.Title level={2} style={titleStyle}>
                Member Registration
              </Typography.Title>
              <Typography.Text type="secondary">
                Create your library membership account
              </Typography.Text>
            </div>

            <Form
              form={form}
              layout="vertical"
              requiredMark
              scrollToFirstError
              onFinish={submitRegistration}
            >
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    name="first_name"
                    label="First Name"
                    rules={[{ required: true, message: 'First name is required' }]}
                  >
                    <Input placeholder="Enter your first name" size="large" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    name="last_name"
                    label="Last Name"
                    rules={[{ required: true, message: 'Last name is required' }]}
                  >
                    <Input placeholder="Enter your last name" size="large" />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                name="email"
                label="Email"
                rules={[
                  { required: true, message: 'Email is required' },
                  { type: 'email', message: 'Please enter a valid email address' }
                ]}
              >
                <Input
                  placeholder="Enter your email address"
                  size="large"
                  prefix={<MailOutlined />}
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="Password"
                hasFeedback
                rules={[
                  { required: true, message: 'Password is required' },
                  { min: 8, message: 'Password must be at least 8 characters' },
                  {
                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
                    message: 'Must contain uppercase, lowercase, and a number'
                  }
                ]}
              >
                <Input.Password
                  placeholder="Create a strong password"
                  size="large"
                  prefix={<LockOutlined />}
                />
              </Form.Item>

              <Form.Item
                name="confirm_password"
                label="Confirm Password"
                dependencies={['password']}
                hasFeedback
                rules={[
                  { required: true, message: 'Please confirm your password' },
                  { validator: validatePasswordMatch }
                ]}
              >
                <Input.Password
                  placeholder="Re-enter your password"
                  size="large"
                  prefix={<LockOutlined />}
                />
              </Form.Item>

              <Form.Item name="phone" label="Phone Number">
                <Input
                  placeholder="Enter your phone number"
                  size="large"
                  prefix={<PhoneOutlined />}
                />
              </Form.Item>

              <Form.Item
                name="date_of_birth"
                label="Date of Birth"
                rules={[
                  { required: true, message: 'Date of birth is required' },
                  { validator: validateAge }
                ]}
                extra="You must be at least 13 years old to register"
              >
                <DatePicker
                  placeholder="Select your date of birth"
                  size="large"
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              </Form.Item>

              <Divider orientation="left">Address</Divider>

              <Form.Item name="street" label="Street Address">
                <Input placeholder="Enter your street address" size="large" />
              </Form.Item>

              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item name="city" label="City">
                    <Input placeholder="City" size="large" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item name="state_value" label="State">
                    <Input placeholder="State" size="large" />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item name="zip" label="Zip Code">
                <Input placeholder="Zip Code" size="large" maxLength={10} style={zipInputStyle} />
              </Form.Item>

              <Button
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={isSubmitting}
                style={submitButtonStyle}
              >
                Create Account
              </Button>

              <div style={loginLinkContainerStyle}>
                <Typography.Text>Already have an account? </Typography.Text>
                <Typography.Link onClick={navigateToLogin}>Sign in here</Typography.Link>
                <Typography.Link onClick={navigateToCatalog} style={catalogLinkStyle}>
                  Browse Library Catalog
                </Typography.Link>
              </div>
            </Form>
          </>
        ) : (
          <Result
            status="success"
            title="Registration Successful!"
            subTitle="Your library membership account has been created. Your membership is currently pending librarian approval."
          >
            <Alert
              type="info"
              showIcon
              message="What happens next?"
              description="A librarian will review your registration and activate your membership. You will receive an email notification once your account is approved. This typically takes 1-2 business days."
              style={successInfoStyle}
            />
            <Button type="primary" size="large" onClick={navigateToLogin}>
              Go to Login
            </Button>
          </Result>
        )}
      </Card>
    </div>
  );
}