import React from "react";
import { Draggable } from "react-beautiful-dnd";
import styles from "./Link.module.css";

export type EditableLink = {
  name: string;
  url: string;
  active: boolean;
  clicks: number;
};

interface LinkProps {
  index: number;
  link: EditableLink;
  onChange: (newLink: EditableLink) => void;
  onDelete: () => void;
}

const DeleteIcon = () => (
  <svg
    color="palette.blueGrey7"
    viewBox="0 0 16 16"
    enableBackground="new 0 0 24 24"
    className="h-4 inline"
  >
    <path
      fill="none"
      stroke="currentColor"
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M6 2.5v-2h4v2M1 2.5h14M9.533 13.5l.25-9M6.217 4.5l.25 9M2.661 4.5l.889 11h8.9l.888-11"
    ></path>
  </svg>
);

const DragIcon = () => (
  <svg width="4" height="16" viewBox="0 0 4 16">
    <path d="M0 2C0 .897.897 0 2 0s2 .897 2 2-.897 2-2 2-2-.897-2-2M0 8c0-1.103.897-2 2-2s2 .897 2 2-.897 2-2 2-2-.897-2-2M0 14c0-1.103.897-2 2-2s2 .897 2 2-.897 2-2 2-2-.897-2-2"></path>
  </svg>
);

const Link: React.FC<LinkProps> = ({ index, link, onChange, onDelete }) => {
  return (
    <Draggable key={index} draggableId={index.toString()} index={index}>
      {(provided) => (
        <div {...provided.draggableProps} ref={provided.innerRef}>
          <div className="p-2 container flex">
            <div
              className="flex justify-center w-1/12 flex items-center border-r bg-white rounded-sm shadow-sm"
              {...provided.dragHandleProps}
            >
              <DragIcon />
            </div>
            <div className="w-11/12 space-y-2 bg-white rounded-sm shadow-sm">
              <div className="flex justify-between items-center px-2 pt-2">
                <input
                  type="text"
                  placeholder="Edit Title"
                  value={link.name}
                  className={styles.input}
                  onChange={(e) => onChange({ ...link, name: e.target.value })}
                />

                <input
                  type="checkbox"
                  onChange={(e) =>
                    onChange({ ...link, active: e.target.checked })
                  }
                  defaultChecked={link.active}
                  className="float-right"
                />
              </div>

              <div className="flex justify-between items-center px-2 pb-2">
                <input
                  type="url"
                  placeholder="https://url"
                  value={link.url}
                  className={styles.input}
                  onChange={(e) => onChange({ ...link, url: e.target.value })}
                />

                <button onClick={onDelete}>
                  <DeleteIcon />
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </Draggable>
  );
};

export default Link;
