'use client';

import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';

import { PageHeader } from '@/components/shared/page-header';
import { TenancyList, type TenancyRow } from '@/components/tenancies/tenancy-list';
import { TableSkeleton } from '@/components/shared/loading-skeleton';
import { apiFetch } from '@/lib/api/client';

interface TenanciesApiResponse {
  data: TenancyRow[];
  pagination: { total: number; page: number; pageSize: number };
}

export function TenanciesListPage() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const { data, isLoading } = useQuery<TenanciesApiResponse>({
    queryKey: ['tenancies', 'list'],
    queryFn: () => apiFetch('/api/v1/tenancies?page=1&limit=100&order=desc'),
  });

  return (
    <div className="flex flex-col gap-6">
      <PageHeader
        eyebrow="Marina"
        title="Tenancies"
        description="All tenancies across all berths"
        actions={
          <Link
            href={`/${portSlug}/berths`}
            className="text-sm text-muted-foreground hover:text-foreground"
          >
            View berths
          </Link>
        }
      />

      {isLoading ? (
        <TableSkeleton />
      ) : (
        <TenancyList
          tenancies={data?.data ?? []}
          showBerth
          portSlug={portSlug}
          emptyMessage="No tenancies found."
        />
      )}
    </div>
  );
}
