import { useState, useEffect } from 'react';
import { Button, Card, Form, Input, message, Typography, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, ThunderboltOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAdminStore } from '../store';
import { getSiteInfo } from '../api';

const AdminLoginPage = () => {
  const navigate = useNavigate();
  const { login } = useAdminStore();
  const [loading, setLoading] = useState(false);
  
  const getInitialSiteInfo = () => {
    try {
      const cached = localStorage.getItem('siteInfo');
      if (cached) {
        const info = JSON.parse(cached);
        return {
          siteName: info.siteName || 'VideoGen.AI',
          siteLogo: info.siteLogo || '',
        };
      }
    } catch { }
    return { siteName: 'VideoGen.AI', siteLogo: '' };
  };
  
  const initialInfo = getInitialSiteInfo();
  const [siteName, setSiteName] = useState(initialInfo.siteName);
  const [siteLogo, setSiteLogo] = useState(initialInfo.siteLogo);

  useEffect(() => {
    getSiteInfo().then(info => {
      setSiteName(info.siteName);
      setSiteLogo(info.siteLogo);
    }).catch(() => {});
  }, []);

  const handleLogin = async (values: { username: string; password: string; rememberMe?: boolean }) => {
    setLoading(true);
    try {
      await login(values.username, values.password, values.rememberMe);
      message.success('登录成功');
      navigate('/');
    } catch (error: any) {
      const errorMsg = error?.message || '登录失败';
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      backgroundImage: `url(/backimage.png)`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      backgroundAttachment: 'fixed',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute',
        inset: 0,
        background: 'linear-gradient(135deg, rgba(240,244,255,0.9) 0%, rgba(232,236,248,0.85) 40%, rgba(240,240,255,0.9) 70%, rgba(248,249,255,0.95) 100%)',
      }} />
      <div style={{
        position: 'absolute',
        width: 500, height: 500, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(99,102,241,0.08) 0%, transparent 70%)',
        top: -150, right: -100, filter: 'blur(40px)',
      }} />
      <div style={{
        position: 'absolute',
        width: 400, height: 400, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(139,92,246,0.06) 0%, transparent 70%)',
        bottom: -100, left: -80, filter: 'blur(50px)',
      }} />

      <Card variant="outlined" style={{
        width: 440,
        borderRadius: 20,
        boxShadow: '0 20px 60px rgba(0,0,0,0.08)',
        border: '1px solid #e2e8f0',
        background: '#fff',
        zIndex: 1,
      }} styles={{ body: { padding: '36px 28px' } }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{
            width: 52,
            height: 52,
            borderRadius: 14,
            margin: '0 auto 16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: siteLogo
              ? 'transparent'
              : 'linear-gradient(135deg, #6366f1, #8b5cf6)',
            boxShadow: siteLogo ? 'none' : '0 8px 24px rgba(99,102,241,0.25)',
          }}>
            {siteLogo ? (
              <img src={siteLogo} alt="logo" style={{ width: '100%', height: '100%', borderRadius: 14, objectFit: 'contain' }} />
            ) : (
              <ThunderboltOutlined style={{ fontSize: 26, color: '#fff' }} />
            )}
          </div>
          <Typography.Title level={3} style={{ margin: 0, color: '#1e293b', fontWeight: 700 }}>
            {siteName}
            <span style={{ color: '#6366f1' }}>.AI</span>
          </Typography.Title>
          <Typography.Text type="secondary" style={{ fontSize: 14, color: '#94a3b8' }}>管理后台</Typography.Text>
        </div>

        <Form onFinish={handleLogin} layout="vertical">
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input
              placeholder="用户名"
              size="large"
              prefix={<UserOutlined style={{ color: '#94a3b8', marginRight: 8 }} />}
              style={{
                background: '#fff',
                border: '1.5px solid #e2e8f0',
                color: '#1e293b',
                height: 48,
                borderRadius: 10,
                fontSize: 14,
              }}
            />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password
              placeholder="密码"
              size="large"
              prefix={<LockOutlined style={{ color: '#94a3b8', marginRight: 8 }} />}
              style={{
                background: '#fff',
                border: '1.5px solid #e2e8f0',
                color: '#1e293b',
                height: 48,
                borderRadius: 10,
                fontSize: 14,
              }}
            />
          </Form.Item>
          <Form.Item name="rememberMe" valuePropName="checked" style={{ marginBottom: 12 }}>
            <Checkbox>记住我的登录状态</Checkbox>
          </Form.Item>
          <Form.Item style={{ marginBottom: 8 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
              style={{
                height: 48,
                borderRadius: 10,
                fontSize: 16,
                fontWeight: 600,
                background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                border: 'none',
                boxShadow: '0 8px 24px rgba(99,102,241,0.25)',
              }}
            >
              登录管理后台
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default AdminLoginPage;
