import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  Space,
  Divider,
  Typography,
  Alert,
  message,
  Steps,
  Row,
  Col,
  Select,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  SafetyOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  UserAddOutlined,
  CheckCircleOutlined,
  ArrowLeftOutlined,
  ArrowRightOutlined,
  BankOutlined,
  PhoneOutlined,
} from '@ant-design/icons';

const { Title, Text, Link } = Typography;
const { Step } = Steps;
const { Option } = Select;

interface RegisterFormValues {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
  companyName: string;
  phone: string;
  businessType: string;
  agreeTerms: boolean;
  captcha: string;
}

export const RegisterPage: React.FC = () => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [registerError, setRegisterError] = useState<string | null>(null);
  const [captchaCode, setCaptchaCode] = useState('');
  const [registrationComplete, setRegistrationComplete] = useState(false);

  const generateCaptcha = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let result = '';
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptchaCode(result);
  };

  React.useEffect(() => {
    generateCaptcha();
  }, []);

  const steps = [
    { title: 'Account', description: 'Basic info' },
    { title: 'Business', description: 'Company details' },
    { title: 'Verify', description: 'Confirmation' },
  ];

  const nextStep = async () => {
    try {
      if (currentStep === 0) {
        await form.validateFields(['username', 'email', 'password', 'confirmPassword']);
      } else if (currentStep === 1) {
        await form.validateFields(['companyName', 'phone', 'businessType']);
      }
      setCurrentStep(currentStep + 1);
    } catch (error) {
      // Validation failed
    }
  };

  const prevStep = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleRegister = async (values: RegisterFormValues) => {
    setLoading(true);
    setRegisterError(null);

    try {
      await new Promise(resolve => setTimeout(resolve, 2000));

      if (values.captcha?.toUpperCase() !== captchaCode) {
        setRegisterError('Invalid verification code');
        generateCaptcha();
        setLoading(false);
        return;
      }

      setRegistrationComplete(true);
      message.success('Registration successful!');
    } catch (error) {
      setRegisterError('Registration failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  if (registrationComplete) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: 24,
      }}>
        <Card style={{ maxWidth: 500, width: '100%', textAlign: 'center', borderRadius: 16 }}>
          <CheckCircleOutlined style={{ fontSize: 80, color: '#52c41a', marginBottom: 24 }} />
          <Title level={3}>Registration Complete!</Title>
          <Text type="secondary" style={{ display: 'block', marginBottom: 24 }}>
            Your account has been created successfully. Please check your email to verify your account.
          </Text>
          <Button type="primary" size="large" href="/auth/login">
            Go to Login
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: 24,
    }}>
      <Card
        style={{
          maxWidth: 600,
          width: '100%',
          borderRadius: 16,
          boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
        }}
        bodyStyle={{ padding: 40 }}
      >
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <Title level={3}>Create Account</Title>
          <Text type="secondary">Join Crawlful Hub today</Text>
        </div>

        <Steps current={currentStep} style={{ marginBottom: 32 }}>
          {steps.map(step => (
            <Step key={step.title} title={step.title} description={step.description} />
          ))}
        </Steps>

        {registerError && (
          <Alert
            message={registerError}
            type="error"
            showIcon
            style={{ marginBottom: 24 }}
            closable
            onClose={() => setRegisterError(null)}
          />
        )}

        <Form
          form={form}
          layout="vertical"
          onFinish={handleRegister}
        >
          {currentStep === 0 && (
            <>
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: 'Please enter username' },
                  { min: 3, message: 'Username must be at least 3 characters' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: 'Only letters, numbers and underscores allowed' },
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Username"
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="email"
                rules={[
                  { required: true, message: 'Please enter email' },
                  { type: 'email', message: 'Please enter valid email' },
                ]}
              >
                <Input
                  prefix={<MailOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Email"
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: 'Please enter password' },
                  { min: 8, message: 'Password must be at least 8 characters' },
                  { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: 'Must contain uppercase, lowercase and number' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Password"
                  size="large"
                  iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                dependencies={['password']}
                rules={[
                  { required: true, message: 'Please confirm password' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('Passwords do not match'));
                    },
                  }),
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Confirm Password"
                  size="large"
                  iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>
            </>
          )}

          {currentStep === 1 && (
            <>
              <Form.Item
                name="companyName"
                rules={[{ required: true, message: 'Please enter company name' }]}
              >
                <Input
                  prefix={<BankOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Company Name"
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: 'Please enter phone number' },
                  { pattern: /^\+?[\d\s-()]+$/, message: 'Please enter valid phone number' },
                ]}
              >
                <Input
                  prefix={<PhoneOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Phone Number"
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="businessType"
                rules={[{ required: true, message: 'Please select business type' }]}
              >
                <Select placeholder="Business Type" size="large">
                  <Option value="manufacturer">Manufacturer</Option>
                  <Option value="trading">Trading Company</Option>
                  <Option value="wholesaler">Wholesaler</Option>
                  <Option value="retailer">Retailer</Option>
                  <Option value="other">Other</Option>
                </Select>
              </Form.Item>
            </>
          )}

          {currentStep === 2 && (
            <>
              <Form.Item
                name="captcha"
                rules={[{ required: true, message: 'Please enter verification code' }]}
              >
                <Row gutter={8} align="middle">
                  <Col flex="auto">
                    <Input
                      prefix={<SafetyOutlined style={{ color: '#bfbfbf' }} />}
                      placeholder="Verification Code"
                      size="large"
                      maxLength={4}
                    />
                  </Col>
                  <Col>
                    <div
                      onClick={generateCaptcha}
                      style={{
                        width: 100,
                        height: 40,
                        background: '#f0f2f5',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontFamily: 'monospace',
                        fontSize: 20,
                        letterSpacing: 4,
                        cursor: 'pointer',
                        userSelect: 'none',
                        borderRadius: 4,
                        color: '#1890ff',
                        fontWeight: 'bold',
                      }}
                    >
                      {captchaCode}
                    </div>
                  </Col>
                </Row>
              </Form.Item>

              <Form.Item
                name="agreeTerms"
                valuePropName="checked"
                rules={[
                  {
                    validator: (_, value) =>
                      value ? Promise.resolve() : Promise.reject(new Error('Please agree to terms')),
                  },
                ]}
              >
                <Checkbox>
                  I agree to the <Link href="/terms">Terms of Service</Link> and{' '}
                  <Link href="/privacy">Privacy Policy</Link>
                </Checkbox>
              </Form.Item>
            </>
          )}

          <Form.Item>
            <Row justify="space-between">
              <Col>
                {currentStep > 0 && (
                  <Button icon={<ArrowLeftOutlined />} onClick={prevStep}>
                    Previous
                  </Button>
                )}
              </Col>
              <Col>
                {currentStep < 2 ? (
                  <Button type="primary" icon={<ArrowRightOutlined />} onClick={nextStep}>
                    Next
                  </Button>
                ) : (
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<UserAddOutlined />}
                  >
                    Create Account
                  </Button>
                )}
              </Col>
            </Row>
          </Form.Item>
        </Form>

        <Divider />

        <div style={{ textAlign: 'center' }}>
          <Text type="secondary">
            Already have an account? <Link href="/auth/login">Sign in</Link>
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default RegisterPage;
