"use client";

import React, { useState } from "react";
import { ListColumn, ListWidgetConfig, QueryResult } 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";
import { Checkbox } from "@/components/ui/checkbox";

interface V2ColumnEditorProps {
  queryResult: QueryResult | null;
  config: ListWidgetConfig;
  onConfigChange: (updates: Partial<ListWidgetConfig>) => void;
}

/**
 * 통합 컬럼 에디터
 * - 쿼리 실행 시 자동으로 컬럼 추출
 * - 모든 필드 편집 가능 (필드명, 표시 이름, 정렬)
 * - 수동으로 컬럼 추가 가능
 */
export function V2ColumnEditor({ queryResult, config, onConfigChange }: V2ColumnEditorProps) {
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);

  const columns = config.columns || [];
  const sampleData = queryResult?.rows[0] || {};

  // 컬럼 추가
  const handleAddColumn = () => {
    const newColumn: ListColumn = {
      id: `col_${Date.now()}`,
      field: "",
      label: "",
      visible: true,
      align: "left",
    };

    onConfigChange({
      columns: [...columns, newColumn],
    });
  };

  // 컬럼 삭제
  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 handleToggle = (id: string) => {
    onConfigChange({
      columns: columns.map((col) => (col.id === id ? { ...col, visible: !col.visible } : col)),
    });
  };

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

  // 드래그 오버
  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();

    if (draggedIndex === null || draggedIndex === index) return;

    const newColumns = [...columns];
    const draggedItem = newColumns[draggedIndex];

    newColumns.splice(draggedIndex, 1);
    newColumns.splice(index, 0, draggedItem);

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

  // 드롭
  const handleDrop = () => {
    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) => {
          const preview = sampleData[col.field];
          const previewText =
            preview !== undefined && preview !== null
              ? typeof preview === "object"
                ? JSON.stringify(preview).substring(0, 30)
                : String(preview).substring(0, 30)
              : "";

          return (
            <div
              key={col.id}
              onDragOver={(e) => handleDragOver(e, index)}
              onDrop={handleDrop}
              className={`group relative rounded-md border transition-all ${
                col.visible
                  ? "border-primary/40 bg-primary/5 shadow-sm"
                  : "border-border bg-background hover:border-border hover:shadow-sm"
              } ${draggedIndex === index ? "scale-95 opacity-50" : ""}`}
            >
              {/* 헤더 */}
              <div className="flex items-center gap-2 px-2.5 py-2">
                <Checkbox
                  checked={col.visible}
                  onCheckedChange={() => handleToggle(col.id)}
                  className="data-[state=checked]:bg-primary data-[state=checked]:border-primary h-4 w-4 shrink-0 rounded-full"
                />
                <div
                  draggable
                  onDragStart={(e) => {
                    handleDragStart(index);
                    e.currentTarget.style.cursor = "grabbing";
                  }}
                  onDragEnd={(e) => {
                    handleDragEnd();
                    e.currentTarget.style.cursor = "grab";
                  }}
                  className="cursor-grab active:cursor-grabbing"
                >
                  <GripVertical className="group-hover:text-primary h-3.5 w-3.5 shrink-0 text-muted-foreground transition-colors" />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-1.5">
                    <span className="truncate text-[11px] font-medium text-foreground">
                      {col.field || "(필드명 없음)"}
                    </span>
                    {previewText && <span className="shrink-0 text-[9px] text-muted-foreground">예: {previewText}</span>}
                  </div>
                </div>
                <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>

              {/* 설정 영역 */}
              {col.visible && (
                <div className="border-t border-border bg-muted/50 px-2.5 py-1.5">
                  <div className="grid grid-cols-2 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">
                      <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>
        </div>
      )}
    </div>
  );
}
