"use client";
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowUpDown,
  ChevronDown,
  ChevronUp,
  GripVertical,
} from "lucide-react";
import PageHeader from "@/components/modals/ui/PageHeader";

export const DEFAULT_CATEGORIES = [
  "Tablet",
  "Capsule",
  "Syrup",
  "Drops",
  "Oint",
  "Powder",
  "Injection",
  "Surg. Items",
];
export default function CategoryOrderPage({
  onBack,
  onClose,
}: {
  onBack?: () => void;
  onClose?: () => void;
}) {
  const router = useRouter();

  const [categories, setCategories] = useState<string[]>(() => {
    try {
      const saved = localStorage.getItem("category-order");
      return saved ? JSON.parse(saved) : DEFAULT_CATEGORIES;
    } catch {
      return DEFAULT_CATEGORIES;
    }
  });

  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [overIndex, setOverIndex] = useState<number | null>(null);
  const dragIndex = useRef<number | null>(null);

  const handleDragStart = (index: number) => {
    dragIndex.current = index;
    setDraggedIndex(index);
  };

  const handleDragEnter = (index: number) => {
    if (dragIndex.current === null || dragIndex.current === index) return;
    setOverIndex(index);

    const updated = [...categories];
    const dragged = updated.splice(dragIndex.current, 1)[0];
    updated.splice(index, 0, dragged);
    dragIndex.current = index;
    setCategories(updated);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
    setOverIndex(null);
    dragIndex.current = null;
  };
  const move = (index: number, direction: -1 | 1) => {
    const newIndex = index + direction;
    if (newIndex < 0 || newIndex >= categories.length) return;
    const updated = [...categories];
    [updated[index], updated[newIndex]] = [updated[newIndex], updated[index]];
    setCategories(updated);
  };

  const handleSave = () => {
    localStorage.setItem("category-order", JSON.stringify(categories));
    onBack?.();
  };

  return (
    <div className="min-h-screen bg-[#f7f7f8] flex flex-col">
      <PageHeader
        icon={<ArrowUpDown size={20} />}
        title="Medicine category order"
        subtitle="Drag to reorder medicine categories"
          onClose={onClose}


      />

      <main className="flex-1 max-w-[600px] w-full mx-auto p-7">
        <div className="bg-white border border-[#e5e7eb] rounded-2xl p-6">
          <div className="flex flex-col gap-2.5">
            {categories.map((cat, index) => {
              const isDragging = draggedIndex === index;
              return (
                <div
                  key={cat}
                  draggable
                  onDragStart={() => handleDragStart(index)}
                  onDragEnter={() => handleDragEnter(index)}
                  onDragEnd={handleDragEnd}
                  onDragOver={(e) => e.preventDefault()}
                  style={{
                    transition:
                      "transform 200ms ease, opacity 200ms ease, box-shadow 200ms ease",
                    opacity: isDragging ? 0.4 : 1,
                    transform: isDragging ? "scale(1.02)" : "scale(1)",
                    boxShadow: isDragging
                      ? "0 8px 24px rgba(212,83,126,0.15)"
                      : "none",
                    zIndex: isDragging ? 10 : 1,
                    position: "relative",
                  }}
                  className={`flex items-center gap-3 rounded-xl px-4 py-3 select-none
                ${isDragging ? "bg-[#fceef3]" : "bg-[#f7f7f8] hover:bg-[#fceef3]"}`}
                >
                  <GripVertical
                    size={18}
                    className="text-[#9ca3af] flex-shrink-0 cursor-grab active:cursor-grabbing"
                  />

                  <span className="text-base font-medium text-[#111111] flex-1">
                    {cat}
                  </span>

                  <div className="flex items-center gap-1">
                    {/* <button
                      onClick={() => move(index, -1)}
                      disabled={index === 0}
                      className="w-8 h-8 rounded-lg flex items-center justify-center text-[#4b5563] bg-white border border-[#e5e7eb] disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#fceef3] hover:text-[#d4537e] cursor-pointer transition-colors"
                    >
                      <ChevronUp size={16} />
                    </button> */}
                    {/* <button
                      onClick={() => move(index, 1)}
                      disabled={index === categories.length - 1}
                      className="w-8 h-8 rounded-lg flex items-center justify-center text-[#4b5563] bg-white border border-[#e5e7eb] disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#fceef3] hover:text-[#d4537e] cursor-pointer transition-colors"
                    >
                      <ChevronDown size={16} />
                    </button> */}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <p className="text-xs text-[#9ca3af] text-center mt-4">
          Drag items to reorder • Changes apply to medicine tabs
        </p>
      </main>

      <div className="sticky bottom-0 bg-white border-t border-[#e5e7eb] px-7 py-4">
        <div className="max-w-[600px] mx-auto flex justify-end gap-3">
          <button
            onClick={() => onBack?.()}
            className="text-sm font-medium text-[#374151] bg-white border border-[#e5e7eb] rounded-xl px-5 py-2.5 cursor-pointer hover:bg-[#f7f7f8] transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            className="text-sm font-semibold text-white bg-[#d4537e] hover:bg-[#993556] rounded-xl px-5 py-2.5 cursor-pointer transition-colors"
          >
            Save order
          </button>
        </div>
      </div>
    </div>
  );
}
