import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { DisabledPersonSelector } from '@d8d/allin-disability-person-management-ui/components';
import { disabilityClientManager } from '@d8d/allin-disability-person-management-ui/api';
import type { DisabledPersonData } from '@d8d/allin-disability-person-management-ui';
import { X } from 'lucide-react';

interface DisabledPersonSelectorWrapperProps {
  value: number | null;  // personId
  onChange: (value: number | null) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  'data-testid'?: string;
}

/**
 * 残疾人选择器包装组件
 *
 * 提供单选模式的残疾人选择功能，支持显示已选择的残疾人信息
 */
export const DisabledPersonSelectorWrapper: React.FC<DisabledPersonSelectorWrapperProps> = ({
  value,
  onChange,
  placeholder = '请选择残疾人',
  disabled = false,
  className,
  'data-testid': testId,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedPerson, setSelectedPerson] = useState<DisabledPersonData | null>(null);

  // 当 value 变化时，获取残疾人详细信息
  useEffect(() => {
    if (value) {
      // 通过 API 获取残疾人详细信息
      disabilityClientManager.get().getDisabledPerson[':id'].$get({
        param: { id: value },
      }).then(res => {
        if (res.status === 200) {
          return res.json();
        }
        return null;
      }).then(data => {
        if (data) {
          setSelectedPerson(data);
        }
      }).catch(() => {
        // 如果获取失败，清空选择
        setSelectedPerson(null);
      });
    } else {
      setSelectedPerson(null);
    }
  }, [value]);

  // 处理选择残疾人
  const handleSelect = (person: DisabledPersonData | DisabledPersonData[]) => {
    const selected = Array.isArray(person) ? person[0] : person;
    if (selected) {
      setSelectedPerson(selected);
      onChange(selected.id);
    }
  };

  // 处理清除选择
  const handleClear = (e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedPerson(null);
    onChange(null);
  };

  return (
    <div className={className} data-testid={testId}>
      {/* 显示已选择的残疾人信息或选择按钮 */}
      {selectedPerson ? (
        <div className="flex items-center gap-2 p-2 border rounded-md bg-background">
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium truncate">{selectedPerson.name}</div>
            <div className="text-xs text-muted-foreground truncate">
              残疾证号: {selectedPerson.disabilityId}
            </div>
          </div>
          {!disabled && (
            <Button
              type="button"
              variant="ghost"
              size="icon"
              onClick={handleClear}
              className="h-6 w-6 flex-shrink-0"
              data-testid="clear-disabled-person-button"
            >
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>
      ) : (
        <Button
          type="button"
          variant="outline"
          onClick={() => setIsOpen(true)}
          disabled={disabled}
          className="w-full justify-start"
          data-testid="select-disabled-person-button"
        >
          {placeholder}
        </Button>
      )}

      {/* 残疾人选择器对话框 */}
      <DisabledPersonSelector
        open={isOpen}
        onOpenChange={setIsOpen}
        onSelect={handleSelect}
        mode="single"
      />
    </div>
  );
};

export default DisabledPersonSelectorWrapper;
