import {
  useState,
  useEffect,
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  Space,
  Divider,
  Typography,
  Alert,
  message,
  Row,
  Col,
  UserOutlined,
  LockOutlined,
  SafetyOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  LoginOutlined,
  GoogleOutlined,
  GithubOutlined,
  Title,
  Text,
  Link,
  useNavigate,
  FC,
} from '@/imports';
import { useLocale } from '@/contexts/LocaleContext';

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

const LoginPage: 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 { t } = useLocale();

  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);
  };

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

  const handleLogin = async (values: LoginFormValues) => {
    setLoading(true);
    setLoginError(null);

    try {
      if (values.captcha?.toUpperCase() !== captchaCode) {
        setLoginError(t('login.invalidCaptcha'));
        generateCaptcha();
        setLoading(false);
        return;
      }

      const response = await fetch('http://localhost:3001/api/v1/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
        }),
      });

      const result = await response.json();

      if (!result.success) {
        setLoginError(result.error || t('login.loginFailed'));
        generateCaptcha();
        setLoading(false);
        return;
      }

      localStorage.setItem('token', result.data.token);
      localStorage.setItem('refreshToken', result.data.refreshToken);
      localStorage.setItem('userId', result.data.user.id);
      localStorage.setItem('username', result.data.user.username);
      localStorage.setItem('roleCode', result.data.user.role);
      localStorage.setItem('tenantId', result.data.user.tenantId);
      localStorage.setItem('shopId', result.data.user.shopId);

      message.success(t('login.loginSuccess'));
      setTimeout(() => {
        navigate('/dashboard');
      }, 1000);
    } catch (error) {
      console.error('Login error:', error);
      setLoginError(t('login.loginFailed'));
      generateCaptcha();
    } 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 }}>
              {t('app.name')}
            </Title>
            <Text style={{ color: 'rgba(255,255,255,0.9)', fontSize: 18, display: 'block', marginBottom: 32 }}>
              {t('app.title')}
            </Text>
            <Space direction="vertical" size="large" style={{ color: 'rgba(255,255,255,0.8)' }}>
              <div>✓ {t('nav.products')}</div>
              <div>✓ {t('nav.orders')}</div>
              <div>✓ {t('nav.analytics')}</div>
              <div>✓ {t('nav.finance')}</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}>
                {t('login.title')}
              </Title>
              <Text type="secondary">
                {t('login.subtitle')}
              </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: t('common.required') },
                  { min: 3, message: 'Username must be at least 3 characters' },
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder={t('login.username')}
                  size="large"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: t('common.required') },
                  { min: 6, message: 'Password must be at least 6 characters' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                  placeholder={t('login.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: t('common.required') }]}
                    >
                      <Input
                        prefix={<SafetyOutlined style={{ color: '#bfbfbf' }} />}
                        placeholder={t('login.verificationCode')}
                        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>
                        {t('login.remember')}
                      </Checkbox>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Link to="/auth/reset-password">
                      {t('login.forgot')}
                    </Link>
                  </Col>
                </Row>
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  size="large"
                  block
                  loading={loading}
                  icon={<LoginOutlined />}
                >
                  {t('login.submit')}
                </Button>
              </Form.Item>

              <Divider>
                {t('login.orContinueWith')}
              </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">
                  {t('login.noAccount')} {' '}
                  <Link to="/auth/register">
                    {t('login.signup')}
                  </Link>
                </Text>
              </div>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default LoginPage;
