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

export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [code, setCode] = useState('');
    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState<{ username?: string, password?: string, code?: string }>({});
    const [keys, setKeys] = useState('');
    const [validImg, setValidImg] = useState('');
    const navigate = useNavigate();

    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(); // 正确解析 Response 为 JSON 数据
        }).then(res => {
            const { data = {} } = res;
            const { data: info = {} } = data;
            const { key = "", img = "" } = info;
            setKeys(key)
            setValidImg(img)
        })
    }

    const handleLogin = () => {
        if (!validateForm()) {
            return;
        }
        
        setLoading(true);
        try {
            console.log("values")
            const params = {
                username,
                password,
                code,
                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()
                    Message.error(msg);
                    setLoading(false);
                    return false;
                }
                Message.success(msg);
                localStorage.setItem("access_token", token);
                localStorage.setItem('isLoggedIn', 'true');
                setIsLoggedIn(true);
                // 跳转到首页
                navigate('/');
                // Cookies.set("access_token", toCode(token));

            }).catch((e) => {
                console.log("catch")
                setLoading(false);
            });
        } catch (error) {
            console.error('登录请求失败:', error);
            Message.error('网络错误，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    const handleInputChange = (field: string, value: string) => {
        if (field === 'username') {
            setUsername(value);
            if (errors.username) {
                setErrors({ ...errors, username: undefined });
            }
        } else if (field === 'password') {
            setPassword(value);
            if (errors.password) {
                setErrors({ ...errors, password: undefined });
            }
        } else if (field === 'code') {
            setCode(value);
            if (errors.code) {
                setErrors({ ...errors, code: undefined });
            }
        }
    };

    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>

            <div className="login-form">
                <div className="form-item mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <Input
                        placeholder="请输入用户名"
                        value={username}
                        onChange={(value) => handleInputChange('username', value)}
                        disabled={loading}
                    />
                    {errors.username && <div className="text-red-500 text-sm mt-1">{errors.username}</div>}
                </div>

                <div className="form-item mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <Input
                        htmlType="password"
                        placeholder="请输入密码"
                        value={password}
                        onChange={(value) => handleInputChange('password', value)}
                        disabled={loading}
                    />
                    {errors.password && <div className="text-red-500 text-sm mt-1">{errors.password}</div>}
                </div>
                
                <Row>
                    <Col span={16}>
                        <div className="form-item">
                            <label className="block text-sm font-medium text-gray-700 mb-1">验证码</label>
                            <Input
                                size="large"
                                placeholder="请输入验证码"
                                value={code}
                                onChange={(value) => handleInputChange('code', value)}
                                disabled={loading}
                            />
                            {errors.code && <div className="text-red-500 text-sm mt-1">{errors.code}</div>}
                        </div>
                    </Col>
                    <Col span={8}>
                        <img
                            src={validImg}
                            style={{
                                width: 82,
                                height: 30,
                                marginTop: 28,
                                cursor: 'pointer'
                            }}
                            onClick={evVerify}
                            alt="验证码"
                        />
                    </Col>
                </Row>

                <div className="form-item mt-6">
                    <Button
                        type="primary"
                        loading={loading}
                        onClick={handleLogin}
                        className="w-full"
                    >
                        {loading ? '登录中...' : '登录'}
                    </Button>
                </div>
            </div>

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