"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { get, post } from "../../lib/api";
import Card from "./Card";

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

  const { data: filesSuccessful, isLoading: filesSuccessfulLoading } = useQuery(
    {
      queryKey: ["files-stats-successful"],
      queryFn: () => get("/files/stats/successful"),
    }
  );

  const { data: filesProcessedTotal, isLoading: filesProcessedLoading } =
    useQuery({
      queryKey: ["files-stats-processed"],
      queryFn: () => get("/files/stats/processed"),
    });

  const {
    data: taskProcessingStatus,
    isLoading: taskProcessingLoading,
    refetch: refetchTaskProcessingStatus,
  } = useQuery({
    queryKey: ["tasks", "processing-status"],
    queryFn: () => get("/tasks/processing-status"),
    staleTime: 0,
    gcTime: 0,
  });

  const { data: queueStatus } = useQuery({
    queryKey: ["tasks", "queue", "status"],
    queryFn: () => get("/tasks/queue/status"),
  });

  const startTaskProcessingMutation = useMutation({
    mutationFn: () => post("/tasks/start-processing"),
    onSuccess: async () => {
      // Small delay to let backend update state
      await new Promise((resolve) => setTimeout(resolve, 200));
      await refetchTaskProcessingStatus();
      queryClient.invalidateQueries({ queryKey: ["tasks", "queue", "status"] });
      toast.success("Task processing started");
    },
    onError: () => {
      toast.error("Failed to start task processing");
    },
  });

  const stopTaskProcessingMutation = useMutation({
    mutationFn: () => post("/tasks/stop-processing"),
    onSuccess: async () => {
      // Small delay to let backend update state
      await new Promise((resolve) => setTimeout(resolve, 200));
      await refetchTaskProcessingStatus();
      queryClient.invalidateQueries({ queryKey: ["tasks", "queue", "status"] });
      toast.success("Task processing stopped");
    },
    onError: () => {
      toast.error("Failed to stop task processing");
    },
  });

  const filesProcessed = filesSuccessful || 0;
  const totalProcessed = filesProcessedTotal || 0;
  const successRate =
    totalProcessed > 0
      ? Math.round((filesProcessed / totalProcessed) * 100)
      : 0;
  const isTaskProcessingActive = taskProcessingStatus?.isProcessing;

  return (
    <Card>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-x-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-500/20 ring-1 ring-emerald-500/30">
            <svg
              className="h-6 w-6 text-emerald-400"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <div>
            <div className="text-2xl font-bold text-white">
              {taskProcessingLoading ? (
                <div className="flex justify-center">
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                </div>
              ) : (
                <span
                  className={
                    isTaskProcessingActive ? "text-green-400" : "text-red-400"
                  }
                >
                  {isTaskProcessingActive ? "Active" : "Idle"}
                </span>
              )}
            </div>
            <div className="text-sm font-medium text-gray-400">
              Task Processing
            </div>
            <div className="text-xs text-gray-500 mt-1">
              {filesSuccessfulLoading || filesProcessedLoading
                ? "..."
                : `${successRate}% success`}
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() =>
              isTaskProcessingActive
                ? stopTaskProcessingMutation.mutate()
                : startTaskProcessingMutation.mutate()
            }
            disabled={
              taskProcessingLoading ||
              startTaskProcessingMutation.isPending ||
              stopTaskProcessingMutation.isPending
            }
            className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
              isTaskProcessingActive
                ? "bg-red-600 hover:bg-red-700 text-white"
                : "bg-green-600 hover:bg-green-700 text-white"
            } disabled:opacity-50`}
          >
            {startTaskProcessingMutation.isPending ||
            stopTaskProcessingMutation.isPending
              ? "..."
              : isTaskProcessingActive
                ? "Stop"
                : "Start"}
          </button>
        </div>
      </div>
      {queueStatus && (
        <div className="mt-4 pt-4 border-t border-white/10">
          <div className="grid grid-cols-4 gap-2 text-xs">
            <div className="text-center">
              <div className="text-gray-400">Pending</div>
              <div className="text-white font-medium">
                {queueStatus.pending || 0}
              </div>
            </div>
            <div className="text-center">
              <div className="text-gray-400">Active</div>
              <div className="text-white font-medium">
                {queueStatus.processing || 0}
              </div>
            </div>
            <div className="text-center">
              <div className="text-gray-400">Done</div>
              <div className="text-white font-medium">
                {queueStatus.completed || 0}
              </div>
            </div>
            <div className="text-center">
              <div className="text-gray-400">Failed</div>
              <div className="text-white font-medium">
                {queueStatus.failed || 0}
              </div>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}
