import { getSupabaseServerClient } from '@kit/supabase/server-client';

import { createModuleBuilderApi } from '@kit/module-builder/api';

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

export default async function ModulesPage({ params }: ModulesPageProps) {
  const { account } = await params;
  const client = getSupabaseServerClient();
  const api = createModuleBuilderApi(client);

  // Get the account ID from slug
  const { data: accountData } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!accountData) {
    return <div>Account not found</div>;
  }

  const modules = await api.modules.listModules(accountData.id);

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Module</h1>
          <p className="text-muted-foreground">
            Verwalten Sie Ihre Datenmodule
          </p>
        </div>
      </div>

      {modules.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <p className="text-muted-foreground">
            Noch keine Module vorhanden. Erstellen Sie Ihr erstes Modul.
          </p>
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {modules.map((module: Record<string, unknown>) => (
            <div
              key={module.id as string}
              className="rounded-lg border p-4 hover:bg-accent/50 transition-colors"
            >
              <h3 className="font-semibold">{String(module.display_name)}</h3>
              {module.description ? (
                <p className="text-sm text-muted-foreground mt-1">
                  {String(module.description)}
                </p>
              ) : null}
              <div className="mt-2 text-xs text-muted-foreground">
                Status: {String(module.status)}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
