import { createModuleBuilderApi } from '@kit/module-builder/api';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { ListToolbar } from '@kit/ui/list-toolbar';

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

import { FileUploadDialog } from './file-upload-dialog';
import { FilesTable } from './files-table';

interface Props {
  params: Promise<{ account: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

export default async function FilesPage({ params, searchParams }: Props) {
  const { account } = await params;
  const search = await searchParams;
  const client = getSupabaseServerClient();

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

  if (!acct) return <AccountNotFound />;

  const api = createModuleBuilderApi(client);
  const page = Number(search.page) || 1;
  const pageSize = 25;

  const result = await api.files.listFiles(acct.id, {
    search: search.q as string,
    page,
    pageSize,
  });

  // Resolve public URLs for each file
  const filesWithUrls = result.data.map((file) => ({
    id: String(file.id),
    file_name: String(file.file_name),
    original_name: String(file.original_name),
    mime_type: String(file.mime_type),
    file_size: Number(file.file_size),
    created_at: String(file.created_at),
    storage_path: String(file.storage_path),
    publicUrl: api.files.getPublicUrl(String(file.storage_path)),
  }));

  return (
    <CmsPageShell
      account={account}
      title="Dateien"
      description="Dateien hochladen und verwalten"
    >
      <div className="flex flex-col gap-4">
        <div className="flex items-center justify-between gap-4">
          <ListToolbar searchPlaceholder="Datei suchen..." />
          <FileUploadDialog accountId={acct.id} />
        </div>

        <FilesTable
          files={filesWithUrls}
          pagination={{ total: result.total, page, pageSize }}
        />
      </div>
    </CmsPageShell>
  );
}
