import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogContent,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogOverlay,
  Button,
} from "@chakra-ui/react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import React from "react"
import { useForm } from "react-hook-form"

import { ItemsService, UsersService, ClientMessagesService, AboutUsService, CoursesService, ImageService, Info_imageService, secheduleService, OrganService } from "../../client"
import useCustomToast from "../../hooks/useCustomToast"

interface DeleteProps {
  type: string
  id: string
  isOpen: boolean
  onClose: () => void
}

const Delete = ({ type, id, isOpen, onClose }: DeleteProps) => {
  const queryClient = useQueryClient()
  const showToast = useCustomToast()
  const cancelRef = React.useRef<HTMLButtonElement | null>(null)
  const {
    handleSubmit,
    formState: { isSubmitting },
  } = useForm()

  const deleteEntity = async (id: string) => {
    if (type === "Item") {
      await ItemsService.deleteItem({ id: id })
    } else if (type === "User") {
      await UsersService.deleteUser({ userId: id })
    } else if (type === "Message") {
      await ClientMessagesService.deleteMessage({ id: id })
    } else if (type === "AboutUs") {
      await AboutUsService.deleteAboutUs({ id: id })
    } else if (type === "Organ") {
      await OrganService.deleteOrgan({ id: id })
    }
    else if (type === "Course") {
      await CoursesService.deleteCourse({ id: id })
    } else if (type === "Image") {
      await ImageService.deleteImage({ id: id })
    } else if (type === "Info_Image") {
      await Info_imageService.deleteImage({ id: id })
    } else if (type === "Sechedule") {
      await secheduleService.deleteSechedule({ id: id })
    }
    else {
      throw new Error(`Unexpected type: ${type}`)
    }
  }

  const mutation = useMutation({
    mutationFn: deleteEntity,
    onSuccess: (data) => {
      showToast(
        "Success",
        `The ${type.toLowerCase()} was deleted successfully.`,
        "success",
      )
      console.log(data)
      //queryClient.setQueryData(['course'], data)
      onClose()
    },
    onError: () => {
      showToast(
        "An error occurred.",
        `An error occurred while deleting the ${type.toLowerCase()}.`,
        "error",
      )
    },
    onSettled: () => {
      var key = ''
      if (type === "Item") {
        key = "items"
      } else if (type === "User") {
        key = "users"
      } else if (type === "Message") {
        key = "messages"
      } else if (type === "AboutUs") {
        key = "aboutUs"
      } else if(type === "Organ"){
        key = "organ"
      } else if (type === "Course") {
        key = "courses"
      } else if (type === "Image") {
        key = "course"
      } else if (type === "Info_Image") {
        key = "course"
      } else if (type === "Sechedule") {
        key = "course"
      }
      else {
        throw new Error(`Unexpected type: ${type}`)
      }
      queryClient.invalidateQueries({
        queryKey: [key],
      })
    },
  })

  const onSubmit = async () => {
    mutation.mutate(id)
  }

  return (
    <>
      <AlertDialog
        isOpen={isOpen}
        onClose={onClose}
        leastDestructiveRef={cancelRef}
        size={{ base: "sm", md: "md" }}
        isCentered
      >
        <AlertDialogOverlay>
          <AlertDialogContent as="form" onSubmit={handleSubmit(onSubmit)}>
            <AlertDialogHeader>Delete {type}</AlertDialogHeader>

            <AlertDialogBody>
              {type === "User" && (
                <span>
                  All items associated with this user will also be{" "}
                  <strong>permantly deleted. </strong>
                </span>
              )}
              Are you sure? You will not be able to undo this action.
            </AlertDialogBody>

            <AlertDialogFooter gap={3}>
              <Button variant="danger" type="submit" isLoading={isSubmitting}>
                Delete
              </Button>
              <Button
                ref={cancelRef}
                onClick={onClose}
                isDisabled={isSubmitting}
              >
                Cancel
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </>
  )
}

export default Delete
