"use client";

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

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

/**
 * 컬럼 선택 컴포넌트 (자동 모드)
 * - 쿼리 결과에서 컬럼 선택
 * - 컬럼명 변경
 * - 정렬, 너비, 정렬 방향 설정
 * - 드래그 앤 드롭으로 순서 변경
 */
export function ColumnSelector({ queryResult, config, onConfigChange }: ColumnSelectorProps) {
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);

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

  // 컬럼 선택/해제
  const handleToggle = (field: string) => {
    const exists = selectedColumns.find((col) => col.field === field);
    if (exists) {
      onConfigChange({ columns: selectedColumns.filter((col) => col.field !== field) });
    } else {
      const newCol: ListColumn = {
        id: `col_${selectedColumns.length}`,
        label: field,
        field,
        align: "left",
        visible: true,
      };
      onConfigChange({ columns: [...selectedColumns, newCol] });
    }
  };

  // 컬럼 라벨 변경
  const handleLabelChange = (field: string, label: string) => {
    onConfigChange({
      columns: selectedColumns.map((col) => (col.field === field ? { ...col, label } : col)),
    });
  };

  // 정렬 방향 변경
  const handleAlignChange = (field: string, align: "left" | "center" | "right") => {
    onConfigChange({
      columns: selectedColumns.map((col) => (col.field === field ? { ...col, align } : 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 = [...selectedColumns];
    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="space-y-1.5">
        {/* 선택된 컬럼을 먼저 순서대로 표시 */}
        {selectedColumns.map((selectedCol, columnIndex) => {
          const field = selectedCol.field;
          const preview = sampleData[field];
          const previewText =
            preview !== undefined && preview !== null
              ? typeof preview === "object"
                ? JSON.stringify(preview).substring(0, 30)
                : String(preview).substring(0, 30)
              : "";
          const isSelected = true;
          const isDraggable = true;

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

              {/* 설정 영역 */}
              {isSelected && selectedCol && (
                <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={selectedCol.label}
                        onChange={(e) => handleLabelChange(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={selectedCol.align}
                        onValueChange={(value: "left" | "center" | "right") => handleAlignChange(field, 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>
          );
        })}

        {/* 선택되지 않은 컬럼들을 아래에 표시 */}
        {availableColumns
          .filter((field) => !selectedColumns.find((col) => col.field === field))
          .map((field) => {
            const preview = sampleData[field];
            const previewText =
              preview !== undefined && preview !== null
                ? typeof preview === "object"
                  ? JSON.stringify(preview).substring(0, 30)
                  : String(preview).substring(0, 30)
                : "";

            return (
              <div
                key={field}
                className="group rounded-md border border-border bg-background transition-all hover:border-border hover:shadow-sm"
              >
                <div className="flex items-center gap-2 px-2.5 py-2">
                  <Checkbox
                    checked={false}
                    onCheckedChange={() => handleToggle(field)}
                    className="h-3.5 w-3.5 shrink-0"
                  />
                  <GripVertical className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-baseline gap-1.5">
                      <span className="truncate text-[11px] font-medium text-foreground">{field}</span>
                      {previewText && <span className="shrink-0 text-[9px] text-muted-foreground">예: {previewText}</span>}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
      </div>

      {selectedColumns.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">최소 1개 이상의 컬럼을 선택해주세요</span>
        </div>
      )}
    </div>
  );
}
