// entrypoints/popup/pages/Login.tsx
import React, { useState, useEffect, useRef } from 'react'; // 添加 useRef
import { useNavigate } from 'react-router-dom';
import { Button, Input, Message, Form, Grid } from '@alifd/next';
const { Row, Col } = Grid
import { CustomMessage } from '@/components/CustomMessage'

export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
    const formRef = useRef<any>(null);
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState<{ username?: string, password?: string, code?: string }>({}); // 添加 code 错误字段
    const [keys, setKeys] = useState('');
    const [validImg, setValidImg] = useState('');
    const navigate = useNavigate();

    // 添加验证码状态
    const [code, setCode] = useState('');

    useEffect(() => {
        evVerify()
    }, [])

    const validateForm = () => {
        const newErrors: { username?: string, password?: string, code?: string } = {};

        if (!username.trim()) {
            newErrors.username = '请输入用户名';
        }

        if (!password) {
            newErrors.password = '请输入密码';
        } else if (password.length < 6) {
            newErrors.password = '密码长度至少为6位';
        }

        // 添加验证码校验
        if (!code.trim()) {
            newErrors.code = '请输入验证码';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const evVerify = () => {
        console.log('username')
        fetch('https://user.landwu.com/api/user/verify', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        }).then(resjson => {
            return resjson.json();
        }).then(res => {
            const { data = {} } = res;
            const { data: info = {} } = data;
            const { key = "", img = "" } = info;
            setKeys(key)
            setValidImg(img)
        })
    }

    const handleLogin = (values: any) => {
        if (!validateForm()) return
        try {
            setLoading(true);
            const params = {
                ...values,
                key: keys
            }
            // 发送登录请求
            fetch('https://user.landwu.com/api/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(params),
            }).then(response => response.json()).then(res => {
                const { msg = "", token = "", code } = res;
                if (!code) {
                    setLoading(false);
                    return false;
                }

                if (code == -1) {
                    evVerify()
                    CustomMessage.error(msg);
                    setLoading(false);
                    return false;
                }
                fetch('https://user.landwu.com/api/user/getProfile', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ api_token: token }),
                }).then(response => response.json()).then(res => {
                    if (res.code == 1) {
                        const { data = {} } = res;
                        const { userinfo = {} } = data;
                        const userinfo_str = JSON.stringify(userinfo);
                        localStorage.setItem('userinfo', userinfo_str);
                        CustomMessage.success(msg);
                        localStorage.setItem("access_token", token);
                        localStorage.setItem('isLoggedIn', 'true');
                        setLoading(false);
                        setIsLoggedIn(true);
                        // 跳转到首页
                        navigate('/');
                    }
                }).catch(err => {
                    setLoading(false);
                })
            }).catch((e) => {
                console.log("catch")
                setLoading(false);
            });
        } catch (error) {
            console.error('登录请求失败:', error);
            CustomMessage.error('网络错误，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="bg-gray-50 p-4">
            <div className="text-center mb-6">
                <h1 className="text-2xl font-bold text-gray-800">登录</h1>
            </div>

            <Form>
                <Form.Item
                    label="用户名"
                    name="username"
                    required
                    help={errors.username}
                    validateState={errors.username ? 'error' : undefined}
                >
                    <Input
                        placeholder="请输入用户名"
                        value={username}
                        onChange={(value) => {
                            if (typeof value === 'string') {
                                setUsername(value);
                            } else {
                                setUsername(String(value));
                            }
                            if (errors.username) {
                                setErrors({ ...errors, username: undefined });
                            }
                        }}
                        disabled={loading}
                    />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="password"
                    required
                    help={errors.password}
                    validateState={errors.password ? 'error' : undefined}
                >
                    <Input
                        htmlType="password"
                        placeholder="请输入密码"
                        value={password}
                        onChange={(value) => {
                            if (typeof value === 'string') {
                                setPassword(value);
                            } else {
                                setPassword(String(value));
                            }
                            if (errors.password) {
                                setErrors({ ...errors, password: undefined });
                            }
                        }}
                        disabled={loading}
                    />
                </Form.Item>
                <Row>
                    <Col span={16}>
                        <Form.Item
                            label="验证码"
                            name="code"
                            required
                            help={errors.code}
                            validateState={errors.code ? 'error' : undefined}
                        >
                            <Input
                                size="large"
                                placeholder="请输入验证码"
                                value={code}
                                onChange={(value) => {
                                    if (typeof value === 'string') {
                                        setCode(value);
                                    } else {
                                        setCode(String(value));
                                    }
                                    if (errors.code) {
                                        setErrors({ ...errors, code: undefined });
                                    }
                                }}
                                disabled={loading}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <img
                            src={validImg}
                            style={{
                                width: 82,
                                height: 28,
                                marginTop: 28,
                                cursor: 'pointer',
                            }}
                            onClick={evVerify}
                        />
                    </Col>
                </Row>

                <Form.Item>
                    <Form.Submit
                        type="primary"
                        validate
                        loading={loading}
                        onClick={handleLogin}
                        className="w-full"
                        style={{ marginRight: 8 }}
                    >
                        {loading ? '登录中...' : '登录'}
                    </Form.Submit>
                </Form.Item>
            </Form>

            <div className="mt-4 text-center text-sm text-gray-500">
                <p>忘记密码？请联系管理员</p>
            </div>
        </div>
    );
}