'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { AllocationRequestList } from '@/components/requests/allocation-request-list';
import type { AllocRequestListItem } from '@/types/requests';

function AllocationRequestsSkeleton() {
  return (
    <Card>
      <CardContent className="p-6">
        <div className="space-y-4">
          <div className="h-8 w-48 animate-pulse rounded bg-muted" />
          <div className="h-10 w-full animate-pulse rounded bg-muted" />
          <div className="space-y-2">
            {[...Array(5)].map((_, i) => (
              <div
                key={i}
                className="h-12 w-full animate-pulse rounded bg-muted"
              />
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

export default function AllocationRequestsPage() {
  const [requests, setRequests] = useState<AllocRequestListItem[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/allocation-requests')
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then((data) => setRequests(data))
      .catch((err) => setError(err.message));
  }, []);

  return (
    <div>
      <h1 className="mb-6 text-3xl font-bold">Allocation Requests</h1>
      {error ? (
        <Card>
          <CardContent className="p-6 text-center text-destructive">
            Failed to load allocation requests: {error}
          </CardContent>
        </Card>
      ) : requests === null ? (
        <AllocationRequestsSkeleton />
      ) : (
        <AllocationRequestList data={requests} />
      )}
    </div>
  );
}
