import { useFormContext, FieldValues, Path } from 'react-hook-form';
import { FormDescription, FormLabel } from '@d8d/shared-ui-components/components/ui/form';
import { ProvinceSelectField } from '../form/ProvinceSelectField';
import { CitySelectField } from '../form/CitySelectField';
import { DistrictSelectField } from '../form/DistrictSelectField';

interface AreaSelectFormProps<T extends FieldValues = FieldValues> {
  provinceName: Path<T>;
  cityName: Path<T>;
  districtName?: Path<T>;
  label?: string;
  description?: string;
  required?: boolean;
  disabled?: boolean;
  className?: string;
  testIdPrefix?: string;
}

export const AreaSelectForm = <T extends FieldValues = FieldValues>({
  provinceName,
  cityName,
  districtName,
  label = '地区选择',
  description,
  required = false,
  disabled = false,
  className,
  testIdPrefix = 'area-select'
}: AreaSelectFormProps<T>) => {
  // 从上下文中获取表单控制
  const formContext = useFormContext<T>();
  const control = formContext?.control;

  if (!control) {
    console.error('AreaSelectForm: 缺少 react-hook-form 上下文');
    return null;
  }

  // 注意：清理逻辑现在由各个表单字段组件内部的Controller处理
  // 省份变化时会自动清空城市和区县字段
  // 城市变化时会自动清空区县字段

  return (
    <div className={className} data-testid={testIdPrefix}>
      {label && (
        <FormLabel>
          {label}{required && <span className="text-destructive">*</span>}
        </FormLabel>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-2">
        <ProvinceSelectField
          name={provinceName}
          label="省份"
          required={required}
          disabled={disabled}
          placeholder="选择省份"
          data-testid={`${testIdPrefix}-province`}
          // 注意：这里不能直接传递onValueChange，因为Controller已经处理了
        />

        <CitySelectField
          name={cityName}
          provinceName={provinceName}
          label="城市"
          required={required}
          disabled={disabled}
          placeholder="选择城市"
          data-testid={`${testIdPrefix}-city`}
        />

        {districtName && (
          <DistrictSelectField
            name={districtName}
            cityName={cityName}
            label="区县"
            disabled={disabled}
            placeholder="选择区县"
            data-testid={`${testIdPrefix}-district`}
          />
        )}
      </div>

      {description && (
        <FormDescription className="mt-2">
          {description}
        </FormDescription>
      )}
    </div>
  );
};