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

interface ProvinceSelectProps {
  value?: string | number;
  onChange?: (value: string) => void;
  disabled?: boolean;
  required?: boolean;
  placeholder?: string;
  className?: string;
  showLabel?: boolean;
  labelText?: string;
  'data-testid'?: string;
}

export const ProvinceSelect: React.FC<ProvinceSelectProps> = ({
  value,
  onChange,
  disabled = false,
  required = false,
  placeholder = '选择省份',
  className,
  showLabel = true,
  labelText = '省份',
  'data-testid': testId = 'province-select',
}) => {
  const { data: provinces, isLoading } = useProvinces();

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

  const currentValue = value?.toString() || '';

  return (
    <div className={className}>
      {showLabel && (
        <Label htmlFor={testId}>
          {labelText}{required && <span className="text-destructive">*</span>}
        </Label>
      )}
      <Select
        value={currentValue}
        onValueChange={handleValueChange}
        disabled={disabled || isLoading}
      >
        <SelectTrigger id={testId} data-testid={testId} className={showLabel ? 'mt-1' : ''}>
          <SelectValue placeholder={isLoading ? '加载中...' : placeholder} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="none">请选择省份</SelectItem>
          {provinces?.map((province) => (
            <SelectItem key={province.id} value={province.id.toString()}>
              {province.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
};