"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 LoadingCard from "./Loading";
import { useNotifications } from "./NotificationContext";

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

  const { data: queueStatus } = useQuery({
    queryKey: ["tasks", "queue", "status"],
    queryFn: () => get("/tasks/queue/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]);

  if (isLoading)
    return <LoadingCard message="Loading task processing status..." />;
  if (error) {
    return (
      <div className="mb-6 p-4 border rounded bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">
        <div className="text-center">
          <div className="mb-4">
            <svg
              className="mx-auto h-12 w-12 text-red-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
              />
            </svg>
          </div>
          <h3 className="font-semibold text-red-800 dark:text-red-200 mb-2">
            Failed to load task processing status
          </h3>
          <p className="text-sm text-red-600 dark:text-red-400 mb-4">
            Unable to connect to the task processing service.
          </p>
          {error && (
            <p className="text-xs text-red-500 dark:text-red-300 mb-4">
              Error: {error.message}
            </p>
          )}
          <button
            onClick={() =>
              queryClient.invalidateQueries({
                queryKey: ["tasks", "processing-status"]
              })
            }
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-red-700 dark:text-red-300 bg-red-100 dark:bg-red-900 hover:bg-red-200 dark:hover:bg-red-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="mb-6 p-4 border rounded bg-gray-50 dark:bg-gray-800">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-semibold">Task Processing</h3>
        <div className="flex gap-2">
          <button
            className="px-3 py-1 rounded bg-green-600 text-white disabled:opacity-50 text-sm"
            onClick={() => startMutation.mutate()}
            disabled={data?.isProcessing || startMutation.isPending}
          >
            {startMutation.isPending ? "Starting..." : "Start"}
          </button>
          <button
            className="px-3 py-1 rounded bg-red-600 text-white disabled:opacity-50 text-sm"
            onClick={() => stopMutation.mutate()}
            disabled={!data?.isProcessing || stopMutation.isPending}
          >
            {stopMutation.isPending ? "Stopping..." : "Stop"}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-4 text-sm">
        <div>
          <span className="font-medium text-gray-700 dark:text-gray-300">
            Status:
          </span>
          <span
            className={`ml-2 ${data?.isProcessing ? "text-green-600" : "text-red-600"}`}
          >
            {data?.isProcessing ? "Processing" : "Idle"}
          </span>
        </div>
        <div>
          <span className="font-medium text-gray-700 dark:text-gray-300">
            Active Tasks:
          </span>
          <span className="ml-2 text-gray-900 dark:text-gray-100">
            {queueStatus?.activeTasks || 0}
          </span>
        </div>
      </div>

      {queueStatus && (
        <div className="grid grid-cols-4 gap-4 text-sm">
          <div>
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Pending:
            </span>
            <span className="ml-2 text-gray-900 dark:text-gray-100">
              {queueStatus.pending || 0}
            </span>
          </div>
          <div>
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Processing:
            </span>
            <span className="ml-2 text-gray-900 dark:text-gray-100">
              {queueStatus.processing || 0}
            </span>
          </div>
          <div>
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Completed:
            </span>
            <span className="ml-2 text-gray-900 dark:text-gray-100">
              {queueStatus.completed || 0}
            </span>
          </div>
          <div>
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Failed:
            </span>
            <span className="ml-2 text-gray-900 dark:text-gray-100">
              {queueStatus.failed || 0}
            </span>
          </div>
        </div>
      )}
    </div>
  );
}
