"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;
}

interface TaskFormState {
  task: string;
  status: string;
  progress: number;
  dataset: string;
  input: string;
  output: string;
  preset: string;
  priority: number;
  isOpen: boolean;
}

const initialTaskState: TaskFormState = {
  task: "handbrake",
  status: "pending",
  progress: 0,
  dataset: "",
  input: "",
  output: "",
  preset: "Fast 1080p30",
  priority: 0,
  isOpen: false
};

export default function TaskCrud({
  editTask,
  onEditClose,
  isAdding,
  onAddClose
}: TaskCrudProps) {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const [formState, setFormState] = useState<TaskFormState>(initialTaskState);

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

  useEffect(() => {
    if (isEditing && editTask) {
      setFormState({
        task: editTask.task || "handbrake",
        status: editTask.status || "",
        progress: editTask.progress || 0,
        dataset: editTask.dataset || "",
        input: editTask.input || "",
        output: editTask.output || "",
        preset: editTask.preset || "",
        priority: editTask.priority || 0,
        isOpen: true
      });
    } else if (isAdding) {
      setFormState({ ...initialTaskState, isOpen: true });
    }
  }, [editTask, isEditing, isAdding]);

  const resetForm = () => {
    setFormState(initialTaskState);
  };

  const createMutation = useMutation({
    mutationFn: () =>
      post(`/tasks`, {
        task: formState.task,
        status: formState.status,
        progress: formState.progress,
        dataset: formState.dataset,
        input: formState.input,
        output: formState.output,
        preset: formState.preset,
        priority: formState.priority
      }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["tasks"] });
      resetForm();
      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: formState.task,
        status: formState.status,
        progress: formState.progress,
        dataset: formState.dataset,
        input: formState.input,
        output: formState.output,
        preset: formState.preset,
        priority: formState.priority
      }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["tasks"] });
      resetForm();
      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 = () => {
    resetForm();
    if (onEditClose) onEditClose();
    if (onAddClose) onAddClose();
  };

  const handleAddClick = () => {
    setFormState({ ...initialTaskState, isOpen: true });
  };

  // If not editing and not adding, render the add button
  if (!isEditing && !isAdding && !formState.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>
    );
  }

  const renderForm = () => (
    <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={formState.task}
          onChange={(e) => setFormState({ ...formState, task: 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={formState.status}
          onChange={(e) =>
            setFormState({ ...formState, status: 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={formState.progress}
          onChange={(e) =>
            setFormState({
              ...formState,
              progress: 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={formState.dataset}
          onChange={(e) =>
            setFormState({ ...formState, dataset: 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={formState.input}
          onChange={(e) =>
            setFormState({ ...formState, input: 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={formState.output}
          onChange={(e) =>
            setFormState({ ...formState, output: 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={formState.preset}
          onChange={(e) =>
            setFormState({ ...formState, preset: 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={formState.priority}
          onChange={(e) =>
            setFormState({
              ...formState,
              priority: parseInt(e.target.value) || 0
            })
          }
        />
      </div>
    </form>
  );

  return (
    <SlideInForm
      isOpen={formState.isOpen}
      onClose={handleClose}
      title={isEditing ? "Edit Task" : "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>
      }
    >
      {renderForm()}
    </SlideInForm>
  );
}
