import { GraphQLClient, gql } from "graphql-request";
import { useEffect, useState } from "react";

interface Resource {
  id: string;
  name: string;
  description?: string;
  indicator: string;
  scopes: string[];
}

const client = new GraphQLClient(process.env.NEXT_PUBLIC_APP_URL + "/api/graphql");

export default function ResourcesSelector({
  selectedResource,
  onChange,
}: {
  selectedResource: string | null;
  onChange: (id: string | null) => void;
}) {
  const [resources, setResources] = useState<Resource[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    client
      .request<{ resources: Resource[] }>(gql`
        {
          resources {
            id
            name
            indicator
          }
        }
      `)
      .then(data => {
        setResources(data.resources);
        setLoading(false);
      })
      .catch(() => {
        setError("Erreur lors du chargement des ressources");
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Chargement des ressources...</div>;
  if (error) return <div className="text-red-500">{error}</div>;

  return (
    <select
      className="w-full rounded border p-2"
      value={selectedResource || ""}
      onChange={e => onChange(e.target.value || null)}
    >
      <option value="">Aucune ressource</option>
      {resources.map(resource => (
        <option key={resource.id} value={resource.id}>
          {resource.name} ({resource.indicator})
        </option>
      ))}
    </select>
  );
}
