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

const loginSchema = z.object({
  phone: z
    .string()
    .regex(/^1[3-9]\d{9}$/, '请输入有效的手机号码'),
  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 as any),
    defaultValues: {
      phone: '',
      password: '',
    },
  })

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

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

      await login({
        phone: data.phone.trim(),
        password: data.password.trim()
      })

      Taro.hideLoading()

      Taro.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500
      })

      setTimeout(() => {
        Taro.switchTab({ url: '/pages/yongren/dashboard/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
        })
      }
    }
  }


  return (
    <View className="min-h-screen bg-white">
      {/* 状态栏由小程序宿主提供，无需实现 */}
      <View className="h-[calc(100%-44px)] flex flex-col justify-center p-8">
        {/* Logo区域 - 对照原型第232-235行 */}
        <View className="text-center mb-10 flex flex-col">
          <Text className="text-2xl font-bold text-gray-800 mb-2">残疾人就业平台</Text>
          <Text className="text-gray-600">为人力资源公司提供专业服务</Text>
        </View>

        {/* 登录表单 - 对照原型第237-246行 */}
        <View className="mb-6">
          <Form {...form}>
            {/* 手机号输入框 */}
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <View className="flex items-center border border-gray-300 rounded-lg px-4 py-3 mb-4">
                      <View className="i-heroicons-phone-20-solid text-gray-400 mr-3 w-5 h-5" />
                      <Input
                        placeholder="请输入手机号"
                        maxlength={11}
                        type="number"
                        confirmType="next"
                        className="w-full outline-none border-none bg-transparent"
                        {...field}
                      />
                    </View>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 密码输入框 */}
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <View className="flex items-center border border-gray-300 rounded-lg px-4 py-3">
                      <View className="i-heroicons-lock-closed-20-solid text-gray-400 mr-3 w-5 h-5" />
                      <Input
                        placeholder="请输入密码"
                        password={!showPassword}
                        maxlength={20}
                        confirmType="done"
                        className="w-full outline-none border-none bg-transparent flex-1"
                        {...field}
                      />
                      <View
                        className={`i-heroicons-${showPassword ? 'eye-20-solid' : 'eye-slash-20-solid'} text-gray-400 ml-3 w-5 h-5`}
                        onClick={() => setShowPassword(!showPassword)}
                      />
                    </View>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </Form>
        </View>

        {/* 登录按钮 - 对照原型第248行 */}
        <Button
          className={cn(
            "bg-gradient-to-r from-blue-500 to-purple-600 text-white w-full py-3 rounded-lg font-medium mb-4",
            !form.formState.isValid || isLoading
              ? "opacity-50 cursor-not-allowed"
              : ""
          )}
          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>

        {/* 忘记密码链接 - 对照原型第250-252行 */}
        <View className="text-center mb-8">
          <Text className="text-sm text-blue-500">忘记密码？</Text>
        </View>

        {/* 协议声明 - 对照原型第254-256行 */}
        <View className="mt-12 text-center text-gray-500 text-sm">
          <Text>登录即表示同意</Text>
          <Text className="text-blue-500">《用户协议》</Text>
          <Text>和</Text>
          <Text className="text-blue-500">《隐私政策》</Text>
        </View>
      </View>
    </View>
  )
}