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 { useTowns } from '../hooks/useAreas';

interface TownSelectProps {
  districtId?: 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 TownSelect: React.FC<TownSelectProps> = ({
  districtId,
  value,
  onChange,
  disabled = false,
  // required = false,
  placeholder = '选择街道',
  className,
  showLabel = true,
  labelText = '街道',
  'data-testid': testId = 'town-select',
}) => {
  const districtIdNum = districtId ? Number(districtId) : undefined;
  const { data: towns, isLoading } = useTowns(districtIdNum);

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

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

  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>
          {towns?.map((town) => (
            <SelectItem key={town.id} value={town.id.toString()}>
              {town.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
};