import { useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { ColumnDef } from '@tanstack/react-table';
import { toast } from 'sonner';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { DataTable } from '@/components/Forms/FormsDataTable/DataTable';
// import useTitle from '../hooks/useTitle';
import { Checkbox } from '@/components/ui/checkbox';
import { DataTableColumnHeader } from '@/components/Forms/FormsDataTable/DataTableColumnHeader';
import { Switch } from '@/components/ui/switch';
import DataTableRowActions from '@/components/Forms/DataTableRowActions';
import Error from '@/pages/Errors';
import DataTableShimmer from '@/components/Forms/FormsDataTable/DataTableShimmer';
import {
useDeleteFormsMutation,
useGetAllFormsQuery,
useUpdateIsActiveMutation,
} from '@/app/backend/endpoints/forms';
dayjs.extend(relativeTime);
interface FormsResponseType extends PaginatedResponseType {
forms: FormType[];
}
export default function Forms() {
// useTitle('My Forms | Form Builder');
const [searchParams] = useSearchParams();
const params: seachParamsType = {
page: parseInt(searchParams.get('page') ?? '0'),
pageSize: parseInt(searchParams.get('pageSize') ?? '10'),
sort: searchParams.get('sort') || '-createdAt',
search: searchParams.get('query'),
};
const {
data: dataWrap,
isLoading,
isError,
isFetching,
} = useGetAllFormsQuery(params);
const data = dataWrap?.data as FormsResponseType;
const [update, { isLoading: isUpdating }] = useUpdateIsActiveMutation();
const mutation = ({
formId,
isActive,
}: {
formId: string;
isActive: boolean;
}) => {
update({
formId: formId as string,
data: { isActive },
})
.unwrap()
.then(() => {
toast.success('Form updated successfully');
})
.catch(() => {
toast.error('Error updating form');
});
};
const [deleteForms, { isLoading: isDeleting }] = useDeleteFormsMutation();
const bulkDeleteMutation = (forms: string[]) => {
deleteForms(forms)
.unwrap()
.then(() => {
toast.success('Forms deleted successfully');
})
.catch(() => {
toast.error('Error deleting forms');
});
};
const columns: ColumnDef<FormType>[] = useMemo(
() => [
{
id: 'select',
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) =>
table.toggleAllPageRowsSelected(!!value)
}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
onClick={(e) => e.stopPropagation()}
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: 'isActive',
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Status" />
),
cell: ({ row }) => (
<Switch
checked={row.original.isActive}
disabled={
isUpdating
// &&
// mutation.variables?.formId === row.original._id
}
onCheckedChange={(checked) => {
mutation({ formId: row.original._id, isActive: checked });
}}
onClick={(e) => e.stopPropagation()}
/>
),
},
{
accessorKey: 'name',
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Form Name" />
),
},
{
accessorKey: 'createdAt',
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Created Date" />
),
cell: ({ row }) => (
<span>{dayjs(row.original.createdAt).format('MMM D, YYYY')}</span>
),
},
{
accessorKey: 'updatedAt',
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Last Updated" />
),
cell: ({ row }) => (
<span>{dayjs(row.original.updatedAt).fromNow()}</span>
),
},
{
id: 'actions',
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Actions" />
),
cell: ({ row }) => (
<DataTableRowActions
formId={row.original._id}
formName={row.original.name}
/>
),
},
],
[mutation]
);
if (isLoading) return <DataTableShimmer columns={4} />;
if (isError) return <Error fullScreen={false} />;
return (
<DataTable<FormType, string>
columns={columns}
data={data?.forms}
totalEntries={data.total}
isFetching={isFetching}
bulkDeleteHandler={(forms) => {
bulkDeleteMutation(forms);
}}
bulkDeleteIsLoading={isDeleting}
// clickHandler={(formId) => {
// window.open(window.location.origin + '/forms/' + formId, '_blank');
// }}
/>
);
}