"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 WatcherControls() {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const { data } = useQuery({
    queryKey: ["watcher", "status"],
    queryFn: () => get("/watcher/status"),
  });

  const startMutation = useMutation({
    mutationFn: () => post("/watcher/start"),
    onSuccess: () => {
      toast.success("File watcher started successfully");
      addNotification({
        type: "success",
        title: "File Watcher Started",
        message: "The file watcher has been started successfully.",
      });
      // Invalidate and refetch to ensure status updates immediately
      queryClient.invalidateQueries({ queryKey: ["watcher", "status"] });
      setTimeout(() => {
        queryClient.refetchQueries({ queryKey: ["watcher", "status"] });
      }, 100);
    },
    onError: () => {
      toast.error("Failed to start file watcher");
    },
  });

  const stopMutation = useMutation({
    mutationFn: () => post("/watcher/stop"),
    onSuccess: () => {
      toast.success("File watcher stopped successfully");
      addNotification({
        type: "success",
        title: "File Watcher Stopped",
        message: "The file watcher has been stopped successfully.",
      });
      // Invalidate and refetch to ensure status updates immediately
      queryClient.invalidateQueries({ queryKey: ["watcher", "status"] });
      setTimeout(() => {
        queryClient.refetchQueries({ queryKey: ["watcher", "status"] });
      }, 100);
    },
    onError: () => {
      toast.error("Failed to stop file watcher");
    },
  });

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

    window.addEventListener(
      "watcherUpdate",
      handleWatcherUpdate as EventListener
    );

    return () => {
      window.removeEventListener(
        "watcherUpdate",
        handleWatcherUpdate 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?.isWatching || startMutation.isPending}
          title="Start file watcher"
        >
          <svg
            className="h-5 w-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
            />
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.543-7z"
            />
          </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 Watcher"}
        </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?.isWatching || stopMutation.isPending}
          title="Stop file watcher"
        >
          <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..." : "Stop Watcher"}
        </div>
      </div>
    </div>
  );
}
