import { View, Text } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { useAuth } from '@/utils/auth'
import { cn } from '@/utils/cn'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import Navbar from '@/components/ui/navbar'
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from '@/components/ui/form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import './index.css'

const loginSchema = z.object({
  username: z
    .string()
    .min(3, '用户名至少3个字符')
    .max(20, '用户名最多20个字符')
    .regex(/^\S+$/, '用户名不能包含空格'),
  password: z
    .string()
    .min(6, '密码至少6位')
    .max(20, '密码最多20位'),
})

type LoginFormData = z.infer<typeof loginSchema>

export default function Login() {
  const [showPassword, setShowPassword] = useState(false)
  const { login, isLoading } = useAuth()

  const form = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      username: '',
      password: '',
    },
  })

  // 设置导航栏标题
  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: '用户登录'
    })
  }, [])

  const onSubmit = async (data: LoginFormData) => {
    try {
      Taro.showLoading({
        title: '登录中...',
        mask: true
      })

      await login({
        username: data.username.trim(),
        password: data.password.trim()
      })
      
      Taro.hideLoading()
      
      Taro.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500
      })
      
      setTimeout(() => {
        Taro.switchTab({ url: '/pages/index/index' })
      }, 1500)
    } catch (error: any) {
      Taro.hideLoading()
      
      const errorMessage = error.message || '登录失败'
      
      if (errorMessage.includes('用户名或密码错误')) {
        Taro.showToast({
          title: '用户名或密码错误',
          icon: 'none',
          duration: 3000
        })
      } else if (errorMessage.includes('网络')) {
        Taro.showModal({
          title: '网络错误',
          content: '请检查网络连接后重试',
          showCancel: false,
          confirmText: '确定'
        })
      } else {
        Taro.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        })
      }
    }
  }

  const goToRegister = () => {
    Taro.navigateTo({
      url: '/pages/register/index'
    })
  }

  return (
    <View className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50">
      <Navbar
        title="用户登录"
        backgroundColor="bg-transparent"
        textColor="text-gray-900"
        border={false}
      />
      <View className="flex-1 px-6 py-12">
        {/* Logo区域 */}
        <View className="flex flex-col items-center mb-10">
          <View className="w-20 h-20 mb-4 rounded-full bg-white shadow-lg flex items-center justify-center">
            <View className="i-heroicons-user-circle-20-solid w-12 h-12 text-blue-500" />
          </View>
          <Text className="text-2xl font-bold text-gray-900 mb-1">欢迎回来</Text>
          <Text className="text-gray-600 text-sm">请使用您的账号登录系统</Text>
        </View>

        {/* 登录表单 */}
        <View className="bg-white rounded-2xl shadow-sm p-6">
          <Form {...form}>
            <View className="space-y-5">
              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>用户名</FormLabel>
                    <FormControl>
                      <Input
                        leftIcon="i-heroicons-user-20-solid"
                        placeholder="请输入用户名"
                        maxlength={20}
                        type="text"
                        confirmType="next"
                        size="lg"
                        variant="filled"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>密码</FormLabel>
                    <FormControl>
                      <Input
                        leftIcon="i-heroicons-lock-closed-20-solid"
                        rightIcon={showPassword ? "i-heroicons-eye-20-solid" : "i-heroicons-eye-slash-20-solid"}
                        placeholder="请输入密码"
                        password={!showPassword}
                        maxlength={20}
                        confirmType="done"
                        size="lg"
                        variant="filled"
                        onRightIconClick={() => setShowPassword(!showPassword)}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 忘记密码 */}
              <View className="flex justify-end">
                <Text className="text-sm text-blue-500 hover:text-blue-600">忘记密码？</Text>
              </View>

              {/* 登录按钮 */}
              <Button
                className={cn(
                  "w-full",
                  !form.formState.isValid || isLoading
                    ? "bg-gray-300"
                    : "bg-blue-500 hover:bg-blue-600"
                )}
                size="lg"
                variant="default"
                onClick={form.handleSubmit(onSubmit) as any}
                disabled={!form.formState.isValid || isLoading}
              >
                {isLoading ? (
                  <View className="flex items-center justify-center">
                    <View className="i-heroicons-arrow-path-20-solid animate-spin w-5 h-5 mr-2" />
                    登录中...
                  </View>
                ) : (
                  '安全登录'
                )}
              </Button>
            </View>
          </Form>

          {/* 微信登录 */}
          <View className="mt-6">
            <View className="relative">
              <View className="absolute inset-0 flex items-center">
                <View className="w-full border-t border-gray-300" />
              </View>
              <View className="relative flex justify-center text-sm">
                <Text className="px-2 bg-white text-gray-500">其他登录方式</Text>
              </View>
            </View>

            <View className="mt-6">
              <Button
                className={cn(
                  "w-full",
                  "bg-green-500 text-white hover:bg-green-600",
                  "border-none"
                )}
                size="lg"
                variant="default"
                onClick={() => {
                  Taro.navigateTo({
                    url: '/pages/login/wechat-login'
                  })
                }}
              >
                <View className="i-heroicons-chat-bubble-left-right-20-solid w-5 h-5 mr-2" />
                微信一键登录
              </Button>
            </View>
          </View>

          {/* 注册链接 */}
          <View className="mt-6 text-center">
            <Text className="text-sm text-gray-600">
              还没有账号？
              <Text
                className="text-blue-500 font-medium hover:text-blue-600"
                onClick={goToRegister}
              >
                立即注册
              </Text>
            </Text>
          </View>
        </View>

        {/* 协议声明 */}
        <View className="mt-8 text-center">
          <Text className="text-xs text-gray-500">
            登录即表示您同意
            <Text className="text-blue-500 mx-1">用户协议</Text>
            和
            <Text className="text-blue-500 mx-1">隐私政策</Text>
          </Text>
        </View>
      </View>
    </View>
  )
}