import Link from 'next/link';

import { Plus } from 'lucide-react';

import { createFischereiApi } from '@kit/fischerei/api';
import {
  FischereiTabNavigation,
  PermitsDataTable,
} from '@kit/fischerei/components';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Button } from '@kit/ui/button';

import { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';

interface Props {
  params: Promise<{ account: string }>;
}

export default async function PermitsPage({ params }: Props) {
  const { account } = await params;
  const client = getSupabaseServerClient();

  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!acct) return <AccountNotFound />;

  const api = createFischereiApi(client);
  const permits = await api.listPermits(acct.id);

  return (
    <CmsPageShell account={account} title="Fischerei - Erlaubnisscheine">
      <FischereiTabNavigation account={account} activeTab="permits" />
      <div className="flex w-full flex-col gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold">Erlaubnisscheine</h1>
            <p className="text-muted-foreground">
              Erlaubnisscheine und Gewässerkarten verwalten
            </p>
          </div>
          <Link href={`/home/${account}/fischerei/permits/new`}>
            <Button size="sm" data-test="permits-new-btn">
              <Plus className="mr-2 h-4 w-4" />
              Neuer Erlaubnisschein
            </Button>
          </Link>
        </div>
        <PermitsDataTable
          data={permits as Array<Record<string, unknown>>}
          accountId={acct.id}
        />
      </div>
    </CmsPageShell>
  );
}
