import React from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { useDistricts } from '../hooks/useAreas';

interface DistrictSelectProps {
  cityId?: string | number;
  value?: string | number;
  onChange?: (value: string) => void;
  disabled?: boolean;
  // required?: boolean; // 区县字段通常不是必填的
  placeholder?: string;
  className?: string;
  showLabel?: boolean;
  labelText?: string;
  'data-testid'?: string;
}

export const DistrictSelect: React.FC<DistrictSelectProps> = ({
  cityId,
  value,
  onChange,
  disabled = false,
  // required = false,
  placeholder = '选择区县',
  className,
  showLabel = true,
  labelText = '区县',
  'data-testid': testId = 'district-select',
}) => {
  const cityIdNum = cityId ? Number(cityId) : undefined;
  const { data: districts, isLoading } = useDistricts(cityIdNum);

  const handleValueChange = (newValue: string) => {
    onChange?.(newValue && newValue !== 'none' ? newValue : '');
  };

  const currentValue = value?.toString() || '';
  const isDisabled = disabled || isLoading || !cityId;

  return (
    <div className={className}>
      {showLabel && (
        <Label htmlFor={testId}>
          {labelText}
        </Label>
      )}
      <Select
        value={currentValue}
        onValueChange={handleValueChange}
        disabled={isDisabled}
      >
        <SelectTrigger id={testId} data-testid={testId} className={showLabel ? 'mt-1' : ''}>
          <SelectValue placeholder={isLoading ? '加载中...' : isDisabled ? '请先选择城市' : placeholder} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="none">请选区县</SelectItem>
          {districts?.map((district) => (
            <SelectItem key={district.id} value={district.id.toString()}>
              {district.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
};