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

interface DistrictSelectFieldProps<T extends FieldValues = FieldValues> {
  name: Path<T>;
  cityName: Path<T>;
  label?: string;
  // required?: boolean; // 区县字段通常不是必填的
  disabled?: boolean;
  placeholder?: string;
  className?: string;
  'data-testid'?: string;
}

export const DistrictSelectField = <T extends FieldValues = FieldValues>({
  name,
  cityName,
  label = '区县',
  // required = false,
  disabled = false,
  placeholder = '选择区县',
  className,
  'data-testid': testId = 'district-select-field',
}: DistrictSelectFieldProps<T>) => {
  const { control } = useFormContext<T>();
  const cityValue = useWatch({ control, name: cityName });
  const cityId = cityValue ? Number(cityValue) : undefined;

  const { data: districts, isLoading } = useDistricts(cityId);

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

        return (
          <FormItem className={className}>
            {label && <FormLabel>{label}</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>
                {districts?.map((district) => (
                  <SelectItem key={district.id} value={district.id.toString()}>
                    {district.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {fieldState.error && (
              <FormMessage>{fieldState.error.message}</FormMessage>
            )}
          </FormItem>
        );
      }}
    />
  );
};