import { FiRefreshCw, FiTrash2 } from 'react-icons/fi';
import { useInwinkEventApi } from '../hooks/useInwinkEventApi';
import { useAsync } from '../hooks/useAsync';
import { useToast } from '../hooks/useToast';
import { useConfirm } from '../hooks/useConfirm';
import Spinner from './feedback/Spinner';
import ErrorState from './feedback/ErrorState';
import EmptyState from './feedback/EmptyState';

// Payload de requête de sessions (cf. docs/inwink-api/query.md).
const SESSION_QUERY = {
  selects: { id: true, title: true, status: true, startDate: true, endDate: true },
  orders: [{ desc: true, value: { validFrom: {} } }],
  page: { index: 0, size: 50 },
};

// Composant de test (overlay "test-app") : exerce d'un coup les building blocks
// useAsync (chargement/erreur/annulation), Spinner/ErrorState/EmptyState,
// useToast et useConfirm — et force leur compilation dans le build de test.
export default function EventApiTester() {
  const eventApi = useInwinkEventApi();
  const toast = useToast();
  const confirm = useConfirm();

  const { data, error, isLoading, refetch } = useAsync(
    (signal) =>
      eventApi.post<{ data?: unknown[] }>(
        '/dae274d9-e86e-f011-8dca-0022488a3cad/session/query',
        SESSION_QUERY,
        { signal },
      ),
    [eventApi],
  );

  async function handleFakeDelete() {
    const ok = await confirm({
      title: 'Action de test',
      message: 'Confirmer cette action factice ? (aucune suppression réelle)',
      confirmLabel: 'Confirmer',
    });
    if (ok) toast.success('Action confirmée (démo).');
  }

  if (isLoading) return <Spinner label="Appel de l'API Event…" />;
  if (error) return <ErrorState error={error} onRetry={refetch} />;

  const sessions = data?.data ?? [];

  return (
    <section>
      <button onClick={refetch}>
        <FiRefreshCw aria-hidden />
        Rappeler l'API Event
      </button>
      <button onClick={() => void handleFakeDelete()}>
        <FiTrash2 aria-hidden />
        Action de test (confirm + toast)
      </button>
      {sessions.length === 0 ? (
        <EmptyState message="La requête n'a retourné aucune session." />
      ) : (
        <pre>{JSON.stringify(data, null, 2)}</pre>
      )}
    </section>
  );
}
