"use client";

import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useReportDesigner } from "@/contexts/ReportDesignerContext";
import { Plus, Copy, Trash2, GripVertical, Edit2, Check, X } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export function PageListPanel() {
  const {
    layoutConfig,
    currentPageId,
    addPage,
    deletePage,
    duplicatePage,
    reorderPages,
    selectPage,
    updatePageSettings,
  } = useReportDesigner();

  const [editingPageId, setEditingPageId] = useState<string | null>(null);
  const [editingName, setEditingName] = useState("");
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);

  const handleStartEdit = (pageId: string, currentName: string) => {
    setEditingPageId(pageId);
    setEditingName(currentName);
  };

  const handleSaveEdit = () => {
    if (editingPageId && editingName.trim()) {
      updatePageSettings(editingPageId, { page_name: editingName.trim() });
    }
    setEditingPageId(null);
    setEditingName("");
  };

  const handleCancelEdit = () => {
    setEditingPageId(null);
    setEditingName("");
  };

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

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    if (draggedIndex === null || draggedIndex === index) return;

    // 실시간으로 순서 변경하지 않고, drop 시에만 변경
  };

  const handleDrop = (e: React.DragEvent, targetIndex: number) => {
    e.preventDefault();
    if (draggedIndex === null) return;

    const sourceIndex = draggedIndex;
    if (sourceIndex !== targetIndex) {
      reorderPages(sourceIndex, targetIndex);
    }

    setDraggedIndex(null);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  return (
    <div className="bg-background flex h-full w-32 flex-col border-r">
      {/* 헤더 */}
      <div className="flex items-center justify-between border-b px-2 py-1.5">
        <h3 className="text-[10px] font-semibold">페이지</h3>
        <Button size="sm" variant="ghost" className="h-5 w-5 p-0" onClick={() => addPage()}>
          <Plus className="h-3 w-3" />
        </Button>
      </div>

      {/* 페이지 목록 */}
      <div className="flex-1 overflow-hidden">
        <ScrollArea className="h-full p-1">
          <div className="space-y-1">
            {layoutConfig.pages
              .sort((a, b) => a.page_order - b.page_order)
              .map((page, index) => (
                <div
                  key={page.page_id}
                  className={`group relative cursor-pointer rounded border p-1.5 transition-all ${
                    page.page_id === currentPageId
                      ? "border-primary bg-primary/10"
                      : "border-border hover:border-primary/50 hover:bg-accent/50"
                  } ${draggedIndex === index ? "opacity-50" : ""}`}
                  onClick={() => selectPage(page.page_id)}
                  onDragOver={(e) => handleDragOver(e, index)}
                  onDrop={(e) => handleDrop(e, index)}
                >
                  <div className="flex items-center gap-1">
                    {/* 드래그 핸들 */}
                    <div
                      draggable
                      onDragStart={(e) => {
                        e.stopPropagation();
                        handleDragStart(index);
                      }}
                      onDragEnd={handleDragEnd}
                      className="text-muted-foreground cursor-grab opacity-0 transition-opacity group-hover:opacity-100 active:cursor-grabbing"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <GripVertical className="h-2.5 w-2.5" />
                    </div>

                    {/* 페이지 정보 */}
                    <div className="min-w-0 flex-1">
                      {editingPageId === page.page_id ? (
                        <div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
                          <Input
                            value={editingName}
                            onChange={(e) => setEditingName(e.target.value)}
                            onKeyDown={(e) => {
                              if (e.key === "Enter") handleSaveEdit();
                              if (e.key === "Escape") handleCancelEdit();
                            }}
                            className="h-5 text-[10px]"
                            autoFocus
                          />
                          <Button size="sm" variant="ghost" className="h-4 w-4 p-0" onClick={handleSaveEdit}>
                            <Check className="h-2.5 w-2.5" />
                          </Button>
                          <Button size="sm" variant="ghost" className="h-4 w-4 p-0" onClick={handleCancelEdit}>
                            <X className="h-2.5 w-2.5" />
                          </Button>
                        </div>
                      ) : (
                        <div className="truncate text-[10px] font-medium">{page.page_name}</div>
                      )}
                      <div className="text-muted-foreground text-[8px]">
                        {page.width}x{page.height}mm
                      </div>
                    </div>

                    {/* 액션 메뉴 */}
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                        <Button
                          size="sm"
                          variant="ghost"
                          className="h-4 w-4 p-0 opacity-0 transition-opacity group-hover:opacity-100"
                        >
                          <span className="sr-only">메뉴</span>
                          <span className="text-[10px] leading-none">⋮</span>
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            handleStartEdit(page.page_id, page.page_name);
                          }}
                        >
                          <Edit2 className="mr-2 h-3 w-3" />
                          이름 변경
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            duplicatePage(page.page_id);
                          }}
                        >
                          <Copy className="mr-2 h-3 w-3" />
                          복제
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            deletePage(page.page_id);
                          }}
                          disabled={layoutConfig.pages.length <= 1}
                          className="text-destructive focus:text-destructive"
                        >
                          <Trash2 className="mr-2 h-3 w-3" />
                          삭제
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </div>
              ))}
          </div>
        </ScrollArea>
      </div>

      {/* 푸터 */}
      <div className="border-t p-1">
        <Button size="sm" variant="outline" className="h-6 w-full text-[10px]" onClick={() => addPage()}>
          <Plus className="mr-1 h-3 w-3" />추가
        </Button>
      </div>
    </div>
  );
}
