import { Controller, useFormContext, FieldValues, Path, useWatch } 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 { useCities } from '../hooks/useAreas';

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

export const CitySelectField = <T extends FieldValues = FieldValues>({
  name,
  provinceName,
  label = '城市',
  required = false,
  disabled = false,
  placeholder = '选择城市',
  className,
  'data-testid': testId = 'city-select-field',
}: CitySelectFieldProps<T>) => {
  const { control } = useFormContext<T>();
  const provinceValue = useWatch({ control, name: provinceName });
  const provinceId = provinceValue ? Number(provinceValue) : undefined;

  const { data: cities, isLoading } = useCities(provinceId);

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState }) => {
        const isDisabled = disabled || isLoading || !provinceValue;

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