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

interface FileCrudProps {
  editFile?: any;
  onEditClose?: () => void;
}

export default function FileCrud({ editFile, onEditClose }: FileCrudProps) {
  const queryClient = useQueryClient();
  const { addNotification } = useNotifications();
  const [isOpen, setIsOpen] = useState(false);
  const [dataset, setDataset] = useState("pr0n");
  const [input, setInput] = useState("");
  const [output, setOutput] = useState("");
  const [date, setDate] = useState("");

  const isEditing = !!editFile;

  // Get available datasets
  const { data: datasets } = useQuery({
    queryKey: ["datasets"],
    queryFn: () => get(`/files/all-datasets`)
  });

  useEffect(() => {
    if (isEditing && editFile) {
      setDataset(editFile.dataset || "pr0n");
      setInput(editFile.input || "");
      setOutput(editFile.output || "");
      setDate(editFile.date || "");
      setIsOpen(true);
    }
  }, [editFile, isEditing]);

  const createMutation = useMutation({
    mutationFn: () => post(`/files/${dataset}/${input}`, { output, date }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["files"] });
      setDataset("pr0n");
      setInput("");
      setOutput("");
      setDate("");
      setIsOpen(false);
      if (onEditClose) onEditClose();
      toast.success("File added successfully");
      addNotification({
        type: "success",
        title: "File Added",
        message: `File "${input}" has been added to dataset "${dataset}" successfully.`
      });
    }
  });

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

  const handleClose = () => {
    setIsOpen(false);
    setDataset("pr0n");
    setInput("");
    setOutput("");
    setDate("");
    if (onEditClose) onEditClose();
  };

  if (isEditing) {
    return (
      <SlideInForm
        isOpen={isOpen}
        onClose={handleClose}
        title="Edit File"
        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.status === "pending"}
              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 File
            </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">
              Dataset
            </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={dataset}
              onChange={(e) => setDataset(e.target.value)}
              required
            >
              <option value="">Select a dataset</option>
              {datasets?.map((ds: string) => (
                <option key={ds} value={ds.split("/").pop()}>
                  {ds.split("/").pop()}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Input (filename)
            </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 (filename)"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Output
            </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"
              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">
              Date
            </label>
            <input
              type="datetime-local"
              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={date ? new Date(date).toISOString().slice(0, 16) : ""}
              onChange={(e) =>
                setDate(
                  e.target.value ? new Date(e.target.value).toISOString() : ""
                )
              }
            />
          </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 File
      </button>

      <SlideInForm
        isOpen={isOpen}
        onClose={handleClose}
        title="Add New File"
        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.status === "pending"}
              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"
            >
              Add File
            </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">
              Dataset
            </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={dataset}
              onChange={(e) => setDataset(e.target.value)}
            >
              <option value="">Select a dataset</option>
              {datasets?.map((ds: string) => (
                <option key={ds} value={ds.split("/").pop()}>
                  {ds.split("/").pop()}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Input (filename)
            </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 (filename)"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
              Output
            </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"
              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">
              Date
            </label>
            <input
              type="datetime-local"
              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={date ? new Date(date).toISOString().slice(0, 16) : ""}
              onChange={(e) =>
                setDate(
                  e.target.value ? new Date(e.target.value).toISOString() : ""
                )
              }
            />
          </div>
        </form>
      </SlideInForm>
    </>
  );
}
