import Link from 'next/link';

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

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

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

import { ModuleToggles } from './_components/module-toggles';

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 <AccountNotFound />;
  }

  // Load account features
  const { data: settings } = await client
    .from('account_settings')
    .select('features')
    .eq('account_id', accountData.id)
    .maybeSingle();

  const features = (settings?.features as Record<string, boolean>) ?? {};

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

  return (
    <CmsPageShell
      account={account}
      title="Module"
      description="Verwalten Sie Ihre Datenmodule"
    >
      <div className="flex flex-col gap-8">
        <ModuleToggles accountId={accountData.id} features={features} />

        {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>) => (
              <Link
                key={module.id as string}
                href={`/home/${account}/modules/${module.id as string}`}
                className="block 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>
              </Link>
            ))}
          </div>
        )}
      </div>
    </CmsPageShell>
  );
}
