import { usePagination } from '@/hooks/usePagination';
import {
  useCreateCityMutation,
  useDeleteCityMutation,
  useGetCitiesQuery,
  useUpdateCityMutation,
} from '@/redux/api/master/location/cityApi';
import { City } from '@/types/city';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';

type initialCitiesType = {
  results: City[];
  totalResults: number;
};

export type dialogueType = { type: 'add' | 'edit' | 'delete'; id: string } | null;
const useCity = (searchParams: { page?: string; limit?: string; search?: string }) => {
  const [dialogueType, setDialogueType] = useState<dialogueType | null>(null);
  const [deleteCity, { isLoading: isDeleting }] = useDeleteCityMutation();
  const [createCity, { isLoading: isCreating }] = useCreateCityMutation();
  const [updateCity, { isLoading: isUpdating }] = useUpdateCityMutation();

  const methods = useForm({ defaultValues: { searchQuery: '' } });
  const { control, watch } = methods;
  const searchQuery = watch('searchQuery');
  const {
    data: citiesData,
    error,
    isLoading,
    isFetching,
  } = useGetCitiesQuery({
    page: parseInt(searchParams.page || '1'),
    limit: parseInt(searchParams.limit || '10'),
    search: searchQuery,
  });

  const filteredCities = citiesData?.data?.results.filter((city) =>
    city.name.toLowerCase().includes(searchQuery.toLowerCase()),
  );

  const handleDeleteConfirm = async () => {
    try {
      //   setDialogueType({ type: 'delete', id });
      //TODO: call delete API
    } catch (error) {
      console.error('Delete failed:', error);
    }
  };

  const handleEditConfirm = async (id: string) => {
    try {
      //   setDialogueType({ type: 'edit', id });
      //TODO: call delete API
    } catch (error) {
      console.error('Delete failed:', error);
    }
  };

  const handleAddConfirm = async (id: string) => {
    try {
      //TODO: call app API
      //   setDialogueType({ type: 'edit', id });
    } catch (error) {
      console.error('Delete failed:', error);
    }
  };

  const {
    currentPage,
    recordsPerPage,
    totalPages,
    startIndex,
    endIndex,
    handlePreviousPage,
    handleNextPage,
    handleRecordsPerPageChange,
  } = usePagination(citiesData?.data.totalResults || 0, 10);
  return {
    filteredCities,
    pagination: {
      currentPage,
      recordsPerPage,
      totalPages,
      startIndex,
      endIndex,
      handlePreviousPage,
      handleNextPage,
      handleRecordsPerPageChange,
    },
    dialogueType,
    setDialogueType,
    control,
    handleDeleteConfirm,
    handleEditConfirm,
    handleAddConfirm,
    totalRecords: citiesData?.data.totalResults || 0,
  };
};

export default useCity;
