"use client";
import { PlusIcon } from "@heroicons/react/24/outline";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { post } from "../../lib/api";
import DatasetsSettingsEditor from "./DatasetsSettingsEditor";
import JsonInput from "./JsonInput";
import { useNotifications } from "./NotificationContext";
import QueueSettingsEditor from "./QueueSettingsEditor";
import SlideInForm from "./SlideInForm";
import WatcherSettingsEditor from "./WatcherSettingsEditor";

interface SettingsCrudProps {
  editKey?: string;
  editValue?: string;
  onEditClose?: () => void;
}

export default function SettingsCrud({
  editKey,
  editValue,
  onEditClose
}: SettingsCrudProps) {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const [isOpen, setIsOpen] = useState(false);
  const [key, setKey] = useState("");
  const [value, setValue] = useState("");

  const isEditing = !!editKey;

  useEffect(() => {
    if (isEditing) {
      setKey(editKey);
      setValue(editValue || "");
      setIsOpen(true);
    }
  }, [editKey, editValue, isEditing]);

  const createMutation = useMutation({
    mutationFn: () => post(`/config/settings`, { [key]: value }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["settings"] });
      setKey("");
      setValue("");
      setIsOpen(false);
      if (onEditClose) onEditClose();
      const message = isEditing
        ? "Setting updated successfully"
        : "Setting added successfully";
      toast.success(message);
      addNotification({
        type: "success",
        title: "Setting Saved",
        message: `${key} has been ${isEditing ? "updated" : "added"} successfully.`
      });
    },
    onError: (error) => {
      console.error("Failed to save setting:", error);
      toast.error("Failed to save setting");
      addNotification({
        type: "error",
        title: "Save Failed",
        message: "Failed to save the setting. Please try again."
      });
    }
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createMutation.mutate();
  };

  const getValueEditor = (currentKey?: string) => {
    const editorKey = currentKey || key;
    switch (editorKey) {
      case "watcher":
        return <WatcherSettingsEditor value={value} onChange={setValue} />;
      case "queue":
        return <QueueSettingsEditor value={value} onChange={setValue} />;
      case "datasets":
        return <DatasetsSettingsEditor value={value} onChange={setValue} />;
      default:
        return (
          <JsonInput
            value={value}
            onChange={setValue}
            className="w-full"
            placeholder="Value (JSON)"
          />
        );
    }
  };

  const handleClose = () => {
    setIsOpen(false);
    setKey("");
    setValue("");
    if (onEditClose) onEditClose();
  };

  if (isEditing) {
    return (
      <SlideInForm
        isOpen={isOpen}
        onClose={handleClose}
        title="Edit Setting"
        actions={
          <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="button"
              onClick={handleSubmit}
              disabled={createMutation.isPending}
              className="inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
            >
              Update Setting
            </button>
          </div>
        }
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Key
            </label>
            <input
              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="Key"
              value={key}
              onChange={(e) => setKey(e.target.value)}
              required
              disabled
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Value
            </label>
            {getValueEditor()}
          </div>
        </form>
      </SlideInForm>
    );
  }

  return (
    <>
      <button
        onClick={() => setIsOpen(true)}
        className="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
      >
        <PlusIcon className="h-4 w-4 mr-2" />
        Add Setting
      </button>

      <SlideInForm
        isOpen={isOpen}
        onClose={handleClose}
        title={isEditing ? `Edit Setting: ${editKey}` : "Add New Setting"}
        actions={
          <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"
              onClick={handleSubmit}
              disabled={createMutation.isPending}
              className="inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
            >
              {isEditing ? "Update Setting" : "Add Setting"}
            </button>
          </div>
        }
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Key
            </label>
            <input
              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="Key"
              value={key}
              onChange={(e) => setKey(e.target.value)}
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Value
            </label>
            {getValueEditor(key)}
          </div>
        </form>
      </SlideInForm>
    </>
  );
}
