"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"),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["tasks", "processing-status"]
      });
      queryClient.invalidateQueries({ queryKey: ["tasks", "queue", "status"] });
      toast.success("Task processing stopped successfully");
      addNotification({
        type: "success",
        title: "Task Processing Stopped",
        message: "The task processing queue has been stopped successfully."
      });
    }
  });

  // 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">
      <button
        className="inline-flex items-center rounded-md bg-green-600 px-3 py-2 text-sm font-medium text-white shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50"
        onClick={() => startMutation.mutate()}
        disabled={data?.isProcessing || startMutation.isPending}
        title="Start task processing"
      >
        <svg
          className="h-4 w-4"
          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>
        {startMutation.isPending ? "Starting..." : "Start"}
      </button>
      <button
        className="inline-flex items-center rounded-md bg-red-600 px-3 py-2 text-sm font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50"
        onClick={() => stopMutation.mutate()}
        disabled={!data?.isProcessing || stopMutation.isPending}
        title="Stop task processing"
      >
        <svg
          className="h-4 w-4"
          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>
        {stopMutation.isPending ? "Stopping..." : "Stop"}
      </button>
    </div>
  );
}
