import React from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/client/components/ui/select';
import { Skeleton } from '@/client/components/ui/skeleton';
import { advertisementTypeClient } from '@/client/api';
import type { InferResponseType } from 'hono/client';

type AdvertisementTypeResponse = InferResponseType<typeof advertisementTypeClient.$get, 200>['data'][0];

interface AdvertisementTypeSelectorProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}

export const AdvertisementTypeSelector: React.FC<AdvertisementTypeSelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择广告类型",
  disabled = false,
  className,
}) => {
  const {
    data: advertisementTypes,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['advertisement-types'],
    queryFn: async () => {
      const res = await advertisementTypeClient.$get();
      if (res.status !== 200) throw new Error('获取广告类型失败');
      return await res.json();
    },
  });

  if (isLoading) {
    return <Skeleton className="h-10 w-full" />;
  }

  if (isError) {
    return (
      <div className="text-sm text-destructive">
        加载广告类型失败
      </div>
    );
  }

  const types = advertisementTypes?.data || [];

  return (
    <Select
      value={value?.toString()}
      onValueChange={(val) => onChange?.(parseInt(val))}
      disabled={disabled || types.length === 0}
    >
      <SelectTrigger className={className}>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {types.map((type) => (
          <SelectItem key={type.id} value={type.id.toString()}>
            {type.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

export default AdvertisementTypeSelector;