import Link from 'next/link';

import { getTranslations } from 'next-intl/server';

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

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

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

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

export default async function ModulesPage({ params }: ModulesPageProps) {
  const { account } = await params;
  const t = await getTranslations('cms.modules');
  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={t('title')}
      description={t('description')}
    >
      <div className="flex flex-col gap-8">
        <ModuleToggles accountId={accountData.id} features={features} />

        {modules.length === 0 ? (
          <EmptyState
            title={t('noModules')}
            description={t('createFirstModule')}
          />
        ) : (
          <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="hover:bg-accent/50 block rounded-lg border p-4 transition-colors"
              >
                <h3 className="font-semibold">{String(module.display_name)}</h3>
                {module.description ? (
                  <p className="text-muted-foreground mt-1 text-sm">
                    {String(module.description)}
                  </p>
                ) : null}
                <div className="text-muted-foreground mt-2 text-xs">
                  {String(module.status)}
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </CmsPageShell>
  );
}
