"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { post, put } from "../../lib/api";
import { useNotifications } from "./NotificationContext";
import SlideInForm from "./SlideInForm";

interface TaskCrudProps {
  editTask?: any;
  onEditClose?: () => void;
  isAdding?: boolean;
  onAddClose?: () => void;
}

export default function TaskCrud({
  editTask,
  onEditClose,
  isAdding,
  onAddClose
}: TaskCrudProps) {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const [isOpen, setIsOpen] = useState(false);
  const [task, setTask] = useState("");
  const [status, setStatus] = useState("");
  const [progress, setProgress] = useState(0);
  const [dataset, setDataset] = useState("");
  const [input, setInput] = useState("");
  const [output, setOutput] = useState("");
  const [preset, setPreset] = useState("");
  const [priority, setPriority] = useState(0);

  const isEditing = !!editTask && Object.keys(editTask).length > 0;

  useEffect(() => {
    if (isEditing && editTask) {
      setTask(editTask.task || "handbrake");
      setStatus(editTask.status || "");
      setProgress(editTask.progress || 0);
      setDataset(editTask.dataset || "");
      setInput(editTask.input || "");
      setOutput(editTask.output || "");
      setPreset(editTask.preset || "");
      setPriority(editTask.priority || 0);
      setIsOpen(true);
    } else if (isAdding) {
      setTask("handbrake");
      setStatus("pending");
      setProgress(0);
      setDataset("");
      setInput("");
      setOutput("");
      setPreset("Fast 1080p30");
      setPriority(0);
      setIsOpen(true);
    }
  }, [editTask, isEditing, isAdding]);

  const createMutation = useMutation({
    mutationFn: () =>
      post(`/tasks`, {
        task,
        status,
        progress,
        dataset,
        input,
        output,
        preset,
        priority
      }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["tasks"] });
      setTask("handbrake");
      setStatus("pending");
      setProgress(0);
      setDataset("");
      setInput("");
      setOutput("");
      setPreset("Fast 1080p30");
      setPriority(0);
      setIsOpen(false);
      if (onAddClose) onAddClose();
      toast.success("Task created successfully");
      addNotification({
        type: "success",
        title: "Task Created",
        message: `Task has been created successfully.`
      });
    }
  });

  const updateMutation = useMutation({
    mutationFn: () =>
      put(`/tasks/${editTask.id}`, {
        task,
        status,
        progress,
        dataset,
        input,
        output,
        preset,
        priority
      }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["tasks"] });
      setTask("handbrake");
      setStatus("pending");
      setProgress(0);
      setDataset("");
      setInput("");
      setOutput("");
      setPreset("Fast 1080p30");
      setPriority(0);
      setIsOpen(false);
      if (onEditClose) onEditClose();
      toast.success("Task updated successfully");
      addNotification({
        type: "success",
        title: "Task Updated",
        message: `Task has been updated successfully.`
      });
    }
  });

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

  const handleClose = () => {
    setIsOpen(false);
    setTask("handbrake");
    setStatus("pending");
    setProgress(0);
    setDataset("");
    setInput("");
    setOutput("");
    setPreset("Fast 1080p30");
    setPriority(0);
    if (onEditClose) onEditClose();
    if (onAddClose) onAddClose();
  };

  const handleAddClick = () => {
    setTask("handbrake");
    setStatus("pending");
    setProgress(0);
    setDataset("");
    setInput("");
    setOutput("");
    setPreset("Fast 1080p30");
    setPriority(0);
    setIsOpen(true);
  };

  // If not editing and not adding, render the add button
  if (!isEditing && !isAdding && !isOpen) {
    return (
      <button
        onClick={handleAddClick}
        className="inline-flex items-center rounded-md bg-green-600 px-4 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"
      >
        <svg
          className="h-4 w-4 mr-2"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M12 4v16m8-8H4"
          />
        </svg>
        Add Task
      </button>
    );
  }

  if (isEditing) {
    return (
      <SlideInForm
        isOpen={isOpen}
        onClose={handleClose}
        title="Edit Task"
        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"
              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 Task
            </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">
              Task Type
            </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="Task Type"
              value={task}
              onChange={(e) => setTask(e.target.value)}
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Status
            </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="pending">Pending</option>
              <option value="processing">Processing</option>
              <option value="completed">Completed</option>
              <option value="failed">Failed</option>
              <option value="skipped">Skipped</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Progress
            </label>
            <input
              type="number"
              min="0"
              max="100"
              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="Progress"
              value={progress}
              onChange={(e) => setProgress(parseInt(e.target.value) || 0)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Dataset
            </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="Dataset"
              value={dataset}
              onChange={(e) => setDataset(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Input File
            </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="Input File Path"
              value={input}
              onChange={(e) => setInput(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Output File
            </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="Output File Path"
              value={output}
              onChange={(e) => setOutput(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Preset
            </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="HandBrake Preset"
              value={preset}
              onChange={(e) => setPreset(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Priority
            </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="Priority"
              value={priority}
              onChange={(e) => setPriority(parseInt(e.target.value) || 0)}
            />
          </div>
        </form>
      </SlideInForm>
    );
  }

  return (
    <SlideInForm
      isOpen={isOpen}
      onClose={handleClose}
      title="Add New Task"
      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"
            disabled={createMutation.isPending || updateMutation.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 Task" : "Add Task"}
          </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">
            Task Type
          </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="Task Type"
            value={task}
            onChange={(e) => setTask(e.target.value)}
            required
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Status
          </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="pending">Pending</option>
            <option value="processing">Processing</option>
            <option value="completed">Completed</option>
            <option value="failed">Failed</option>
            <option value="skipped">Skipped</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Progress
          </label>
          <input
            type="number"
            min="0"
            max="100"
            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="Progress"
            value={progress}
            onChange={(e) => setProgress(parseInt(e.target.value) || 0)}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Dataset
          </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="Dataset"
            value={dataset}
            onChange={(e) => setDataset(e.target.value)}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Input File
          </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="Input File Path"
            value={input}
            onChange={(e) => setInput(e.target.value)}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Output File
          </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="Output File Path"
            value={output}
            onChange={(e) => setOutput(e.target.value)}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Preset
          </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="HandBrake Preset"
            value={preset}
            onChange={(e) => setPreset(e.target.value)}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
            Priority
          </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="Priority"
            value={priority}
            onChange={(e) => setPriority(parseInt(e.target.value) || 0)}
          />
        </div>
      </form>
    </SlideInForm>
  );
}
