import { useState, useCallback, useMemo, CSSProperties } from 'react';
import { Form, Input, Button, Card, Typography, Space, Divider, Checkbox, Progress, message } from 'antd';
import { UserOutlined, MailOutlined, LockOutlined, GoogleOutlined, FacebookOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { UserManagementService } from '@/services/userManagement';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';

interface PasswordStrengthResult {
  score: number;
  label: string;
}

const calculatePasswordStrength = (password: string): PasswordStrengthResult => {
  if (!password) return { score: 0, label: '' };
  
  let score = 0;
  if (password.length >= 8) score++;
  if (/[a-z]/.test(password)) score++;
  if (/[A-Z]/.test(password)) score++;
  if (/\d/.test(password)) score++;
  if (/[^a-zA-Z0-9]/.test(password)) score++;
  
  const labels = ['', 'Weak', 'Fair', 'Good', 'Strong'];
  return { score, label: labels[score] || '' };
};

const RegisterPage = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  
  const [loading, setLoading] = useState<boolean>(false);
  const [passwordStrength, setPasswordStrength] = useState<number>(0);
  const [passwordStrengthLabel, setPasswordStrengthLabel] = useState<string>('');

  const handlePasswordChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    const result = calculatePasswordStrength(value);
    setPasswordStrength(result.score);
    setPasswordStrengthLabel(result.label);
  }, []);

  const handleSubmit = async (values: {
    email: string;
    password: string;
    confirm_password: string;
    display_name: string;
    terms_accepted: boolean;
    privacy_accepted: boolean;
  }) => {
    setLoading(true);
    try {
      const registerResponse = await UserManagementService.createRegister({
        email: values.email,
        password: values.password,
        role: 'BUYER',
        is_active: true,
        is_verified: false
      });

      if (registerResponse.data) {
        messageApi.success('Account created! Please check your email to verify your account.');
        navigate(ROUTES.LOGIN);
      }
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Registration failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

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

  const handleSocialLoginGoogle = useCallback(() => {
    messageApi.info('Google sign-in is not yet implemented.');
  }, [messageApi]);

  const handleSocialLoginFacebook = useCallback(() => {
    messageApi.info('Facebook sign-in is not yet implemented.');
  }, [messageApi]);

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

  const validateCheckbox = useCallback((_: unknown, value: boolean) => {
    if (value) {
      return Promise.resolve();
    }
    return Promise.reject(new Error('This field is required'));
  }, []);

  const pageContainerStyle: CSSProperties = useMemo(() => ({
    minHeight: '100vh',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    background: 'linear-gradient(135deg, #fef3f0 0%, #ffffff 50%, #fff5f3 100%)',
    padding: '24px'
  }), []);

  const formCardStyle: CSSProperties = useMemo(() => ({
    width: '100%',
    maxWidth: '480px',
    boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
    borderRadius: '12px',
    padding: '8px'
  }), []);

  const headerSectionStyle: CSSProperties = useMemo(() => ({
    textAlign: 'center',
    marginBottom: '8px'
  }), []);

  const logoTextStyle: CSSProperties = useMemo(() => ({
    color: '#E3350D',
    marginBottom: '4px',
    fontWeight: 700
  }), []);

  const pageTitleStyle: CSSProperties = useMemo(() => ({
    marginBottom: '4px',
    marginTop: '0'
  }), []);

  const socialSectionStyle: CSSProperties = useMemo(() => ({
    marginBottom: '8px'
  }), []);

  const socialButtonStyle: CSSProperties = useMemo(() => ({
    height: '44px',
    borderRadius: '8px'
  }), []);

  const dividerStyle: CSSProperties = useMemo(() => ({
    margin: '16px 0'
  }), []);

  const passwordStrengthContainerStyle: CSSProperties = useMemo(() => ({
    marginTop: '-16px',
    marginBottom: '8px'
  }), []);

  const passwordStrengthTextStyle: CSSProperties = useMemo(() => ({
    fontSize: '12px'
  }), []);

  const agreementsSectionStyle: CSSProperties = useMemo(() => ({
    marginBottom: '16px'
  }), []);

  const termsFieldStyle: CSSProperties = useMemo(() => ({
    marginBottom: '8px'
  }), []);

  const privacyFieldStyle: CSSProperties = useMemo(() => ({
    marginBottom: '8px'
  }), []);

  const submitButtonStyle: CSSProperties = useMemo(() => ({
    height: '48px',
    borderRadius: '8px',
    fontWeight: 600,
    fontSize: '16px'
  }), []);

  const loginSectionStyle: CSSProperties = useMemo(() => ({
    textAlign: 'center',
    marginTop: '16px'
  }), []);

  const loginLinkStyle: CSSProperties = useMemo(() => ({
    color: '#E3350D'
  }), []);

  const progressStrokeColor = useMemo(() => ({
    '0%': '#ff4d4f',
    '25%': '#ff7a45',
    '50%': '#ffc53d',
    '75%': '#73d13d',
    '100%': '#52c41a'
  }), []);

  return (
    <div style={pageContainerStyle}>
      {contextHolder}
      <Card bordered={false} style={formCardStyle}>
        <div style={headerSectionStyle}>
          <Typography.Title level={3} style={logoTextStyle}>
            PokeResell
          </Typography.Title>
          <Typography.Title level={4} style={pageTitleStyle}>
            Create Your Account
          </Typography.Title>
          <Typography.Text type="secondary">
            Join the largest Pokémon card marketplace
          </Typography.Text>
        </div>

        <div style={socialSectionStyle}>
          <Space direction="vertical" size={12} style={{ width: '100%' }}>
            <Button
              block
              size="large"
              icon={<GoogleOutlined />}
              style={socialButtonStyle}
              onClick={handleSocialLoginGoogle}
            >
              Continue with Google
            </Button>
            <Button
              block
              size="large"
              icon={<FacebookOutlined />}
              style={socialButtonStyle}
              onClick={handleSocialLoginFacebook}
            >
              Continue with Facebook
            </Button>
          </Space>
        </div>

        <Divider style={dividerStyle}>or sign up with email</Divider>

        <Form
          form={form}
          layout="vertical"
          requiredMark={true}
          size="large"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="Display Name"
            name="display_name"
            rules={[
              { required: true, message: 'Please enter a display name' },
              { min: 2, message: 'Display name must be at least 2 characters' }
            ]}
          >
            <Input
              placeholder="Choose a display name"
              prefix={<UserOutlined />}
              maxLength={50}
            />
          </Form.Item>

          <Form.Item
            label="Email Address"
            name="email"
            rules={[
              { required: true, message: 'Please enter your email address' },
              { type: 'email', message: 'Please enter a valid email address' }
            ]}
          >
            <Input
              placeholder="you@example.com"
              prefix={<MailOutlined />}
              type="email"
            />
          </Form.Item>

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

          <div style={passwordStrengthContainerStyle}>
            <Progress
              percent={passwordStrength * 25}
              showInfo={false}
              size="small"
              strokeColor={progressStrokeColor}
            />
            <Typography.Text type="secondary" style={passwordStrengthTextStyle}>
              {passwordStrengthLabel}
            </Typography.Text>
          </div>

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

          <div style={agreementsSectionStyle}>
            <Form.Item
              name="terms_accepted"
              valuePropName="checked"
              rules={[{ validator: validateCheckbox, message: 'You must accept the Terms of Service' }]}
              style={termsFieldStyle}
            >
              <Checkbox>I agree to the Terms of Service</Checkbox>
            </Form.Item>

            <Form.Item
              name="privacy_accepted"
              valuePropName="checked"
              rules={[{ validator: validateCheckbox, message: 'You must accept the Privacy Policy' }]}
              style={privacyFieldStyle}
            >
              <Checkbox>I agree to the Privacy Policy</Checkbox>
            </Form.Item>
          </div>

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

        <div style={loginSectionStyle}>
          <Typography.Text type="secondary">Already have an account? </Typography.Text>
          <Typography.Link strong style={loginLinkStyle} onClick={handleNavigateToLogin}>
            Log In
          </Typography.Link>
        </div>
      </Card>
    </div>
  );
};

export default RegisterPage;