import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { login } from './service';
import { getEnabledTenants } from '@/pages/System/Tenant/service';
import { setToken, setUserInfo, setMenus } from '../../store/userSlice';
import { getCurrentUserMenus } from '@/pages/System/Menu/service';
import type { TenantResponse } from '@/pages/System/Tenant/types';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { Loader2 } from 'lucide-react';
import styles from './index.module.css';

const loginFormSchema = z.object({
  tenantId: z.string().min(1, '请选择租户'),
  username: z.string().min(1, '请输入用户名'),
  password: z.string().min(1, '请输入密码'),
});

type LoginFormValues = z.infer<typeof loginFormSchema>;

const Login: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [tenants, setTenants] = useState<TenantResponse[]>([]);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginFormSchema),
    defaultValues: {
      tenantId: '',
      username: '',
      password: '',
    },
  });

  const selectedTenantId = watch('tenantId');

  useEffect(() => {
    const fetchTenants = async () => {
      try {
        const data = await getEnabledTenants();
        setTenants(data);
      } catch (error) {
        console.error('获取租户列表失败:', error);
      }
    };

    fetchTenants();
  }, []);

  // 加载菜单数据
  const loadMenuData = async () => {
    try {
      const menuData = await getCurrentUserMenus();
      if (menuData && menuData.length > 0) {
        dispatch(setMenus(menuData));
      }
    } catch (error) {
      console.error('获取菜单数据失败:', error);
    }
  };

  const onSubmit = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      // 1. 登录获取 token 和用户信息
      const loginData = await login(values);
      dispatch(setToken(loginData.token));
      dispatch(
        setUserInfo({
          id: loginData.id,
          username: loginData.username,
          nickname: loginData.nickname,
          email: loginData.email,
          phone: loginData.phone,
        })
      );

      // 2. 获取菜单数据
      await loadMenuData();

      toast({
        title: '登录成功',
        description: '欢迎回来！',
      });
      navigate('/');
    } catch (error) {
      console.error('登录失败:', error);
      toast({
        title: '登录失败',
        description: error instanceof Error ? error.message : '用户名或密码错误',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      {/* 左侧区域 */}
      <div className={styles.leftSection}>
        <div>
          <h1 className="text-xl font-bold">链宇DevOps门户管理系统</h1>
        </div>
        <div className="space-y-4">
          <blockquote className="text-2xl font-medium">
            "平台帮助我们显著提升了部署效率，让团队可以更专注于业务开发。"
          </blockquote>
        </div>
      </div>

      {/* 右侧登录区域 */}
      <div className={styles.rightSection}>
        <div className={styles.loginBox}>
          <div className={styles.logo}>
            <h1>Deploy Ease Platform</h1>
            <p className="text-gray-500 mt-2">输入您的账号密码登录系统</p>
          </div>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            {/* 租户选择 */}
            <div className="space-y-2">
              <Label htmlFor="tenantId">租户</Label>
              <Select
                value={selectedTenantId}
                onValueChange={(value) => setValue('tenantId', value, { shouldValidate: true })}
              >
                <SelectTrigger id="tenantId" className="h-10">
                  <SelectValue placeholder="系统管理租户" />
                </SelectTrigger>
                <SelectContent>
                  {tenants.map((tenant) => (
                    <SelectItem key={tenant.code} value={tenant.code}>
                      {tenant.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.tenantId && (
                <p className="text-sm text-destructive">{errors.tenantId.message}</p>
              )}
            </div>

            {/* 用户名 */}
            <div className="space-y-2">
              <Label htmlFor="username">用户名</Label>
              <Input
                id="username"
                placeholder="admin"
                className="h-10"
                {...register('username')}
              />
              {errors.username && (
                <p className="text-sm text-destructive">{errors.username.message}</p>
              )}
            </div>

            {/* 密码 */}
            <div className="space-y-2">
              <Label htmlFor="password">密码</Label>
              <Input
                id="password"
                type="password"
                placeholder="········"
                className="h-10"
                {...register('password')}
              />
              {errors.password && (
                <p className="text-sm text-destructive">{errors.password.message}</p>
              )}
            </div>

            {/* 登录按钮 */}
            <Button type="submit" className="w-full h-10" disabled={loading}>
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              登录
            </Button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;
