"use client";

import React, { useState } from "react";
import { ListColumn, ListWidgetConfig } from "../../types";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Trash2, GripVertical } from "lucide-react";

interface ManualColumnEditorProps {
  config: ListWidgetConfig;
  onConfigChange: (updates: Partial<ListWidgetConfig>) => void;
}

/**
 * 수동 컬럼 편집 컴포넌트
 * - 사용자가 직접 컬럼 추가/삭제
 * - 컬럼명과 데이터 필드 직접 매핑
 * - 드래그 앤 드롭으로 순서 변경
 */
export function ManualColumnEditor({ config, onConfigChange }: ManualColumnEditorProps) {
  const columns = config.columns || [];
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);

  // 새 컬럼 추가
  const handleAddColumn = () => {
    const newCol: ListColumn = {
      id: `col_${Date.now()}`,
      label: `컬럼 ${columns.length + 1}`,
      field: "",
      align: "left",
      visible: true,
    };
    onConfigChange({ columns: [...columns, newCol] });
  };

  // 컬럼 삭제
  const handleRemove = (id: string) => {
    onConfigChange({ columns: columns.filter((col) => col.id !== id) });
  };

  // 컬럼 속성 업데이트
  const handleUpdate = (id: string, updates: Partial<ListColumn>) => {
    onConfigChange({ columns: columns.map((col) => (col.id === id ? { ...col, ...updates } : col)) });
  };

  // 드래그 시작
  const handleDragStart = (index: number) => {
    setDraggedIndex(index);
  };

  // 드래그 오버 - 실시간으로 순서 변경하여 UI 업데이트
  const handleDragOver = (e: React.DragEvent, hoverIndex: number) => {
    e.preventDefault();
    if (draggedIndex === null || draggedIndex === hoverIndex) return;

    const newColumns = [...columns];
    const draggedItem = newColumns[draggedIndex];
    newColumns.splice(draggedIndex, 1);
    newColumns.splice(hoverIndex, 0, draggedItem);

    setDraggedIndex(hoverIndex);
    onConfigChange({ columns: newColumns });
  };

  // 드롭
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDraggedIndex(null);
  };

  // 드래그 종료
  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  return (
    <div>
      {/* 헤더 */}
      <div className="mb-3 flex items-center justify-between">
        <p className="text-[10px] text-muted-foreground">직접 컬럼을 추가하고 데이터 필드를 매핑하세요</p>
        <button
          onClick={handleAddColumn}
          className="bg-primary hover:bg-primary/90 flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium text-primary-foreground transition-colors"
        >
          <Plus className="h-3 w-3" />
          컬럼 추가
        </button>
      </div>

      <div className="space-y-1.5">
        {columns.map((col, index) => (
          <div
            key={col.id}
            draggable
            onDragStart={(e) => {
              handleDragStart(index);
              e.currentTarget.style.cursor = "grabbing";
            }}
            onDragOver={(e) => handleDragOver(e, index)}
            onDrop={handleDrop}
            onDragEnd={(e) => {
              handleDragEnd();
              e.currentTarget.style.cursor = "grab";
            }}
            className={`group relative rounded-md border border-border bg-background shadow-sm transition-all hover:border-border hover:shadow-sm ${
              draggedIndex === index ? "scale-95 opacity-50" : ""
            } cursor-grab active:cursor-grabbing`}
          >
            {/* 헤더 */}
            <div className="flex items-center gap-2 px-2.5 py-2">
              <GripVertical className="group-hover:text-primary h-3.5 w-3.5 shrink-0 text-muted-foreground transition-colors" />
              <span className="text-[11px] font-medium text-foreground">컬럼 {index + 1}</span>
              <button
                onClick={() => handleRemove(col.id)}
                className="ml-auto flex h-5 w-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
              >
                <Trash2 className="h-3 w-3" />
              </button>
            </div>

            {/* 설정 영역 */}
            <div className="border-t border-border bg-muted/50 px-2.5 py-1.5">
              <div className="flex flex-col gap-1.5">
                {/* 표시 이름 */}
                <div className="min-w-0">
                  <Input
                    value={col.label}
                    onChange={(e) => handleUpdate(col.id, { label: e.target.value })}
                    placeholder="표시 이름"
                    className="focus:border-primary focus:ring-primary/20 h-6 w-full border-border bg-background px-1.5 text-[10px] placeholder:text-muted-foreground focus:ring-1"
                    style={{ fontSize: "10px" }}
                  />
                </div>

                {/* 데이터 필드 */}
                <div className="min-w-0">
                  <Input
                    value={col.field}
                    onChange={(e) => handleUpdate(col.id, { field: e.target.value })}
                    placeholder="데이터 필드"
                    className="focus:border-primary focus:ring-primary/20 h-6 w-full border-border bg-background px-1.5 text-[10px] placeholder:text-muted-foreground focus:ring-1"
                    style={{ fontSize: "10px" }}
                  />
                </div>

                {/* 정렬 */}
                <div className="min-w-0">
                  <Select
                    value={col.align}
                    onValueChange={(value: "left" | "center" | "right") => handleUpdate(col.id, { align: value })}
                  >
                    <SelectTrigger
                      className="focus:border-primary focus:ring-primary/20 h-6 w-full border-border bg-background px-1.5 text-[10px] focus:ring-1 [&>span]:leading-none [&>svg]:h-3 [&>svg]:w-3"
                      style={{ fontSize: "10px", height: "24px", minHeight: "24px" }}
                    >
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="min-w-[4rem]">
                      <SelectItem value="left" className="py-1 text-[10px]">
                        왼쪽
                      </SelectItem>
                      <SelectItem value="center" className="py-1 text-[10px]">
                        가운데
                      </SelectItem>
                      <SelectItem value="right" className="py-1 text-[10px]">
                        오른쪽
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {columns.length === 0 && (
        <div className="mt-3 flex items-center gap-2 rounded-md border border-warning bg-warning/10 px-3 py-2">
          <span className="text-warning">⚠️</span>
          <span className="text-[10px] text-warning">컬럼을 추가하여 시작하세요</span>
          <button
            onClick={handleAddColumn}
            className="bg-primary hover:bg-primary/90 ml-auto flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium text-white transition-colors"
          >
            <Plus className="h-3 w-3" />
            추가
          </button>
        </div>
      )}
    </div>
  );
}
