import { createFileRoute } from '@tanstack/react-router';
import { z } from 'zod';

import { AccessDenied } from '@/app/components/layout/access-denied';
import { DataTable } from '@/app/components/ui/data-table/data-table';
import { SearchInput } from '@/app/components/ui/forms/search-input';
import { AutomationsActionMenu } from '@/app/features/automations/components/automations-action-menu';
import { AutomationsTable } from '@/app/features/automations/components/automations-table';
import type { AutomationTableItem } from '@/app/features/automations/components/automations-table';
import { workflowListKey } from '@/app/features/automations/hooks/file-queries';
import { useAutomationsTableConfig } from '@/app/features/automations/hooks/use-automations-table-config';
import { useAbility, useAbilityLoading } from '@/app/hooks/use-ability';
import { api } from '@/convex/_generated/api';
import { useT } from '@/lib/i18n/client';
import { seo } from '@/lib/utils/seo';

const searchSchema = z.object({
  folder: z.string().optional(),
});

export const Route = createFileRoute('/dashboard/$id/automations/')({
  head: () => ({
    meta: seo('automations'),
  }),
  validateSearch: searchSchema,
  loader: ({ context, params }) => {
    // Warm the workflows list (filesystem-backed action) so the table paints
    // without a skeleton on first nav. AutomationsTable mounts
    // useListWorkflows(orgId, 'installed'); match that key + args.
    void context.queryClient.prefetchQuery({
      queryKey: workflowListKey(params.id, 'installed'),
      queryFn: () =>
        context.convexQueryClient.convexClient.action(
          api.workflows.file_actions.listWorkflows,
          { organizationId: params.id, filter: 'installed' },
        ),
      staleTime: Infinity,
      retry: false,
    });
  },
  component: AutomationsPage,
});

function AutomationsPage() {
  const { id: organizationId } = Route.useParams();
  const { folder } = Route.useSearch();
  const { t } = useT('accessDenied');
  const { t: tAutomations } = useT('automations');

  const ability = useAbility();
  const abilityLoading = useAbilityLoading();
  const { columns, searchPlaceholder } =
    useAutomationsTableConfig(organizationId);

  if (abilityLoading) {
    // The DataTable renders its own loading skeleton; mirror AutomationsTable's
    // header so the layout doesn't shift once the ability check resolves.
    return (
      <div className="flex flex-col gap-4 p-4">
        <div className="flex items-center justify-between gap-4">
          <SearchInput
            wrapperClassName="w-full max-w-sm"
            placeholder={searchPlaceholder}
            aria-label={searchPlaceholder}
            value=""
            onChange={() => {}}
            readOnly
          />
          <AutomationsActionMenu organizationId={organizationId} />
        </div>
        <DataTable<AutomationTableItem>
          columns={columns}
          data={[]}
          isLoading
          approxRowCount={5}
          infiniteScroll={{
            hasMore: false,
            onLoadMore: () => {},
            entityLabel: tAutomations('entityLabel'),
            totalCount: 0,
          }}
        />
      </div>
    );
  }

  if (ability.cannot('write', 'wfDefinitions')) {
    return <AccessDenied message={t('automations')} />;
  }

  return (
    <AutomationsTable organizationId={organizationId} currentFolder={folder} />
  );
}
