import { View, Text } from '@tarojs/components'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
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 { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from '@/components/ui/form'
import Navbar from '@/components/ui/navbar'
import { registerSchema, type RegisterFormData } from '@/schemas/register.schema'
import './index.css'

export default function Register() {
  const { register, isLoading } = useAuth()
  
  const form = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    }
  })

  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: '创建账号'
    })
  }, [])

  const handleRegister = async (data: RegisterFormData) => {
    try {
      Taro.showLoading({
        title: '注册中...',
        mask: true
      })

      await register({
        username: data.username.trim(),
        password: data.password.trim(),
        email: data.email?.trim() || undefined
      })
      
      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 || '注册失败，请重试'
      Taro.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
  }

  const goToLogin = () => {
    Taro.navigateBack()
  }

  return (
    <View className="min-h-screen bg-gradient-to-br from-green-50 via-white to-emerald-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-plus-20-solid w-12 h-12 text-green-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="请输入用户名（3-20个字符）"
                        maxlength={20}
                        size="lg"
                        variant="filled"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 邮箱输入框 */}
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>邮箱（可选）</FormLabel>
                    <FormControl>
                      <Input
                        leftIcon="i-heroicons-envelope-20-solid"
                        placeholder="请输入邮箱地址"
                        type="text"
                        maxlength={50}
                        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="请输入密码（至少6位）"
                        password={!showPassword}
                        maxlength={20}
                        size="lg"
                        variant="filled"
                        onRightIconClick={() => setShowPassword(!showPassword)}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 确认密码输入框 */}
              <FormField
                control={form.control}
                name="confirmPassword"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>确认密码</FormLabel>
                    <FormControl>
                      <Input
                        leftIcon="i-heroicons-lock-closed-20-solid"
                        rightIcon={showConfirmPassword ? "i-heroicons-eye-20-solid" : "i-heroicons-eye-slash-20-solid"}
                        placeholder="请再次输入密码"
                        password={!showConfirmPassword}
                        maxlength={20}
                        size="lg"
                        variant="filled"
                        onRightIconClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 注册按钮 */}
              <Button
                className={cn(
                  "w-full",
                  isLoading ? "bg-gray-300" : "bg-green-500 hover:bg-green-600"
                )}
                size="lg"
                variant="default"
                onClick={form.handleSubmit(handleRegister) 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 text-center">
            <Text className="text-sm text-gray-600">
              已有账号？ 
              <Text 
                className="text-green-500 font-medium hover:text-green-600" 
                onClick={goToLogin}
              >
                立即登录
              </Text>
            </Text>
          </View>
        </View>

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