import { useState, useEffect } from 'react'
import { View, Text, ScrollView, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Navbar } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useAuth } from '@/utils/auth'
import { passengerClient } from '@/api'
import { IdType } from '@/types/passenger.types'

interface PassengerFormData {
  name: string
  idType: IdType
  idNumber: string
  phone: string
}

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

  const [formData, setFormData] = useState<PassengerFormData>({
    name: '',
    idType: IdType.ID_CARD,
    idNumber: '',
    phone: ''
  })

  const [from, setFrom] = useState<string>('order')

  // 证件类型选项
  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 === formData.idType)

  // 获取页面参数
  useEffect(() => {
    const currentPage = Taro.getCurrentPages().pop()
    if (currentPage?.options?.from) {
      setFrom(currentPage.options.from)
    }
  }, [])

  // 添加乘客
  const addMutation = useMutation({
    mutationFn: async (passengerData: PassengerFormData) => {
      const response = await passengerClient.$post({ json: passengerData })
      return await response.json()
    },
    onSuccess: (savedPassenger) => {
      queryClient.invalidateQueries({ queryKey: ['passengers'] })
      Taro.showToast({ title: '保存成功', icon: 'success' })

      // 如果来自订单页面，传递数据回上一页
      if (from === 'order') {
        const pages = Taro.getCurrentPages()
        const prevPage = pages[pages.length - 2]

        if (prevPage) {
          // 通过事件总线或全局状态传递数据
          // 这里使用简单的回调方式
          const eventChannel = Taro.getCurrentInstance().page?.getOpenerEventChannel?.()
          if (eventChannel) {
            eventChannel.emit('passengerAdded', savedPassenger)
          }
        }
      }

      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    },
    onError: (error) => {
      Taro.showToast({
        title: '保存失败',
        icon: 'none'
      })
      console.error('保存乘客失败:', error)
    }
  })

  // 保存乘客
  const savePassenger = () => {
    // 基本验证
    if (!formData.name.trim()) {
      Taro.showToast({ title: '请输入姓名', icon: 'none' })
      return
    }

    if (!formData.idNumber.trim()) {
      Taro.showToast({ title: '请输入证件号码', icon: 'none' })
      return
    }

    if (!formData.phone.trim()) {
      Taro.showToast({ title: '请输入手机号', icon: 'none' })
      return
    }

    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(formData.phone)) {
      Taro.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }

    addMutation.mutate(formData)
  }

  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-gray-50 min-h-screen">
      <Navbar
        title="添加乘车人"
        leftIcon="i-heroicons-arrow-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />

      <ScrollView className="flex-1 px-4 py-4">
        <Card className="bg-white rounded-2xl shadow-sm">
          <CardHeader>
            <CardTitle className="text-lg">乘车人信息</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 姓名 */}
            <View className="space-y-2">
              <Label htmlFor="name">姓名</Label>
              <Input
                id="name"
                placeholder="请输入姓名"
                value={formData.name}
                onChange={(value) => setFormData({ ...formData, name: value })}
                className="w-full"
              />
            </View>

            {/* 证件类型 */}
            <View className="space-y-2">
              <Label htmlFor="idType">证件类型</Label>
              <Picker
                mode="selector"
                range={idTypeOptions.map(option => option.label)}
                value={currentIdTypeIndex}
                onChange={(e) => {
                  const index = Number(e.detail.value)
                  setFormData({ ...formData, idType: 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>
            </View>

            {/* 证件号码 */}
            <View className="space-y-2">
              <Label htmlFor="idNumber">证件号码</Label>
              <Input
                id="idNumber"
                placeholder="请输入证件号码"
                value={formData.idNumber}
                onChange={(value) => setFormData({ ...formData, idNumber: value })}
                className="w-full"
              />
            </View>

            {/* 手机号 */}
            <View className="space-y-2">
              <Label htmlFor="phone">手机号</Label>
              <Input
                id="phone"
                placeholder="请输入手机号"
                value={formData.phone}
                onChange={(value) => setFormData({ ...formData, phone: value })}
                type="number"
                maxlength={11}
                className="w-full"
              />
            </View>
          </CardContent>
        </Card>

        {/* 提示信息 */}
        <View className="mt-4 p-4 bg-blue-50 rounded-xl border border-blue-200">
          <Text className="text-sm text-blue-700">
            • 请确保填写的信息准确无误
          </Text>
          <Text className="text-sm text-blue-700 mt-1">
            • 证件号码将用于实名认证
          </Text>
          <Text className="text-sm text-blue-700 mt-1">
            • 手机号将用于接收出行通知
          </Text>
        </View>
      </ScrollView>

      {/* 保存按钮 */}
      <View className="p-4 bg-white border-t border-gray-200">
        <Button
          className="w-full"
          onClick={savePassenger}
          disabled={addMutation.isPending}
        >
          {addMutation.isPending ? (
            <View className="flex items-center justify-center">
              <View className="i-heroicons-arrow-path-20-solid animate-spin w-4 h-4 mr-2" />
              保存中...
            </View>
          ) : (
            '保存'
          )}
        </Button>
      </View>
    </View>
  )
}

export default AddPassengerPage