"use client";
import {
  ChevronDownIcon,
  WrenchScrewdriverIcon
} from "@heroicons/react/24/outline";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import toast from "react-hot-toast";
import { get, post } from "../../lib/api";
import { useNotifications } from "./NotificationContext";
import SlideInForm from "./SlideInForm";

export default function TaskMaintenance() {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const [isOpen, setIsOpen] = useState(false);
  const [operation, setOperation] = useState<
    "cleanup" | "archive" | "purge" | "scheduled" | "stats" | null
  >(null);
  const [status, setStatus] = useState<string>("");
  const [olderThanDays, setOlderThanDays] = useState<number | undefined>();
  const [daysOld, setDaysOld] = useState<number>(30);

  // Query for task stats
  const { data: stats } = useQuery({
    queryKey: ["taskStats"],
    queryFn: () => get("/maintenance/tasks/stats"),
    enabled: operation === "stats"
  });

  const cleanupMutation = useMutation({
    mutationFn: () =>
      post("/maintenance/tasks/cleanup", { status, olderThanDays }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
      setIsOpen(false);
      resetForm();
      toast.success("Task cleanup completed successfully");
      addNotification({
        type: "success",
        title: "Task Maintenance Complete",
        message: "Task cleanup operation completed successfully."
      });
    },
    onError: (error: any) => {
      toast.error(`Task cleanup failed: ${error.message}`);
      addNotification({
        type: "error",
        title: "Task Maintenance Failed",
        message: `Task cleanup operation failed: ${error.message}`
      });
    }
  });

  const archiveMutation = useMutation({
    mutationFn: () => post("/maintenance/tasks/archive", { daysOld }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
      setIsOpen(false);
      resetForm();
      toast.success("Task archive completed successfully");
      addNotification({
        type: "success",
        title: "Task Maintenance Complete",
        message: "Task archive operation completed successfully."
      });
    },
    onError: (error: any) => {
      toast.error(`Task archive failed: ${error.message}`);
      addNotification({
        type: "error",
        title: "Task Maintenance Failed",
        message: `Task archive operation failed: ${error.message}`
      });
    }
  });

  const purgeMutation = useMutation({
    mutationFn: () => post("/maintenance/tasks/purge"),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
      setIsOpen(false);
      resetForm();
      toast.success("All tasks purged successfully");
      addNotification({
        type: "success",
        title: "Task Maintenance Complete",
        message: "All tasks have been purged successfully."
      });
    },
    onError: (error: any) => {
      toast.error(`Task purge failed: ${error.message}`);
      addNotification({
        type: "error",
        title: "Task Maintenance Failed",
        message: `Task purge operation failed: ${error.message}`
      });
    }
  });

  const scheduledMutation = useMutation({
    mutationFn: () => post("/maintenance/tasks/scheduled-cleanup"),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
      setIsOpen(false);
      resetForm();
      toast.success("Scheduled task cleanup completed successfully");
      addNotification({
        type: "success",
        title: "Task Maintenance Complete",
        message: "Scheduled task cleanup operation completed successfully."
      });
    },
    onError: (error: any) => {
      toast.error(`Scheduled cleanup failed: ${error.message}`);
      addNotification({
        type: "error",
        title: "Task Maintenance Failed",
        message: `Scheduled cleanup operation failed: ${error.message}`
      });
    }
  });

  const resetForm = () => {
    setOperation(null);
    setStatus("");
    setOlderThanDays(undefined);
    setDaysOld(30);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (operation === "cleanup") {
      cleanupMutation.mutate();
    } else if (operation === "archive") {
      archiveMutation.mutate();
    } else if (operation === "purge") {
      purgeMutation.mutate();
    } else if (operation === "scheduled") {
      scheduledMutation.mutate();
    }
  };

  const handleClose = () => {
    setIsOpen(false);
    resetForm();
  };

  const renderForm = () => {
    if (operation === "cleanup") {
      return (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Task Status (Optional)
            </label>
            <select
              className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              value={status}
              onChange={(e) => setStatus(e.target.value)}
            >
              <option value="">All statuses</option>
              <option value="completed">Completed</option>
              <option value="failed">Failed</option>
              <option value="skipped">Skipped</option>
              <option value="processing">Processing</option>
              <option value="pending">Pending</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Older Than Days (Optional)
            </label>
            <input
              type="number"
              className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              placeholder="Delete tasks older than this many days"
              value={olderThanDays || ""}
              onChange={(e) =>
                setOlderThanDays(
                  e.target.value ? parseInt(e.target.value) : undefined
                )
              }
            />
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              If no status is selected, will cleanup completed, failed, and
              skipped tasks older than 7 days.
            </p>
          </div>
        </form>
      );
    } else if (operation === "archive") {
      return (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Days Old
            </label>
            <input
              type="number"
              className="block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              placeholder="Archive tasks older than this many days"
              value={daysOld}
              onChange={(e) => setDaysOld(parseInt(e.target.value) || 30)}
              min="1"
              required
            />
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              Tasks older than this will be moved to the archive table. Default:
              30 days.
            </p>
          </div>
        </form>
      );
    } else if (operation === "scheduled") {
      return (
        <div className="space-y-4">
          <p className="text-sm text-gray-700 dark:text-gray-200">
            This will run the same cleanup operations that run automatically
            every day at 2 AM:
          </p>
          <ul className="text-sm text-gray-600 dark:text-gray-400 space-y-1 ml-4">
            <li>• Archive completed tasks older than 30 days</li>
            <li>• Delete failed tasks older than 7 days</li>
            <li>• Delete skipped tasks older than 7 days</li>
            <li>• Delete completed tasks older than 90 days</li>
          </ul>
        </div>
      );
    } else if (operation === "stats") {
      return (
        <div className="space-y-4">
          {stats ? (
            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-md">
                <span className="font-medium text-gray-900 dark:text-gray-100">
                  Total Tasks
                </span>
                <span className="text-lg font-bold text-indigo-600 dark:text-indigo-400">
                  {stats.total}
                </span>
              </div>
              {stats.byStatus?.map((status: any) => (
                <div
                  key={status.status}
                  className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-md"
                >
                  <div>
                    <span className="font-medium text-gray-900 dark:text-gray-100 capitalize">
                      {status.status}
                    </span>
                    <div className="text-xs text-gray-500 dark:text-gray-400">
                      Oldest: {new Date(status.oldest).toLocaleDateString()} |
                      Newest: {new Date(status.newest).toLocaleDateString()}
                    </div>
                  </div>
                  <span className="text-lg font-bold text-gray-700 dark:text-gray-300">
                    {status.count}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-4">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-2">
                Loading task statistics...
              </p>
            </div>
          )}
        </div>
      );
    } else if (operation === "purge") {
      return (
        <div className="space-y-4">
          <div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
            <div className="flex">
              <div className="flex-shrink-0">
                <svg
                  className="h-5 w-5 text-red-400"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fillRule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                    clipRule="evenodd"
                  />
                </svg>
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800 dark:text-red-200">
                  Warning: This action cannot be undone
                </h3>
                <div className="mt-2 text-sm text-red-700 dark:text-red-300">
                  <p>
                    This will permanently delete ALL tasks from the database,
                    including pending, processing, completed, failed, and
                    skipped tasks. This action cannot be reversed.
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div className="text-sm text-gray-600 dark:text-gray-400">
            <p>
              Are you sure you want to purge all tasks? Type &quot;PURGE&quot;
              below to confirm:
            </p>
            <input
              type="text"
              className="mt-2 block w-full rounded-md border-gray-300 dark:border-gray-700 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              placeholder="Type PURGE to confirm"
              onChange={() => {
                // We could add confirmation logic here if needed
              }}
            />
          </div>
        </div>
      );
    }
    return null;
  };

  const getFormTitle = () => {
    switch (operation) {
      case "cleanup":
        return "Cleanup Tasks";
      case "archive":
        return "Archive Old Tasks";
      case "purge":
        return "Purge All Tasks";
      case "scheduled":
        return "Run Scheduled Cleanup";
      case "stats":
        return "Task Statistics";
      default:
        return "Task Maintenance";
    }
  };

  const isLoading =
    cleanupMutation.status === "pending" ||
    archiveMutation.status === "pending" ||
    purgeMutation.status === "pending" ||
    scheduledMutation.status === "pending";

  return (
    <>
      <div className="relative">
        <button
          onClick={() => setIsOpen(!isOpen)}
          className="inline-flex items-center rounded-md bg-purple-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2"
        >
          <WrenchScrewdriverIcon className="h-4 w-4 mr-2" />
          Task Maintenance
          <ChevronDownIcon className="h-4 w-4 ml-2" />
        </button>
        {isOpen && (
          <div className="absolute right-0 mt-2 w-56 bg-white dark:bg-gray-800 rounded-md shadow-lg border border-gray-200 dark:border-gray-700 z-10">
            <div className="py-1">
              <button
                onClick={() => {
                  setOperation("stats");
                  setIsOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                View Statistics
              </button>
              <button
                onClick={() => {
                  setOperation("cleanup");
                  setIsOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                Cleanup Tasks
              </button>
              <button
                onClick={() => {
                  setOperation("archive");
                  setIsOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                Archive Old Tasks
              </button>
              <button
                onClick={() => {
                  setOperation("purge");
                  setIsOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20"
              >
                Purge All Tasks
              </button>
              <button
                onClick={() => {
                  setOperation("scheduled");
                  setIsOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                Run Scheduled Cleanup
              </button>
            </div>
          </div>
        )}
      </div>

      <SlideInForm
        isOpen={!!operation}
        onClose={handleClose}
        title={getFormTitle()}
        actions={
          operation === "stats" ? (
            <div className="flex justify-end">
              <button
                type="button"
                onClick={handleClose}
                className="inline-flex items-center rounded-md border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 shadow-sm hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
              >
                Close
              </button>
            </div>
          ) : (
            <div className="flex justify-end space-x-3">
              <button
                type="button"
                onClick={handleClose}
                className="inline-flex items-center rounded-md border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 shadow-sm hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={isLoading}
                onClick={handleSubmit}
                className="inline-flex items-center rounded-md border border-transparent bg-purple-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2"
              >
                {isLoading ? "Running..." : "Execute"}
              </button>
            </div>
          )
        }
      >
        {renderForm()}
      </SlideInForm>
    </>
  );
}
