import { useState, useEffect } from 'react'
import { View, Text } from '@tarojs/components'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

interface CancelReasonDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onConfirm: (reason: string) => void
  loading?: boolean
}

// 预定义的取消原因选项
const CANCEL_REASONS = [
  '我不想买了',
  '信息填写错误，重新下单',
  '商家缺货',
  '价格不合适',
  '其他原因'
]

export default function CancelReasonDialog({
  open,
  onOpenChange,
  onConfirm,
  loading = false
}: CancelReasonDialogProps) {
  const [reason, setReason] = useState('')
  const [selectedReason, setSelectedReason] = useState('')
  const [error, setError] = useState('')

  // 当对话框打开时重置状态
  useEffect(() => {
    if (open) {
      handleReset()
    }
  }, [open])

  // 处理原因选择
  const handleReasonSelect = (reasonText: string) => {
    setSelectedReason(reasonText)
    setReason(reasonText)
    if (error) setError('')
  }

  // 处理自定义原因输入
  const handleCustomReasonChange = (value: string, event: any) => {
    setReason(value)
    if (value && !CANCEL_REASONS.includes(value)) {
      setSelectedReason('')
    }
    if (error) setError('')
  }

  // 确认取消
  const handleConfirm = () => {
    const trimmedReason = reason.trim()

    if (!trimmedReason) {
      setError('请输入取消原因')
      return
    }

    if (trimmedReason.length < 2) {
      setError('取消原因至少需要2个字符')
      return
    }

    if (trimmedReason.length > 200) {
      setError('取消原因不能超过200个字符')
      return
    }

    setError('')
    onConfirm(trimmedReason)
  }

  // 重置对话框状态
  const handleReset = () => {
    setReason('')
    setSelectedReason('')
    setError('')
  }

  // 处理取消
  const handleCancel = () => {
    handleReset()
    onOpenChange(false)
  }

  const handleOpenChange = (newOpen: boolean) => {
    if (!newOpen) {
      handleReset()
    }
    onOpenChange(newOpen)
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>取消订单</DialogTitle>
          <DialogDescription>
            请选择或填写取消原因，这将帮助我们改进服务
          </DialogDescription>
        </DialogHeader>

        <View className="grid gap-4 py-4">
          {/* 预定义原因选项 */}
          <View className="space-y-2">
            {CANCEL_REASONS.map((reasonText) => (
              <View
                key={reasonText}
                data-testid={`cancel-reason-${reasonText}`}
                className={`px-3 py-2 rounded border cursor-pointer transition-colors select-none ${
                  selectedReason === reasonText
                    ? 'border-primary bg-primary/10'
                    : 'border-gray-300 bg-white hover:bg-gray-50'
                }`}
                onClick={() => handleReasonSelect(reasonText)}
              >
                <Text
                  className={`text-sm ${
                    selectedReason === reasonText
                      ? 'text-primary'
                      : 'text-gray-700'
                  }`}
                >
                  {reasonText}
                </Text>
              </View>
            ))}
          </View>

          {/* 自定义原因输入 */}
          <View className="grid grid-cols-4 items-center gap-4">
            <Label htmlFor="reason" className="text-right">
              其他原因
            </Label>
            <View className="col-span-3">
              <Input
                id="reason"
                placeholder="请输入其他取消原因..."
                value={reason}
                onChange={handleCustomReasonChange}
                className={error ? 'border-destructive' : ''}
              />
              {error && (
                <Text className="text-sm text-destructive mt-1">{error}</Text>
              )}
            </View>
          </View>
        </View>

        <DialogFooter>
          <Button variant="outline" onClick={handleCancel} disabled={loading}>
            取消
          </Button>
          <Button onClick={handleConfirm} disabled={loading} data-testid="confirm-cancel-button">
            {loading ? '提交中...' : '确认取消'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}