import Link from 'next/link';

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

import { createModuleBuilderApi } from '@kit/module-builder/api';
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';

import { decodeFilters } from './_lib/filter-params';
import { ModuleRecordsTable } from './module-records-table';
import { ModuleSearchBar } from './module-search-bar';

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

export default async function ModuleDetailPage({
  params,
  searchParams,
}: ModuleDetailPageProps) {
  const { account, moduleId } = await params;
  const search = await searchParams;
  const client = getSupabaseServerClient();
  const t = await getTranslations('cms.modules');
  const api = createModuleBuilderApi(client);

  const moduleWithFields = await api.modules.getModuleWithFields(moduleId);

  if (!moduleWithFields) {
    return <AccountNotFound />;
  }

  const page = Number(search.page) || 1;
  const pageSize =
    Number(search.pageSize) || moduleWithFields.default_page_size || 25;

  const sortField =
    (search.sort as string) ?? moduleWithFields.default_sort_field ?? undefined;
  const sortDirection =
    (search.dir as 'asc' | 'desc') ??
    (moduleWithFields.default_sort_direction as 'asc' | 'desc') ??
    'asc';

  const filters = decodeFilters(search.f as string | undefined);

  const result = await api.query.query({
    moduleId,
    page,
    pageSize,
    sortField,
    sortDirection,
    search: (search.q as string) ?? undefined,
    filters: filters as Array<{
      field: string;
      operator:
        | 'eq'
        | 'neq'
        | 'gt'
        | 'gte'
        | 'lt'
        | 'lte'
        | 'like'
        | 'is_null'
        | 'not_null';
      value?: string;
    }>,
  });

  const allFields = moduleWithFields.fields;

  const records = (result.data ?? []).map((row: Record<string, unknown>) => ({
    id: String(row.id ?? ''),
    data: (row.data ?? {}) as Record<string, unknown>,
    status: String(row.status ?? 'active'),
    created_at: String(row.created_at ?? ''),
    updated_at: String(row.updated_at ?? ''),
  }));

  return (
    <CmsPageShell
      account={account}
      title={String(moduleWithFields.display_name)}
      description={moduleWithFields.description ?? undefined}
    >
      <div className="flex flex-col gap-4">
        <div className="flex items-center justify-between">
          <div>
            {moduleWithFields.description && (
              <p className="text-muted-foreground">
                {moduleWithFields.description}
              </p>
            )}
          </div>
          <Button asChild>
            <Link href={`/home/${account}/modules/${moduleId}/new`}>
              <Plus className="mr-2 h-4 w-4" />
              {t('newRecord')}
            </Link>
          </Button>
        </div>

        <ModuleSearchBar fields={allFields} />

        <ModuleRecordsTable
          fields={allFields}
          records={records}
          pagination={result.pagination}
          account={account}
          moduleId={moduleId}
          currentSort={
            sortField
              ? { field: sortField, direction: sortDirection }
              : undefined
          }
        />
      </div>
    </CmsPageShell>
  );
}
