import { useState } from 'react'
import { View, Text, ScrollView, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { z } from 'zod'
import { Navbar, NavbarPresets } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Input as ShadcnInput } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from '@/components/ui/form'
import { useAuth } from '@/utils/auth'
import { passengerClient } from '@/api'
import type { InferResponseType } from 'hono/client'
import { IdType } from '@/types/passenger.types'

// 使用RPC方式提取类型
type Passenger = InferResponseType<typeof passengerClient.$get, 200>['data'][0]

// 证件号码验证函数
const validateIdNumber = (idNumber: string, idType: IdType) => {
  switch (idType) {
    case IdType.ID_CARD:
      return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idNumber)
    case IdType.HONG_KONG_MACAO_PASS:
      return /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/.test(idNumber)
    case IdType.TAIWAN_PASS:
      return /^[0-9]{8}$/.test(idNumber)
    case IdType.PASSPORT:
      return /^[EeKkGgDdSsPp]([0-9]{8}|[0-9]{7})$/.test(idNumber)
    case IdType.OTHER:
      return idNumber.length >= 1 && idNumber.length <= 30
    default:
      return true
  }
}

// 乘客表单验证schema
const passengerFormSchema = z.object({
  name: z
    .string()
    .min(1, '请输入姓名')
    .min(2, '姓名至少2个字符')
    .max(50, '姓名不能超过50个字符'),
  idType: z.nativeEnum(IdType, {
    message: '请选择证件类型'
  }),
  idNumber: z
    .string()
    .min(1, '请输入证件号码')
    .max(30, '证件号码不能超过30个字符'),
  phone: z
    .string()
    .min(1, '请输入手机号')
    .regex(/^1[3-9]\d{9}$/, '手机号格式不正确')
})

type PassengerFormData = z.infer<typeof passengerFormSchema>

const PassengersPage: React.FC = () => {
  const { user } = useAuth()
  const queryClient = useQueryClient()

  const [searchKeyword, setSearchKeyword] = useState('')
  const [showSearchBar, setShowSearchBar] = useState(false)
  const [showAddModal, setShowAddModal] = useState(false)
  const [editingPassenger, setEditingPassenger] = useState<Passenger | null>(null)

  // 初始化react-hook-form
  const form = useForm<PassengerFormData>({
    resolver: zodResolver(passengerFormSchema),
    defaultValues: {
      name: '',
      idType: IdType.ID_CARD,
      idNumber: '',
      phone: ''
    }
  })

  // 证件类型选项
  const idTypeOptions = [
    { label: '身份证', value: IdType.ID_CARD },
    { label: '港澳通行证', value: IdType.HONG_KONG_MACAO_PASS },
    { label: '台湾通行证', value: IdType.TAIWAN_PASS },
    { label: '护照', value: IdType.PASSPORT },
    { label: '其他证件', value: IdType.OTHER }
  ]

  // 获取当前证件类型的索引
  const currentIdTypeIndex = idTypeOptions.findIndex(option => option.value === form.watch('idType'))

  // 获取乘客列表
  const { data: passengersResponse, isLoading } = useQuery({
    queryKey: ['passengers'],
    queryFn: async () => {
      const response = await passengerClient.$get({ query: { page: 1, pageSize: 100 } })
      const result = await response.json()
      // 检查响应是否包含data字段
      if ('data' in result) {
        return result
      }
      // 如果响应是错误格式，返回空数据
      return { data: [], total: 0, page: 1, pageSize: 100 }
    },
    enabled: !!user
  })

  // 提取乘客列表数据
  const passengers = passengersResponse?.data || []

  // 添加乘客
  const addMutation = useMutation({
    mutationFn: async (passengerData: { name: string; idType: IdType; idNumber: string; phone: string }) => {
      const response = await passengerClient.$post({ json: passengerData })
      return await response.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['passengers'] })
      setShowAddModal(false)
      resetForm()
      Taro.showToast({ title: '添加成功', icon: 'success' })
    },
    onError: (error) => {
      Taro.showToast({ title: '添加失败', icon: 'none' })
      console.error('添加乘客失败:', error)
    }
  })

  // 更新乘客
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: Partial<Passenger> }) => {
      const response = await passengerClient[':id'].$put({
        param: { id },
        json: data
      })
      return await response.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['passengers'] })
      setShowAddModal(false)
      resetForm()
      Taro.showToast({ title: '更新成功', icon: 'success' })
    },
    onError: (error) => {
      Taro.showToast({ title: '更新失败', icon: 'none' })
      console.error('更新乘客失败:', error)
    }
  })

  // 删除乘客
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      await passengerClient[':id'].$delete({ param: { id } })
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['passengers'] })
      Taro.showToast({ title: '删除成功', icon: 'success' })
    },
    onError: (error) => {
      Taro.showToast({ title: '删除失败', icon: 'none' })
      console.error('删除乘客失败:', error)
    }
  })

  // 设置默认乘客
  const setDefaultMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await passengerClient[':id']['set-default'].$post({
        param: { id }
      })
      return await response.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['passengers'] })
      Taro.showToast({ title: '设置成功', icon: 'success' })
    },
    onError: (error) => {
      Taro.showToast({ title: '设置失败', icon: 'none' })
      console.error('设置默认乘客失败:', error)
    }
  })

  // 重置表单
  const resetForm = () => {
    form.reset({
      name: '',
      idType: IdType.ID_CARD,
      idNumber: '',
      phone: ''
    })
    setEditingPassenger(null)
  }

  // 过滤乘客列表
  const filteredPassengers = passengers.filter(passenger => {
    if (!searchKeyword) return true
    const keyword = searchKeyword.toLowerCase()
    return (
      passenger.name.toLowerCase().includes(keyword) ||
      passenger.phone.includes(keyword) ||
      passenger.idNumber.includes(keyword)
    )
  })

  // 显示添加模态框
  const showAddPassenger = () => {
    resetForm()
    setShowAddModal(true)
  }

  // 编辑乘客
  const editPassenger = (passenger: Passenger) => {
    form.reset({
      name: passenger.name,
      idType: passenger.idType,
      idNumber: passenger.idNumber,
      phone: passenger.phone
    })
    setEditingPassenger(passenger)
    setShowAddModal(true)
  }

  // 删除乘客
  const deletePassenger = (passenger: Passenger) => {
    Taro.showModal({
      title: '确认删除',
      content: `确定要删除乘车人"${passenger.name}"吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#ff4d4f',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          deleteMutation.mutate(passenger.id)
        }
      }
    })
  }

  // 设置默认乘客
  const setDefaultPassenger = (passenger: Passenger) => {
    setDefaultMutation.mutate(passenger.id)
  }

  // 保存乘客
  const onSubmit = (data: PassengerFormData) => {
    // 额外的证件号码格式验证
    if (!validateIdNumber(data.idNumber, data.idType)) {
      Taro.showToast({ title: '证件号码格式不正确', icon: 'none' })
      return
    }

    if (editingPassenger) {
      updateMutation.mutate({
        id: editingPassenger.id,
        data: data
      })
    } else {
      addMutation.mutate(data)
    }
  }

  // 查看乘客详情
  const viewPassengerDetail = (passenger: Passenger) => {
    Taro.showModal({
      title: '乘车人详情',
      content: `姓名：${passenger.name}\n证件类型：${passenger.idType}\n证件号码：${passenger.idNumber}\n手机号：${passenger.phone}\n创建时间：${format(new Date(passenger.createdAt), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })}`,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: '#4A90C2'
    })
  }


  if (!user) {
    return (
      <View className="flex-1 flex flex-col items-center justify-center">
        <View className="flex flex-col items-center">
          <View className="i-heroicons-exclamation-circle-20-solid w-12 h-12 text-gray-400 mx-auto mb-4" />
          <Text className="text-gray-600 mb-4">请先登录</Text>
          <Button
            variant="default"
            size="lg"
            onClick={() => Taro.navigateTo({ url: '/pages/login/index' })}
          >
            去登录
          </Button>
        </View>
      </View>
    )
  }

  return (
    <View className="flex-1 bg-gradient-to-b from-gray-50 to-gray-100 min-h-screen pb-40">
      <Navbar
        title="乘车人管理"
        leftIcon="i-heroicons-arrow-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
        {...NavbarPresets.primary}
      />

      {/* 顶部操作栏 */}
      <View className="px-4 py-4 bg-white shadow-sm">
        <View className="mb-3">
        <Button
            variant="outline"
            className="w-full bg-[rgba(74,144,194,0.1)] border-2 border-[rgba(74,144,194,0.2)] text-primary rounded-[50rpx] px-[32rpx] py-[20rpx] transition-all duration-300 active:bg-[rgba(74,144,194,0.15)] active:scale-98"
            onClick={() => setShowSearchBar(!showSearchBar)}
          >
            <View className="flex items-center justify-center">
              <View className="text-[32rpx] mr-[12rpx]">🔍</View>
              <Text className="text-[28rpx] font-medium">搜索乘车人</Text>
            </View>
          </Button>
        </View>

        {showSearchBar && (
          <View className="animate-slide-down">
            <ShadcnInput
              placeholder="输入姓名、手机号或证件号"
              value={searchKeyword}
              onChange={(value) => setSearchKeyword(value)}
              className="w-full"
            />
          </View>
        )}
      </View>

      {/* 乘车人列表 */}
      <ScrollView className="px-4 mt-3 flex-1">
        {isLoading ? (
          <View className="flex items-center justify-center py-20">
            <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
            <Text className="text-gray-500 mt-2">加载中...</Text>
          </View>
        ) : filteredPassengers.length === 0 ? (
          <View className="text-center py-20 bg-white/80 rounded-2xl my-4 backdrop-blur-sm border border-white/30">
            <View className="text-6xl mb-3 opacity-60">👥</View>
            <Text className="text-lg text-gray-600 mb-1 font-semibold">
              {searchKeyword ? '没有找到相关乘车人' : '暂无乘车人'}
            </Text>
            <Text className="text-sm text-gray-500">
              {searchKeyword ? '试试其他关键词' : '点击下方按钮添加常用乘车人'}
            </Text>
          </View>
        ) : (
          <View className="space-y-3">
            {filteredPassengers.map((passenger) => (
              <Card
                key={passenger.id}
                className="bg-white/95 rounded-2xl shadow-lg backdrop-blur-md border border-white/40 transition-all duration-300 active:translate-y-0.5 active:shadow-md"
              >
                <CardContent className="p-4">
                  <View
                    className="mb-3"
                    onClick={() => viewPassengerDetail(passenger)}
                  >
                    <View className="flex items-center justify-between mb-2">
                      <View className="flex items-center space-x-2">
                        <Text className="text-lg font-semibold text-gray-900 tracking-wide">
                          {passenger.name}
                        </Text>
                        {passenger.isDefault && (
                          <View className="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full font-medium">
                            默认
                          </View>
                        )}
                      </View>
                      <View className="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full font-medium">
                        {passenger.idType}
                      </View>
                    </View>

                    <View className="bg-blue-50 rounded-xl p-3 border border-blue-100">
                      <Text className="text-sm text-gray-700 mb-1 font-mono tracking-wide">
                        {passenger.idNumber}
                      </Text>
                      <Text className="text-sm text-gray-600 font-mono tracking-wide">
                        {passenger.phone}
                      </Text>
                    </View>
                  </View>

                  <View className="flex justify-end gap-2">
                    {!passenger.isDefault && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setDefaultPassenger(passenger)}
                        className="min-w-20"
                      >
                        设默认
                      </Button>
                    )}
                    <Button
                      variant="default"
                      size="sm"
                      onClick={() => editPassenger(passenger)}
                      className="min-w-20"
                    >
                      编辑
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => deletePassenger(passenger)}
                      className="min-w-20 border-red-500 text-red-500 hover:bg-red-50"
                    >
                      删除
                    </Button>
                  </View>
                </CardContent>
              </Card>
            ))}
          </View>
        )}
      </ScrollView>

      {/* 添加按钮 */}
      <View className="fixed bottom-4 left-4 right-4 z-100">
        <Button
          className="w-full"
          onClick={showAddPassenger}
        >
          <View className="flex items-center justify-center">
            <View className="text-lg mr-2">➕</View>
            添加乘车人
          </View>
        </Button>
      </View>

      {/* 添加/编辑乘车人模态框 */}
      <Dialog open={showAddModal} onOpenChange={setShowAddModal}>
        <DialogContent className="max-w-md max-h-80vh overflow-hidden">
          <DialogHeader>
            <DialogTitle className="text-lg font-semibold text-gray-900">
              {editingPassenger ? '编辑乘车人' : '添加乘车人'}
            </DialogTitle>
          </DialogHeader>

          <Form {...form}>
            <ScrollView className="max-h-60vh overflow-y-auto p-1">
              <View className="space-y-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>姓名</FormLabel>
                      <FormControl>
                        <ShadcnInput
                          placeholder="请输入姓名"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="idType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>证件类型</FormLabel>
                      <FormControl>
                        <Picker
                          mode="selector"
                          range={idTypeOptions.map(option => option.label)}
                          value={currentIdTypeIndex}
                          onChange={(e) => {
                            const index = Number(e.detail.value)
                            field.onChange(idTypeOptions[index].value)
                          }}
                        >
                          <View className="border border-gray-300 rounded-lg px-3 py-2 bg-white">
                            <Text className="text-gray-900">
                              {idTypeOptions[currentIdTypeIndex]?.label || '选择证件类型'}
                            </Text>
                          </View>
                        </Picker>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="idNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>证件号码</FormLabel>
                      <FormControl>
                        <ShadcnInput
                          placeholder="请输入证件号码"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>手机号</FormLabel>
                      <FormControl>
                        <ShadcnInput
                          placeholder="请输入手机号"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </View>
            </ScrollView>

            <DialogFooter className="pt-4 border-t border-gray-100 bg-gray-50/50 flex flex-row gap-4">
              <Button
                variant="outline"
                onClick={() => setShowAddModal(false)}
                className="flex-1"
              >
                取消
              </Button>
              <Button
                onClick={() => form.handleSubmit(onSubmit)()}
                disabled={addMutation.isPending || updateMutation.isPending}
                className="flex-1"
              >
                {addMutation.isPending || updateMutation.isPending ? (
                  <View className="i-heroicons-arrow-path-20-solid animate-spin w-4 h-4 mr-2" />
                ) : null}
                {editingPassenger ? '更新' : '保存'}
              </Button>
            </DialogFooter>
          </Form>
        </DialogContent>
      </Dialog>
    </View>
  )
}

export default PassengersPage