import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import DeleteModal from '../../../../components/DeleteModal';
import Table from '../../../../components/Table';
import TableLoading from '../../../../components/TableLoading';
import { useDeleteFilterMutation, useGetFiltersQuery } from '../../../../features/filters/filtersApi';
import { resetFilterState } from '../../../../features/filters/filtersSlice';
import formatISODate from '../../../../utils/formatISODate';
import FilterActions from './FilterActions';

const FiltersTable = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [deleteFilter, { isLoading: deleting }] = useDeleteFilterMutation();
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleteId, setDeleteId] = useState(null);
  const { data, isLoading, isError } = useGetFiltersQuery();

  const handleDelete = async () => {
    if (deleteId) {
      const result = await deleteFilter(deleteId).unwrap();
      if (result.deleted) {
        setShowDeleteModal(false);
        setDeleteId(null);
        toast.success('Filter deleted successfully');
      }
    }
  };

  return (
    <div className='wmx-shadow wmx-rounded-lg wmx-overflow-hidden wmx-border wmx-border-gray-100'>
      <Table>
        <thead className='wmx-bg-white'>
          <tr>
            <Table.Heading className='wmx-pl-4 '>Filter Name</Table.Heading>
            <Table.Heading className='wmx-pl-4 '>Create At</Table.Heading>

            <Table.Heading className='wmx-w-20 wmx-text-center'>Actions</Table.Heading>
          </tr>
        </thead>
        {isLoading ? (
          <TableLoading column={3} row={5} />
        ) : (
          !isError && (
            <tbody className='wmx-divide-y wmx-divide-gray-200 wmx-bg-white'>
              {data?.map((filter) => (
                <tr key={filter.id}>
                  <Table.Data className='wmx-pl-4 wmx-my-auto wmx-py-3'>
                    <button
                      className='wmx-cursor-pointer wmx-font-semibold wmx-text-primary'
                      onClick={() => {
                        navigate(`editor?id=${filter.id}`, { state: { filter } });
                      }}
                    >
                      {filter.name}
                    </button>
                  </Table.Data>
                  <Table.Data className='wmx-pl-4 wmx-my-auto wmx-py-3'>
                    {formatISODate(filter.created_date)}
                  </Table.Data>

                  <Table.Data>
                    <FilterActions filter={filter} setDeleteId={setDeleteId} setShowDeleteModal={setShowDeleteModal} />
                  </Table.Data>
                </tr>
              ))}
            </tbody>
          )
        )}
      </Table>

      <DeleteModal
        isOpen={showDeleteModal}
        setIsOpen={setShowDeleteModal}
        handleDelete={handleDelete}
        isLoading={deleting}
      />

      {isError && (
        <p className='wmx-p-6 wmx-flex wmx-items-center wmx-gap-2 wmx-border-t wmx-border-gray-300 wmx-text-lg wmx-font-medium wmx-bg-white'>
          No Filters Found,
          <button
            className='wmx-text-primary wmx-font-bold wmx-underline wmx-underline-offset-4'
            onClick={() => {
              dispatch(resetFilterState());
              navigate('editor');
            }}
          >
            Add New Filter
          </button>
        </p>
      )}
    </div>
  );
};
export default FiltersTable;
