"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: () => {
      queryClient.invalidateQueries({ queryKey: ["watcher", "status"] });
      toast.success("File watcher started successfully");
      addNotification({
        type: "success",
        title: "File Watcher Started",
        message: "The file watcher has been started successfully."
      });
    },
    onError: () => {
      toast.error("Failed to start file watcher");
    }
  });

  const stopMutation = useMutation({
    mutationFn: () => post("/watcher/stop"),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["watcher", "status"] });
      toast.success("File watcher stopped successfully");
      addNotification({
        type: "success",
        title: "File Watcher Stopped",
        message: "The file watcher has been stopped successfully."
      });
    },
    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">
      <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?.isWatching || startMutation.isPending}
        title="Start file watcher"
      >
        <svg
          className="h-4 w-4 mr-1"
          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>
        {startMutation.isPending ? "Starting..." : "Start Watcher"}
      </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?.isWatching || stopMutation.isPending}
        title="Stop file watcher"
      >
        <svg
          className="h-4 w-4 mr-1"
          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 Watcher"}
      </button>
    </div>
  );
}
