import { Controller, useFormContext, FieldValues, Path } from 'react-hook-form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { FormControl, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { useProvinces } from '../hooks/useAreas';

interface ProvinceSelectFieldProps<T extends FieldValues = FieldValues> {
  name: Path<T>;
  label?: string;
  required?: boolean;
  disabled?: boolean;
  placeholder?: string;
  className?: string;
  'data-testid'?: string;
}

export const ProvinceSelectField = <T extends FieldValues = FieldValues>({
  name,
  label = '省份',
  required = false,
  disabled = false,
  placeholder = '选择省份',
  className,
  'data-testid': testId = 'province-select-field',
}: ProvinceSelectFieldProps<T>) => {
  const { control } = useFormContext<T>();
  const { data: provinces, isLoading } = useProvinces();

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState }) => (
        <FormItem className={className}>
          {label && <FormLabel>{label}{required && <span className="text-destructive">*</span>}</FormLabel>}
          <Select
            value={field.value || ''}
            onValueChange={(value) => {
              field.onChange(value && value !== 'none' ? value : '');
              // 注意：清空依赖字段的逻辑由父组件处理
            }}
            disabled={disabled || isLoading}
          >
            <FormControl>
              <SelectTrigger data-testid={testId}>
                <SelectValue placeholder={isLoading ? '加载中...' : placeholder} />
              </SelectTrigger>
            </FormControl>
            <SelectContent>
              <SelectItem value="none">请选择省份</SelectItem>
              {provinces?.map((province) => (
                <SelectItem key={province.id} value={province.id.toString()}>
                  {province.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {fieldState.error && (
            <FormMessage>{fieldState.error.message}</FormMessage>
          )}
        </FormItem>
      )}
    />
  );
};