import { Reorder, useDragControls } from "motion/react";
import type { RecipeIngredientSection } from "../../types/recipe";
import DeleteIconSmall from "../icons/DeleteIconSmall";
import DragIconSmall from "../icons/DragIconSmall";
import type { ReactNode } from "react";

interface IngredientSectionProps {
  section: RecipeIngredientSection;
  onChange: (id: string, name: string) => void;
  removeIngredientSectionHandler: (id: string) => void;
  allowDelete: boolean;
  children?: ReactNode;
};

export default function IngredientSection({ section, onChange, removeIngredientSectionHandler, allowDelete, children }: IngredientSectionProps) {
  const controls = useDragControls();

  return (
    <Reorder.Item
      key={section.Id}
      value={section}
      dragListener={false}
      dragControls={controls}
      className="select-none"
    >
      <div className="w-full bg-gray-100 px-4 py-2 flex items-center my-2">
        <p className="text-xs md:text-sm font-semibold">Group:</p>
        <input
          type="text"
          value={section.Name}
          onChange={(e) => onChange(section.Id, e.target.value)}
          placeholder="Group label"
          className="mx-2 px-2 py-1 border border-gray-300 flex-grow rounded-sm min-w-1"
        />

        <div className="flex gap-x-2 items-center">
          <button
            disabled={!allowDelete}
            className="p-2 pr-0 cursor-pointer text-gray-500 hover:text-red-500 disabled:text-gray-200 disabled:cursor-not-allowed duration-300"
            onClick={() => removeIngredientSectionHandler(section.Id)}
          >
            <DeleteIconSmall />
          </button>
          <div
            className="p-0 cursor-pointer touch-none"
            onPointerDown={(e) => {
              e.preventDefault();
              controls.start(e);
            }}
          >
            <DragIconSmall />
          </div>
        </div>
      </div>
      {children}
    </Reorder.Item>
  );
}

