'use client';

import { useState } from 'react';

import { useQuery, useQueryClient } from '@tanstack/react-query';

import {
  PaginatedData,
  ResponseTable,
  ServerActionResponse,
} from '@kit/doctor/schema/doctor-analysis.schema';
import TableSkeleton from '@kit/shared/components/table-skeleton';
import { Trans } from '@kit/ui/trans';
import { cn } from '@kit/ui/utils';

import ResultsTable from './results-table';

const PAGE_SIZE = 10;

export default function ResultsTableWrapper({
  titleKey,
  action,
  queryKey,
}: {
  titleKey: string;
  action: ({
    page,
    pageSize,
  }: {
    page: number;
    pageSize: number;
  }) => Promise<ServerActionResponse<PaginatedData<ResponseTable>>>;
  queryKey: string;
}) {
  const [page, setPage] = useState(1);

  const {
    data: jobs,
    isLoading,
    isError,
    isFetching,
  } = useQuery({
    queryKey: [queryKey, 'doctor-jobs', page],
    queryFn: async () => await action({ page: page, pageSize: PAGE_SIZE }),
    placeholderData: (previousData) => previousData,
  });

  const queryClient = useQueryClient();

  const onJobUpdate = () => {
    queryClient.invalidateQueries({
      predicate: (query) => query.queryKey.includes('doctor-jobs'),
    });
  };

  const createPageChangeHandler = (setPage: (page: number) => void) => {
    return async ({ page }: { page: number; pageSize: number }) => {
      setPage(page);
      return { success: true, data: null };
    };
  };

  if (isLoading) {
    return (
      <>
        <h3>
          <Trans i18nKey={titleKey} />
        </h3>

        <div className="relative">
          <div
            className={`transition-opacity duration-200 ${
              isFetching ? 'opacity-50' : 'opacity-100'
            }`}
          >
            <TableSkeleton />
          </div>
        </div>
      </>
    );
  }

  if (isError) {
    return (
      <>
        <h3>
          <Trans i18nKey={titleKey} />
        </h3>
        <div className="flex items-center justify-center p-8">
          <div className="text-lg text-red-600">
            <Trans i18nKey="common:genericServerError" />
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <h3>
        <Trans i18nKey={titleKey} />
      </h3>

      <div className="relative">
        <div
          className={cn('opacity-100 transition-opacity duration-200', {
            'opacity-50': isFetching,
          })}
        >
          <ResultsTable
            results={jobs?.data?.data || []}
            pagination={jobs?.data?.pagination}
            fetchAction={createPageChangeHandler(setPage)}
            onJobUpdate={onJobUpdate}
          />
        </div>
      </div>
    </>
  );
}
