import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Check, ChevronsUpDown, X } from 'lucide-react';
import type { InferResponseType } from 'hono/client';

import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@d8d/shared-ui-components/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@d8d/shared-ui-components/components/ui/popover';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { cn } from '@d8d/shared-ui-components/utils';
import { goodsClient, goodsClientManager } from '../api/goodsClient';

interface GoodsChildSelectorProps {
  value?: number[];
  onChange?: (value: number[]) => void;
  parentGoodsId?: number;
  tenantId?: number;
  disabled?: boolean;
  placeholder?: string;
}

type GoodsResponse = InferResponseType<typeof goodsClient.index.$get, 200>['data'][0];

export const GoodsChildSelector: React.FC<GoodsChildSelectorProps> = ({
  value = [],
  onChange,
  parentGoodsId,
  tenantId,
  disabled = false,
  placeholder = '选择子商品...'
}) => {
  const [open, setOpen] = useState(false);
  const [selectedGoods, setSelectedGoods] = useState<GoodsResponse[]>([]);
  const [searchQuery, setSearchQuery] = useState('');

  // 获取商品列表
  const { data: goodsData, isLoading } = useQuery({
    queryKey: ['goods', 'child-selector', searchQuery, tenantId],
    queryFn: async () => {
      const res = await goodsClientManager.get().index.$get({
        query: {
          page: 1,
          pageSize: 50,
          keyword: searchQuery
        }
      });
      if (res.status !== 200) throw new Error('获取商品列表失败');
      const result = await res.json();
      return result.data || [];
    },
    enabled: !disabled
  });

  // 过滤可选的商品
  const availableGoods = React.useMemo(() => {
    if (!goodsData) return [];

    return goodsData.filter((goods: GoodsResponse) => {
      // 排除自己
      if (parentGoodsId && goods.id === parentGoodsId) return false;

      // 排除已经是子商品的商品（spuId > 0）
      if (goods.spuId > 0) return false;

      // 排除已经是父商品的商品（有子商品的商品）
      // 这里需要后端API支持查询某个商品的子商品数量
      // 暂时先不过滤

      return true;
    });
  }, [goodsData, parentGoodsId]);

  // 初始化选中的商品
  useEffect(() => {
    if (value && value.length > 0 && goodsData) {
      const selected = goodsData.filter((goods: GoodsResponse) =>
        value.includes(goods.id)
      );
      setSelectedGoods(selected);
    } else {
      setSelectedGoods([]);
    }
  }, [value, goodsData]);

  const handleSelect = (goods: GoodsResponse) => {
    const newSelected = [...selectedGoods, goods];
    setSelectedGoods(newSelected);
    if (onChange) {
      onChange(newSelected.map(g => g.id));
    }
    setSearchQuery('');
  };

  const handleRemove = (goodsId: number) => {
    const newSelected = selectedGoods.filter(g => g.id !== goodsId);
    setSelectedGoods(newSelected);
    if (onChange) {
      onChange(newSelected.map(g => g.id));
    }
  };

  const handleClear = () => {
    setSelectedGoods([]);
    if (onChange) {
      onChange([]);
    }
  };

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap gap-2 mb-2">
        {selectedGoods.map((goods) => (
          <Badge key={goods.id} variant="secondary" className="px-2 py-1">
            {goods.name}
            <button
              type="button"
              onClick={() => handleRemove(goods.id)}
              className="ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
            >
              <X className="h-3 w-3" />
            </button>
          </Badge>
        ))}
      </div>

      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            role="combobox"
            aria-expanded={open}
            className="w-full justify-between"
            disabled={disabled}
          >
            <span className="truncate">
              {selectedGoods.length > 0
                ? `已选择 ${selectedGoods.length} 个子商品`
                : placeholder}
            </span>
            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-full p-0" align="start">
          <Command>
            <CommandInput
              placeholder="搜索商品名称..."
              value={searchQuery}
              onValueChange={setSearchQuery}
            />
            <CommandList>
              <CommandEmpty>
                {isLoading ? '加载中...' : '未找到商品'}
              </CommandEmpty>
              <CommandGroup>
                {availableGoods.map((goods: GoodsResponse) => {
                  const isSelected = selectedGoods.some(g => g.id === goods.id);
                  return (
                    <CommandItem
                      key={goods.id}
                      value={goods.name}
                      onSelect={() => handleSelect(goods)}
                      disabled={isSelected}
                    >
                      <Check
                        className={cn(
                          "mr-2 h-4 w-4",
                          isSelected ? "opacity-100" : "opacity-0"
                        )}
                      />
                      <div className="flex-1">
                        <div className="font-medium">{goods.name}</div>
                        <div className="text-xs text-muted-foreground">
                          价格: ¥{goods.price.toFixed(2)} | 库存: {goods.stock}
                        </div>
                      </div>
                      {isSelected && (
                        <Badge variant="outline" className="ml-2">
                          已选择
                        </Badge>
                      )}
                    </CommandItem>
                  );
                })}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>

      {selectedGoods.length > 0 && (
        <div className="flex justify-end">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={handleClear}
            disabled={disabled}
          >
            清空选择
          </Button>
        </div>
      )}

      <div className="text-xs text-muted-foreground">
        <p>• 只能选择同一租户下的商品</p>
        <p>• 不能选择自己作为子商品</p>
        <p>• 不能选择已经是子商品的商品</p>
        {parentGoodsId && (
          <p>• 当前父商品ID: {parentGoodsId}</p>
        )}
      </div>
    </div>
  );
};