'use client';

import React, { useState } from 'react';
import {
  ChevronUp,
  ChevronDown,
  Pencil,
  Trash2,
  Plus,
  Check,
  X,
  ChevronRight,
  Save,
  RotateCcw,
  Loader2,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ChecklistCategory, ChecklistSubItem } from '../types';

interface ChecklistTemplateEditorProps {
  categories: ChecklistCategory[];
  hasChanges: boolean;
  saving: boolean;
  loading?: boolean;
  error?: string | null;
  // 카테고리
  onAddCategory: () => void;
  onUpdateCategoryTitle: (categoryId: string, title: string) => void;
  onDeleteCategory: (categoryId: string) => void;
  onMoveCategoryUp: (index: number) => void;
  onMoveCategoryDown: (index: number) => void;
  // 하위 항목
  onAddSubItem: (categoryId: string) => void;
  onUpdateSubItemName: (categoryId: string, subItemId: string, name: string) => void;
  onDeleteSubItem: (categoryId: string, subItemId: string) => void;
  onMoveSubItemUp: (categoryId: string, index: number) => void;
  onMoveSubItemDown: (categoryId: string, index: number) => void;
  // 저장/초기화
  onSave: () => void;
  onReset: () => void;
}

export function ChecklistTemplateEditor({
  categories,
  hasChanges,
  saving,
  loading,
  error,
  onAddCategory,
  onUpdateCategoryTitle,
  onDeleteCategory,
  onMoveCategoryUp,
  onMoveCategoryDown,
  onAddSubItem,
  onUpdateSubItemName,
  onDeleteSubItem,
  onMoveSubItemUp,
  onMoveSubItemDown,
  onSave,
  onReset,
}: ChecklistTemplateEditorProps) {
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
    new Set(categories.map(c => c.id))
  );

  const toggleExpand = (categoryId: string) => {
    setExpandedCategories(prev => {
      const next = new Set(prev);
      if (next.has(categoryId)) next.delete(categoryId);
      else next.add(categoryId);
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-32 text-gray-400 text-sm gap-2">
        <Loader2 className="h-4 w-4 animate-spin" />
        점검표 로딩 중...
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-32 text-red-500 text-sm">
        {error}
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {/* 카테고리 목록 */}
      <div className="space-y-1.5">
        {categories.map((category, catIdx) => (
          <CategoryEditor
            key={category.id}
            category={category}
            index={catIdx}
            isFirst={catIdx === 0}
            isLast={catIdx === categories.length - 1}
            isExpanded={expandedCategories.has(category.id)}
            onToggleExpand={() => toggleExpand(category.id)}
            onUpdateTitle={(title) => onUpdateCategoryTitle(category.id, title)}
            onDelete={() => onDeleteCategory(category.id)}
            onMoveUp={() => onMoveCategoryUp(catIdx)}
            onMoveDown={() => onMoveCategoryDown(catIdx)}
            onAddSubItem={() => onAddSubItem(category.id)}
            onUpdateSubItemName={(subItemId, name) => onUpdateSubItemName(category.id, subItemId, name)}
            onDeleteSubItem={(subItemId) => onDeleteSubItem(category.id, subItemId)}
            onMoveSubItemUp={(idx) => onMoveSubItemUp(category.id, idx)}
            onMoveSubItemDown={(idx) => onMoveSubItemDown(category.id, idx)}
          />
        ))}
      </div>

      {/* 카테고리 추가 */}
      <button
        type="button"
        onClick={onAddCategory}
        className="w-full flex items-center justify-center gap-1.5 py-2 text-xs text-blue-600 bg-blue-50 rounded-lg border border-dashed border-blue-200 hover:bg-blue-100 transition-colors"
      >
        <Plus className="h-3.5 w-3.5" />
        카테고리 추가
      </button>

      {/* 저장/초기화 */}
      <div className="flex items-center gap-2 pt-2 border-t border-gray-200">
        <button
          type="button"
          onClick={onReset}
          disabled={!hasChanges}
          className="flex-1 flex items-center justify-center gap-1.5 py-2 text-xs text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
        >
          <RotateCcw className="h-3.5 w-3.5" />
          초기화
        </button>
        <button
          type="button"
          onClick={() => onSave()}
          disabled={!hasChanges || saving}
          className="flex-1 flex items-center justify-center gap-1.5 py-2 text-xs text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
        >
          <Save className="h-3.5 w-3.5" />
          {saving ? '저장 중...' : '저장'}
        </button>
      </div>

      {hasChanges && (
        <p className="text-[10px] text-amber-600 text-center">
          저장하지 않은 변경사항이 있습니다
        </p>
      )}
    </div>
  );
}

// ===== 카테고리 편집 =====

interface CategoryEditorProps {
  category: ChecklistCategory;
  index: number;
  isFirst: boolean;
  isLast: boolean;
  isExpanded: boolean;
  onToggleExpand: () => void;
  onUpdateTitle: (title: string) => void;
  onDelete: () => void;
  onMoveUp: () => void;
  onMoveDown: () => void;
  onAddSubItem: () => void;
  onUpdateSubItemName: (subItemId: string, name: string) => void;
  onDeleteSubItem: (subItemId: string) => void;
  onMoveSubItemUp: (index: number) => void;
  onMoveSubItemDown: (index: number) => void;
}

function CategoryEditor({
  category,
  index,
  isFirst,
  isLast,
  isExpanded,
  onToggleExpand,
  onUpdateTitle,
  onDelete,
  onMoveUp,
  onMoveDown,
  onAddSubItem,
  onUpdateSubItemName,
  onDeleteSubItem,
  onMoveSubItemUp,
  onMoveSubItemDown,
}: CategoryEditorProps) {
  const [editing, setEditing] = useState(false);
  const [editValue, setEditValue] = useState(category.title);

  const handleSaveTitle = () => {
    const trimmed = editValue.trim();
    if (trimmed) {
      onUpdateTitle(trimmed);
    } else {
      setEditValue(category.title);
    }
    setEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') handleSaveTitle();
    if (e.key === 'Escape') {
      setEditValue(category.title);
      setEditing(false);
    }
  };

  return (
    <div className="bg-gray-50 rounded-lg border border-gray-200 overflow-hidden">
      {/* 카테고리 헤더 */}
      <div className="flex items-center gap-1 px-2 py-1.5">
        {/* 순서 변경 */}
        <div className="flex flex-col">
          <button
            type="button"
            onClick={onMoveUp}
            disabled={isFirst}
            className="p-0.5 text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ChevronUp className="h-3 w-3" />
          </button>
          <button
            type="button"
            onClick={onMoveDown}
            disabled={isLast}
            className="p-0.5 text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ChevronDown className="h-3 w-3" />
          </button>
        </div>

        {/* 펼치기/접기 */}
        <button
          type="button"
          onClick={onToggleExpand}
          className="p-0.5 text-gray-500"
        >
          <ChevronRight className={cn(
            'h-3.5 w-3.5 transition-transform',
            isExpanded && 'rotate-90'
          )} />
        </button>

        {/* 제목 */}
        {editing ? (
          <div className="flex-1 flex items-center gap-1">
            <input
              type="text"
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              onBlur={handleSaveTitle}
              onKeyDown={handleKeyDown}
              className="flex-1 text-xs px-1.5 py-0.5 border border-blue-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"
              autoFocus
            />
            <button type="button" onClick={handleSaveTitle} className="p-0.5 text-green-600">
              <Check className="h-3 w-3" />
            </button>
            <button type="button" onClick={() => { setEditValue(category.title); setEditing(false); }} className="p-0.5 text-gray-400">
              <X className="h-3 w-3" />
            </button>
          </div>
        ) : (
          <span className="flex-1 text-xs font-medium text-gray-800 truncate">
            {index + 1}. {category.title}
          </span>
        )}

        {/* 항목 수 */}
        <span className="text-[10px] text-gray-400 mr-1">
          {category.subItems.length}
        </span>

        {/* 편집/삭제 */}
        {!editing && (
          <>
            <button
              type="button"
              onClick={() => { setEditValue(category.title); setEditing(true); }}
              className="p-1 text-gray-400 hover:text-blue-600 rounded"
            >
              <Pencil className="h-3 w-3" />
            </button>
            <button
              type="button"
              onClick={onDelete}
              className="p-1 text-gray-400 hover:text-red-600 rounded"
            >
              <Trash2 className="h-3 w-3" />
            </button>
          </>
        )}
      </div>

      {/* 하위 항목 */}
      {isExpanded && (
        <div className="border-t border-gray-200 bg-white">
          {category.subItems.map((subItem, subIdx) => (
            <SubItemEditor
              key={subItem.id}
              subItem={subItem}
              index={subIdx}
              isFirst={subIdx === 0}
              isLast={subIdx === category.subItems.length - 1}
              onUpdateName={(name) => onUpdateSubItemName(subItem.id, name)}
              onDelete={() => onDeleteSubItem(subItem.id)}
              onMoveUp={() => onMoveSubItemUp(subIdx)}
              onMoveDown={() => onMoveSubItemDown(subIdx)}
            />
          ))}

          {/* 항목 추가 */}
          <button
            type="button"
            onClick={onAddSubItem}
            className="w-full flex items-center justify-center gap-1 py-1.5 text-[10px] text-blue-500 hover:bg-blue-50 transition-colors"
          >
            <Plus className="h-3 w-3" />
            항목 추가
          </button>
        </div>
      )}
    </div>
  );
}

// ===== 하위 항목 편집 =====

interface SubItemEditorProps {
  subItem: ChecklistSubItem;
  index: number;
  isFirst: boolean;
  isLast: boolean;
  onUpdateName: (name: string) => void;
  onDelete: () => void;
  onMoveUp: () => void;
  onMoveDown: () => void;
}

function SubItemEditor({
  subItem,
  index,
  isFirst,
  isLast,
  onUpdateName,
  onDelete,
  onMoveUp,
  onMoveDown,
}: SubItemEditorProps) {
  const [editing, setEditing] = useState(false);
  const [editValue, setEditValue] = useState(subItem.name);

  const handleSave = () => {
    const trimmed = editValue.trim();
    if (trimmed) {
      onUpdateName(trimmed);
    } else {
      setEditValue(subItem.name);
    }
    setEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') handleSave();
    if (e.key === 'Escape') {
      setEditValue(subItem.name);
      setEditing(false);
    }
  };

  return (
    <div className="flex items-center gap-1 px-2 py-1 border-b border-gray-100 last:border-b-0 hover:bg-gray-50">
      {/* 순서 변경 */}
      <div className="flex flex-col ml-4">
        <button
          type="button"
          onClick={onMoveUp}
          disabled={isFirst}
          className="p-0.5 text-gray-300 hover:text-gray-500 disabled:opacity-30 disabled:cursor-not-allowed"
        >
          <ChevronUp className="h-2.5 w-2.5" />
        </button>
        <button
          type="button"
          onClick={onMoveDown}
          disabled={isLast}
          className="p-0.5 text-gray-300 hover:text-gray-500 disabled:opacity-30 disabled:cursor-not-allowed"
        >
          <ChevronDown className="h-2.5 w-2.5" />
        </button>
      </div>

      {/* 이름 */}
      {editing ? (
        <div className="flex-1 flex items-center gap-1">
          <input
            type="text"
            value={editValue}
            onChange={(e) => setEditValue(e.target.value)}
            onBlur={handleSave}
            onKeyDown={handleKeyDown}
            className="flex-1 text-[11px] px-1.5 py-0.5 border border-blue-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"
            autoFocus
          />
          <button type="button" onClick={handleSave} className="p-0.5 text-green-600">
            <Check className="h-2.5 w-2.5" />
          </button>
        </div>
      ) : (
        <span
          className="flex-1 text-[11px] text-gray-700 cursor-pointer hover:text-blue-600 truncate"
          onClick={() => { setEditValue(subItem.name); setEditing(true); }}
        >
          {subItem.name}
        </span>
      )}

      {/* 편집/삭제 */}
      {!editing && (
        <>
          <button
            type="button"
            onClick={() => { setEditValue(subItem.name); setEditing(true); }}
            className="p-0.5 text-gray-300 hover:text-blue-500"
          >
            <Pencil className="h-2.5 w-2.5" />
          </button>
          <button
            type="button"
            onClick={onDelete}
            className="p-0.5 text-gray-300 hover:text-red-500"
          >
            <Trash2 className="h-2.5 w-2.5" />
          </button>
        </>
      )}
    </div>
  );
}

