import React, { useState } from "react";
import { DragDropContext, Droppable, DropResult } from "react-beautiful-dnd";
import Link, { EditableLink } from "components/Editor/Link";

import { useDragDrop } from "./useDragDrop";
import equal from "fast-deep-equal";

interface EditorProps {
  links: EditableLink[];
  setLinks: React.Dispatch<React.SetStateAction<EditableLink[]>>;
}

const Editor: React.FC<EditorProps> = ({ links, setLinks }) => {
  const [formState, setFormState] = useState<EditableLink[]>(links);
  const { displayDragDrop } = useDragDrop();

  const handleOnDragEnd = (result: DropResult) => {
    if (!result?.destination) return;

    const items = Array.from(formState);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    setFormState(items);
  };

  /*note that we need to make the new links name render with nothing*/
  const handleOnClickAdd = () =>
    setFormState([
      ...formState,
      {
        name: "",
        url: "",
        clicks: 0,
        active: true,
      },
    ]);

  // useEffect(() => {
  //   setFormState(links);
  // }, [links]);

  const onSubmit = () => {
    // const res = await updateLinks(formState);
    // setLinks(res.data);
  };

  const didEdit = !equal(formState, links);

  console.log({ formState, didEdit });

  return (
    <div className="space-y-4 bg-gray-100 w-1/2 p-2">
      {/* add link button */}
      <button
        className="block flex py-2 items-center justify-center rounded-md bg-purple-600 hover:bg-purple-500 cursor-pointer text-white w-full"
        onClick={handleOnClickAdd}
      >
        Add New Link
      </button>
      {displayDragDrop && (
        <DragDropContext onDragEnd={handleOnDragEnd}>
          <Droppable droppableId="links">
            {(provided) => (
              <div
                className="links"
                {...provided.droppableProps}
                ref={provided.innerRef}
              >
                {formState.map((link, index) => (
                  <Link
                    key={index}
                    index={index}
                    link={link}
                    onChange={(newLink: EditableLink) =>
                      setFormState([
                        ...formState.slice(0, index),
                        newLink,
                        ...formState.slice(index + 1),
                      ])
                    }
                    onDelete={() =>
                      setFormState([
                        ...formState.slice(0, index),
                        ...formState.slice(index + 1),
                      ])
                    }
                  />
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      )}
    </div>
  );
};

export default Editor;
