import React, { useEffect, useRef, useState } from 'react';
import { Form, Input, Button, Checkbox, Card, Typography } from 'antd';
import { UserOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { history } from 'umi';
import cookie from 'react-cookies';
import CaptchaInput from '@/components/CaptchaInput';
import styles from './internal.less';
import { internalUserLogin } from '@/services/login';

const { Title, Link } = Typography;

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

const InternalLogin: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const captchaRef = useRef<any>(null);

  const onFinish = async (values: LoginFormValues) => {
    const params = {
      account: values.username,
      password: values.password,
      captcha: values.captcha,
      remember: values.remember,
    }
    try {
      setLoading(true);
      const res = await internalUserLogin(params);
      if (res?.code === 200) {
        sessionStorage.setItem('Authorization', res?.data?.token || '');
        history.push('/redirect');
      } else {
        captchaRef.current?.refresh();
        form.setFieldsValue({
          captcha: {
            captcha: '',
            captchaToken: '',
          },
        });
      }
    } catch (error) {
      console.error('登录失败:', error);
    } finally {
      setLoading(false);
    }
  };


  // 组件挂载时，检查是否有记住的用户名
  useEffect(() => {
    const savedUser = localStorage.getItem('remember_user');
    if (savedUser) {
      const user = JSON.parse(savedUser);
      form.setFieldsValue({
        username: user.username,
        password: user.password,
        remember: true,
      });
    }
  }, [form]);

  useEffect(() => {
    cookie.remove('mall3_token');
    sessionStorage.clear();
  }, []);

  const renderLoginForm = () => (
    <Form
      form={form}
      name="login"
      onFinish={onFinish}
      autoComplete="off"
      size="large"
    >
      <Form.Item
        name="username"
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input
          prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
          placeholder={'请输入用户名'}
        />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password
          prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
          placeholder="请输入密码"
          iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
        />
      </Form.Item>

      <Form.Item
        name="captcha"
        rules={[
          { required: true, message: '请输入验证码' },
        ]}
      >
        <CaptchaInput
          placeholder="请输入验证码"
          ref={captchaRef}
        />
      </Form.Item>

      <Form.Item>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
          <Link href="#" style={{ color: '#1890ff' }}>忘记密码？</Link>
        </div>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading} block>
          登录
        </Button>
      </Form.Item>

      <div style={{ textAlign: 'center' }}>
        <span style={{ color: '#8c8c8c' }}>还没有账号？</span>
        <Link style={{ color: '#1890ff' }}>立即注册</Link>
      </div>
    </Form>
  );

  return (
    <div className={styles.loginContainer}>
      <Card className={styles.loginCard}>
        <Title level={2} style={{ textAlign: 'center', lineHeight: '80px', fontSize: 32, fontWeight: 700, marginBottom: 0 }}>
          电子招投标平台
        </Title>

        {renderLoginForm()}
      </Card>
    </div>
  );
};

export default InternalLogin;