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

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

export const TownSelectField = <T extends FieldValues = FieldValues>({
  name,
  districtName,
  label = '街道',
  // required = false,
  disabled = false,
  placeholder = '选择街道',
  className,
  'data-testid': testId = 'town-select-field',
}: TownSelectFieldProps<T>) => {
  const { control } = useFormContext<T>();
  const districtValue = useWatch({ control, name: districtName });
  const districtId = districtValue ? Number(districtValue) : undefined;

  const { data: towns, isLoading } = useTowns(districtId);

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

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