import { Suspense, useState } from 'react';

import { EVENT_NAMES, ORDER, PAGINATION, STALE_TIME } from '../../constants/define';
import { useQuery, useQueryClient, useMutation } from 'react-query';
import { Button, HStack, Container } from '@chakra-ui/react';
import { isEmpty, isNil } from 'lodash';
import { useMyToast } from '../../hooks';
import CreateCounty from '../../components/counties/CreateCounty';
import CountyTable from '../../components/counties/CountyTable';
import SearchBar from '../../components/common/SearchBar';
const CountyListPage = () => {
  const toast = useMyToast()
  const [search, setSearch] = useState(''),
    [page, setPage] = useState(PAGINATION.PAGE),
    [pageSize, setPageSize] = useState(PAGINATION.PAGE_SIZE),
    [order, setOrder] = useState({
      id: ORDER.ORDER_BY,
      desc: true,
    }),
    queryClient = useQueryClient(),
    [isOpen, setIsOpen] = useState(false);

  // DELETE COUNTY
  const deleteCountyMutation = useMutation(
    (countyId) => {
      // Modify this function to delete a county using the appropriate API endpoint
      return window.grpcAPIs[EVENT_NAMES.COUNTIES.DELETE](countyId.id);
    },
    {
      onSuccess: () => {
        // Invalidate the query for County list to trigger a refresh
        queryClient.invalidateQueries([EVENT_NAMES.COUNTIES.LIST, page, pageSize, search, order?.id, order?.desc]);
        // Optionally, show a success message
        console.log('County deleted successfully');
      },
      onError: (error) => {
        toast({
          title: `${error}`,
          description: 'Failed to delete data', // You can customize the error message here
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
      },
    },
  );

  //  SORT COUNTY
  const handleSort = (value) => {
    setOrder({
      id: value.id,
      desc: !order.desc,
    });
  };
  //  PAGINATION COUNTY
  const hanldePaginationChange = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
    // handleCallApi();
  };

  const handleOnSearchChange = (value) => {
    setSearch(value);
    setPage(PAGINATION.PAGE);
    setPageSize(PAGINATION.PAGE_SIZE);
    setOrder({
      id: ORDER.ORDER_BY,
      desc: true,
    });
  };

  const handleClickCreate = () => {
    setIsOpen(true);
  };

  const createCountyMutation = useMutation(
    (newCounty) => {
      // You can perform the createCounty logic here and return a promise
      return window.grpcAPIs[EVENT_NAMES.COUNTIES.CREATE](newCounty);
    },
    {
      onSuccess: () => {
        setIsOpen(false);
        // Invalidate the query for County list to trigger a refresh
        queryClient.invalidateQueries([EVENT_NAMES.COUNTIES.LIST, page, pageSize, search, order?.id, order?.desc]);
        // Optionally, show a success message
        console.log('County create successfully');
      },
      onError: (error) => {
        toast({
          title: `${error}`,
          description: 'Failed to create data', // You can customize the error message here
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
      },
    },
  );

  const createCounty = (title, description, user) => {
    // Call the mutation to create a new County
    createCountyMutation.mutate({ title, description, managerId: user });
  };

  const { isFetching, isError, data, error } = useQuery({
    queryKey: [EVENT_NAMES.COUNTIES.LIST, page, pageSize, search, order?.id, order?.desc],
    queryFn: () =>
      window.grpcAPIs[EVENT_NAMES.COUNTIES.LIST]({
        search,
        page,
        pageSize,
        orderBy: order?.id,
      }),
    onSuccess: (response) => {
      toast({
        title: 'Success',
        description: data.message,
        status: 'success',
        duration: 5000,
        isClosable: true,
      });
      (response?.data || [])?.forEach((county) => {
        queryClient.setQueryData([EVENT_NAMES.COUNTIES.VIEW, county.id], county);
      });
    },
    onError: (error) => {
      toast({
        title: `${error}`,
        description: 'Failed to List data', // You can customize the error message here
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    },
    staleTime: STALE_TIME,
    placeholderData: {
      data: [],
    },
  });
  // END LIST

  return (
    <>
      <Container maxW="-moz-fit-content" display="flex" flexDir="column" gap="5">
        <HStack>
          <SearchBar onSearch={handleOnSearchChange} />
          <Button colorScheme="primary" onClick={handleClickCreate}>
            Create County
          </Button>
          <CreateCounty
            isCreating={createCountyMutation.isLoading}
            isOpen={isOpen}
            onClose={() => setIsOpen(false)}
            onCreate={createCounty}
          />
        </HStack>
        <Suspense fallback={<>loading</>}>
          <CountyTable
            onSort={handleSort}
            counties={isEmpty(data?.data) || isNil(data?.data) ? [] : data?.data}
            onDelete={deleteCountyMutation.mutate}
            loading={isFetching}
            order={{
              ...(order?.id
                ? {
                    id: order?.id,
                    desc: order?.desc,
                  }
                : {}),
              onOrderBy: handleSort,
            }}
            pagination={{
              currentPage: page,
              pageSize,
              total: data?.total || 0,
              onPaginationChange: hanldePaginationChange,
            }}
          />
        </Suspense>
      </Container>
    </>
  );
};

export default CountyListPage;
