import { useQuery } from '@tanstack/react-query';
import { Switch } from '@/components/ui/switch';
import { useClient } from 'hooks/useClient';
import { useServerSettings } from 'state/useServerSettings';

type PluginInfo = {
  id: string;
  name: string;
  description: string;
  enabled: boolean;
};

export const PluginsSection = () => {
  const client = useClient();
  const { plugins, saveSettings } = useServerSettings();

  const { data: pluginList } = useQuery({
    queryKey: ['PLUGINS_LIST'],
    queryFn: () => client.get<PluginInfo[]>('/server-settings/plugins'),
  });

  const togglePlugin = (id: string, enabled: boolean) => {
    saveSettings({ plugins: { ...plugins, [id]: enabled } });
  };

  return (
    <div className="flex flex-col gap-4">
      {pluginList?.map((p: PluginInfo) => (
        <div key={p.id} className="flex items-center justify-between gap-4">
          <div>
            <div className="text-sm font-medium text-duck-dark">{p.name}</div>
            <div className="text-xs text-duck-dark/50">{p.description}</div>
          </div>
          <Switch checked={plugins?.[p.id] !== false} onCheckedChange={(checked) => togglePlugin(p.id, !!checked)} />
        </div>
      ))}
    </div>
  );
};
