"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import toast from "react-hot-toast";
import { get, post } from "../../lib/api";
import { useNotifications } from "./NotificationContext";

export default function TaskProcessingControls() {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const { data } = useQuery({
    queryKey: ["tasks", "processing-status"],
    queryFn: () => get("/tasks/processing-status"),
  });

  const startMutation = useMutation({
    mutationFn: () => post("/tasks/start-processing"),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["tasks", "processing-status"],
      });
      queryClient.invalidateQueries({ queryKey: ["tasks", "queue", "status"] });
      toast.success("Task processing started successfully");
      addNotification({
        type: "success",
        title: "Task Processing Started",
        message: "The task processing queue has been started successfully.",
      });
    },
  });

  const stopMutation = useMutation({
    mutationFn: () => post("/tasks/stop-processing", { graceful: true }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["tasks", "processing-status"],
      });
      queryClient.invalidateQueries({ queryKey: ["tasks", "queue", "status"] });
      toast.success("Graceful stop initiated – finishing active tasks");
      addNotification({
        type: "info",
        title: "Graceful Stop Requested",
        message: "The queue will finish active tasks before stopping.",
      });
    },
  });

  const hardStopMutation = useMutation({
    mutationFn: () => post("/tasks/stop-processing", { graceful: false }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["tasks", "processing-status"],
      });
      queryClient.invalidateQueries({ queryKey: ["tasks", "queue", "status"] });
      toast.success("Task processing stopped immediately");
      addNotification({
        type: "warning",
        title: "Immediate Stop",
        message: "Queue scheduling and active work halted immediately.",
      });
    },
  });

  // Listen for WebSocket events
  useEffect(() => {
    const handleTaskUpdate = (event: CustomEvent) => {
      const updateData = event.detail;
      if (
        updateData.type === "started" ||
        updateData.type === "stopped" ||
        updateData.type === "progress"
      ) {
        // Invalidate and refetch the task processing status
        queryClient.invalidateQueries({
          queryKey: ["tasks", "processing-status"],
        });
        queryClient.invalidateQueries({
          queryKey: ["tasks", "queue", "status"],
        });
      }
    };

    window.addEventListener("taskUpdate", handleTaskUpdate as EventListener);

    return () => {
      window.removeEventListener(
        "taskUpdate",
        handleTaskUpdate as EventListener
      );
    };
  }, [queryClient]);

  return (
    <div className="flex items-center gap-2">
      <div className="relative group">
        <button
          className="p-2 rounded-md text-gray-600 dark:text-gray-400 hover:bg-green-100 dark:hover:bg-green-900/30 hover:text-green-600 dark:hover:text-green-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          onClick={() => startMutation.mutate()}
          disabled={data?.isProcessing || startMutation.isPending}
          title="Start task processing"
        >
          <svg
            className="h-5 w-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M14.828 14.828a4 4 0 01-5.656 0M9 10h1.586a1 1 0 01.707.293l.707.707A1 1 0 0012.414 11H15m-3-3v3m0 0v3m0-3h3m-3 0H9"
            />
          </svg>
        </button>
        <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
          {startMutation.isPending ? "Starting..." : "Start"}
        </div>
      </div>

      <div className="relative group">
        <button
          className="p-2 rounded-md text-gray-600 dark:text-gray-400 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          onClick={() => stopMutation.mutate()}
          disabled={!data?.isProcessing || stopMutation.isPending}
          title="Graceful stop (finish active tasks)"
        >
          <svg
            className="h-5 w-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"
            />
          </svg>
        </button>
        <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
          {stopMutation.isPending ? "Stopping..." : "Graceful Stop"}
        </div>
      </div>

      <div className="relative group">
        <button
          className="p-2 rounded-md text-gray-600 dark:text-gray-400 hover:bg-orange-100 dark:hover:bg-orange-900/30 hover:text-orange-600 dark:hover:text-orange-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          onClick={() => hardStopMutation.mutate()}
          disabled={!data?.isProcessing || hardStopMutation.isPending}
          title="Immediate stop (cancel scheduling)"
        >
          <svg
            className="h-5 w-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
        <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
          {hardStopMutation.isPending ? "Stopping..." : "Hard Stop"}
        </div>
      </div>
    </div>
  );
}
