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

interface CitySelectProps {
  provinceId?: 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 CitySelect: React.FC<CitySelectProps> = ({
  provinceId,
  value,
  onChange,
  disabled = false,
  required = false,
  placeholder = '选择城市',
  className,
  showLabel = true,
  labelText = '城市',
  'data-testid': testId = 'city-select',
}) => {
  const provinceIdNum = provinceId ? Number(provinceId) : undefined;
  const { data: cities, isLoading } = useCities(provinceIdNum);

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

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

  return (
    <div className={className}>
      {showLabel && (
        <Label htmlFor={testId}>
          {labelText}{required && provinceId && <span className="text-destructive">*</span>}
        </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>
          {cities?.map((city) => (
            <SelectItem key={city.id} value={city.id.toString()}>
              {city.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
};