"use client";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import ApiHealth from "./ApiHealth";
import Card from "./Card";
import FilesProcessedCard from "./FilesProcessedCard";
import FileWatcherCard from "./FileWatcherCard";
import TaskProcessingCard from "./TaskProcessingCard";
import WatcherHealthStatus from "./WatcherHealthStatus";

export default function StatsSection() {
  const queryClient = useQueryClient();

  // Listen for WebSocket updates to refresh stats
  useEffect(() => {
    const handleTaskUpdate = (event: CustomEvent) => {
      const taskData = event.detail;
      // Refresh task-related queries when tasks are updated
      if (
        taskData.type === "progress" ||
        taskData.type === "completed" ||
        taskData.type === "failed"
      ) {
        queryClient.invalidateQueries({ queryKey: ["tasks"] });
        queryClient.invalidateQueries({
          queryKey: ["tasks", "processing-status"],
        });
        queryClient.invalidateQueries({
          queryKey: ["tasks", "queue", "status"],
        });
      }
    };

    const handleFileUpdate = (event: CustomEvent) => {
      const fileData = event.detail;
      // Refresh file stats when files are processed
      if (fileData.type === "processed" || fileData.type === "success") {
        queryClient.invalidateQueries({ queryKey: ["files-stats-successful"] });
        queryClient.invalidateQueries({ queryKey: ["files-stats-processed"] });
      }
    };

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

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

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
        {/* API Health Widget */}
        <ApiHealth />

        {/* File Watcher Card */}
        <FileWatcherCard />

        {/* Task Processing Card */}
        <TaskProcessingCard />

        {/* Files Processed Card */}
        <FilesProcessedCard />
      </div>

      {/* Watcher Health Status - Full Width */}
      <div>
        <Card>
          <div className="space-y-4">
            <div className="flex items-center gap-x-3 mb-6">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-500/20 ring-1 ring-amber-500/30">
                <svg
                  className="h-6 w-6 text-amber-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth="1.5"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M9.348 14.652a3.75 3.75 0 010-5.304m5.304 0a3.75 3.75 0 010 5.304m6.632-7.08a9 9 0 11-12.728 0m12.728 0A9 9 0 003.75 12c0 4.478 2.943 8.268 7-9.542"
                  />
                </svg>
              </div>
              <div>
                <h3 className="text-lg font-bold text-white">Watcher Health</h3>
                <p className="text-xs text-gray-400">Status & Monitoring</p>
              </div>
            </div>
            <WatcherHealthStatus />
          </div>
        </Card>
      </div>
    </div>
  );
}
