import React, { useState } from 'react';
import { useNavigate } from 'umi';
import {
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  Space,
  Divider,
  Typography,
  Alert,
  message,
  Row,
  Col,
  Image,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  SafetyOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  LoginOutlined,
  GoogleOutlined,
  GithubOutlined,
} from '@ant-design/icons';

const { Title, Text, Link } = Typography;

interface LoginFormValues {
  username: string;
  password: string;
  remember: boolean;
  captcha?: string;
}

export const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [loginError, setLoginError] = useState<string | null>(null);
  const [captchaCode, setCaptchaCode] = useState('');
  const navigate = useNavigate();

  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 handleLogin = async (values: LoginFormValues) => {
    setLoading(true);
    setLoginError(null);

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

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

      message.success('Login successful! Redirecting...');
      setTimeout(() => {
        navigate('/dashboard');
      }, 1000);
    } catch (error) {
      setLoginError('Login failed. Please check your credentials.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: 24,
    }}>
      <Row gutter={[48, 0]} align="middle" style={{ maxWidth: 1000, width: '100%' }}>
        <Col xs={0} md={12}>
          <div style={{ color: 'white', paddingRight: 48 }}>
            <Title level={1} style={{ color: 'white', marginBottom: 24 }}>
              Crawlful Hub
            </Title>
            <Text style={{ color: 'rgba(255,255,255,0.9)', fontSize: 18, display: 'block', marginBottom: 32 }}>
              Your all-in-one cross-border e-commerce management platform
            </Text>
            <Space direction="vertical" size="large" style={{ color: 'rgba(255,255,255,0.8)' }}>
              <div>✓ Multi-platform integration</div>
              <div>✓ Automated operations</div>
              <div>✓ Real-time analytics</div>
              <div>✓ Compliance management</div>
            </Space>
          </div>
        </Col>

        <Col xs={24} md={12}>
          <Card
            style={{
              borderRadius: 16,
              boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
            }}
            bodyStyle={{ padding: 40 }}
          >
            <div style={{ textAlign: 'center', marginBottom: 32 }}>
              <Title level={3}>Welcome Back</Title>
              <Text type="secondary">Sign in to your account</Text>
            </div>

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

            <Form
              form={form}
              layout="vertical"
              onFinish={handleLogin}
              initialValues={{ remember: true }}
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: 'Please enter your username' },
                  { min: 3, message: 'Username must be at least 3 characters' },
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Username or Email"
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: 'Please enter your password' },
                  { min: 6, message: 'Password must be at least 6 characters' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder="Password"
                  size="large"
                  iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>

              <Form.Item>
                <Row gutter={8} align="middle">
                  <Col flex="auto">
                    <Form.Item
                      name="captcha"
                      noStyle
                      rules={[{ required: true, message: 'Please enter verification code' }]}
                    >
                      <Input
                        prefix={<SafetyOutlined style={{ color: '#bfbfbf' }} />}
                        placeholder="Verification Code"
                        size="large"
                        maxLength={4}
                      />
                    </Form.Item>
                  </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>
                <Row justify="space-between" align="middle">
                  <Col>
                    <Form.Item name="remember" valuePropName="checked" noStyle>
                      <Checkbox>Remember me</Checkbox>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Link href="/auth/reset-password">Forgot password?</Link>
                  </Col>
                </Row>
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  size="large"
                  block
                  loading={loading}
                  icon={<LoginOutlined />}
                >
                  Sign In
                </Button>
              </Form.Item>

              <Divider>Or continue with</Divider>

              <Space style={{ width: '100%', justifyContent: 'center' }}>
                <Button icon={<GoogleOutlined />} size="large">
                  Google
                </Button>
                <Button icon={<GithubOutlined />} size="large">
                  GitHub
                </Button>
              </Space>

              <div style={{ textAlign: 'center', marginTop: 24 }}>
                <Text type="secondary">
                  Don't have an account? <Link href="/auth/register">Sign up</Link>
                </Text>
              </div>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default LoginPage;
