// entrypoints/popup/pages/Login.tsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Input, Message } from '@alifd/next';

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 navigate = useNavigate();

    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) {
            newErrors.code = '请输入验证码';
        }

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

    const evVerify = () => {
        // 验证码刷新逻辑
        console.log('刷新验证码');
    };

    const handleLogin = (e: React.FormEvent) => {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        setLoading(true);

        // 模拟登录请求
        setTimeout(() => {
            // 这里添加实际的登录逻辑
            if (username && password && code) {
                // 模拟登录成功
                localStorage.setItem('isLoggedIn', 'true');
                setIsLoggedIn(true);
                // 跳转到首页
                navigate('/');
                Message.success('登录成功');
            } else {
                Message.error('登录失败，请检查输入信息');
            }
            setLoading(false);
        }, 1000);
    };

    return (
        <div className="bg-gray-50 p-4">
            <div className="text-center mb-6">
                <h1 className="text-2xl font-bold text-gray-800">系统登录</h1>
                <p className="text-gray-500 mt-2">请输入您的账号和密码</p>
            </div>

            <form onSubmit={handleLogin}>
                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2">用户名 *</label>
                    <Input
                        placeholder="请输入用户名"
                        value={username}
                        onChange={(value) => {
                            setUsername(value);
                            if (errors.username) {
                                setErrors({ ...errors, username: undefined });
                            }
                        }}
                        disabled={loading}
                        state={errors.username ? 'error' : undefined}
                    />
                    {errors.username && <div className="text-red-500 text-xs mt-1">{errors.username}</div>}
                </div>

                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2">密码 *</label>
                    <Input
                        htmlType="password"
                        placeholder="请输入密码"
                        value={password}
                        onChange={(value) => {
                            setPassword(value);
                            if (errors.password) {
                                setErrors({ ...errors, password: undefined });
                            }
                        }}
                        disabled={loading}
                        state={errors.password ? 'error' : undefined}
                    />
                    {errors.password && <div className="text-red-500 text-xs mt-1">{errors.password}</div>}
                </div>

                <div className="mb-6">
                    <label className="block text-gray-700 text-sm font-bold mb-2">验证码 *</label>
                    <Input
                        placeholder="请输入验证码"
                        value={code}
                        onChange={(value) => {
                            setCode(value);
                            if (errors.code) {
                                setErrors({ ...errors, code: undefined });
                            }
                        }}
                        disabled={loading}
                        state={errors.code ? 'error' : undefined}
                        addonTextAfter={
                            <img
                                src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNzAiIGhlaWdodD0iMzgiIHZpZXdCb3g9IjAgMCA3MCAzOCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjcwIiBoZWlnaHQ9IjM4IiBmaWxsPSIjRjBGMEYwIi8+Cjx0ZXh0IHg9IjM1IiB5PSIyMyIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjE0IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjMDAwIj5DNERMOEw8L3RleHQ+Cjwvc3ZnPgo="
                                style={{ width: 70, height: 38, cursor: 'pointer' }}
                                onClick={evVerify}
                                alt="验证码"
                            />
                        }
                    />
                    {errors.code && <div className="text-red-500 text-xs mt-1">{errors.code}</div>}
                </div>

                <div className="mb-4">
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                        className="w-full"
                    >
                        {loading ? '登录中...' : '登录'}
                    </Button>
                </div>
            </form>

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