import { Await, createLazyFileRoute, getRouteApi, useNavigate } from '@tanstack/react-router';
import { Suspense, useEffect, useState } from 'react';
import CommonPageHeader from '@/components/custom/page/commonPage';
import UsersSubscriptionFilter from '@/components/custom/usersSubscription/filters';
import UsersSubscriptionTableBody from '@/components/custom/usersSubscription/tableBody';
import { Table, TableBody } from '@/components/ui/table';
import TableHeaderColumn from '@/components/custom/table/header';
import TableDataLoadingState from '@/components/custom/table/bodyLoadingState';
import { useDebounce } from '@/utils/useDebounce.hook';
import { SubscriptionStatus } from '@/apis/common/types';
import Pagination from '@/components/custom/table/pagination';
import { usersSubscriptionTableHeaders } from '@/static/tables/usersSubscripionTable';

export const Route = createLazyFileRoute('/_authenticated/users-subscription')({
  component: SurveyResponses,
});

const routeApi = getRouteApi('/_authenticated/users-subscription/');

function SurveyResponses() {
  const { usersSubscriptionData } = routeApi.useLoaderData();
  const routeSearch = routeApi.useSearch();

  const [email, setEmail] = useState<string | undefined>(() => routeSearch.email);
  const [status, setStatus] = useState<SubscriptionStatus | undefined>(() => routeSearch.status);
  const [page, setPage] = useState<number>(() => routeSearch.page || 1);
  const [totalPages, setTotalPages] = useState<number>(1);

  const debouncedEmail = useDebounce(email, 1000);

  const navigate = useNavigate({ from: '/users-subscription' });

  const onClearFilter = () => {
    setEmail(undefined);
    setStatus(undefined);
    setPage(1);
  };

  const refreshData = () => {
    const search: any = { page, status };

    if (debouncedEmail) search.email = debouncedEmail;

    if (routeSearch.email !== search.email || routeSearch.status !== search.status) {
      setPage(1);
    } else {
      search.page = page;
    }

    navigate({
      to: '/users-subscription/',
      search,
    });
  };

  useEffect(() => {
    refreshData();
  }, [debouncedEmail, status, page]);

  return (
    <div className="bg-gray-50">
      <CommonPageHeader />
      <UsersSubscriptionFilter
        email={email}
        setEmail={setEmail}
        status={status}
        setStatus={setStatus}
        onClearFilter={onClearFilter}
      />
      <div className="rounded-md bg-white border mx-4">
        <Table>
          <TableHeaderColumn columnData={usersSubscriptionTableHeaders} />
          <TableBody>
            <Suspense
              fallback={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((num) => (
                <TableDataLoadingState key={num} columnData={usersSubscriptionTableHeaders} />
              ))}
            >
              <Await promise={usersSubscriptionData}>
                {(data) => {
                  setTotalPages(data.data.totalPages);
                  return (
                    <>
                      <UsersSubscriptionTableBody data={data.data.responseData} refreshData={refreshData} />
                    </>
                  );
                }}
              </Await>
            </Suspense>
          </TableBody>
        </Table>
      </div>
      <Pagination page={page} setPages={setPage} totalPages={totalPages} />
    </div>
  );
}
