"use client";

import React, { useState } from "react";
import { ArrowLeft, Save, CheckCircle, XCircle, AlertCircle } from "lucide-react";
import { TableInfo, FieldMapping, ColumnInfo } from "../types/redesigned";

interface FieldMappingStepProps {
  fromTable?: TableInfo;
  toTable?: TableInfo;
  fieldMappings: FieldMapping[];
  onMappingsChange: (mappings: FieldMapping[]) => void;
  onBack: () => void;
  onSave: () => void;
}

export const FieldMappingStep: React.FC<FieldMappingStepProps> = ({
  fromTable,
  toTable,
  fieldMappings,
  onMappingsChange,
  onBack,
  onSave,
}) => {
  const [draggedField, setDraggedField] = useState<ColumnInfo | null>(null);

  const createMapping = (fromField: ColumnInfo, toField: ColumnInfo) => {
    const mapping: FieldMapping = {
      id: `${fromField.name}-${toField.name}`,
      fromField,
      toField,
      isValid: fromField.type === toField.type,
      validationMessage: fromField.type !== toField.type ? "타입이 다릅니다" : undefined
    };

    const newMappings = [...fieldMappings, mapping];
    onMappingsChange(newMappings);
  };

  const removeMapping = (mappingId: string) => {
    const newMappings = fieldMappings.filter(m => m.id !== mappingId);
    onMappingsChange(newMappings);
  };

  const handleDragStart = (field: ColumnInfo) => {
    setDraggedField(field);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const handleDrop = (e: React.DragEvent, toField: ColumnInfo) => {
    e.preventDefault();
    if (draggedField) {
      createMapping(draggedField, toField);
      setDraggedField(null);
    }
  };

  const getMappedFromField = (toFieldName: string) => {
    return fieldMappings.find(m => m.toField.name === toFieldName)?.fromField;
  };

  const isFieldMapped = (fieldName: string) => {
    return fieldMappings.some(m => m.fromField.name === fieldName || m.toField.name === fieldName);
  };

  return (
    <div className="space-y-8">
      <div className="text-center">
        <h2 className="text-2xl font-bold text-foreground mb-2">
          필드 매핑
        </h2>
        <p className="text-muted-foreground">
          소스 테이블의 필드를 대상 테이블의 필드에 드래그하여 매핑하세요
        </p>
      </div>

      {/* 매핑 통계 */}
      <div className="grid grid-cols-4 gap-4">
        <div className="bg-accent p-4 rounded-lg border border-primary/20">
          <div className="text-2xl font-bold text-primary">{fieldMappings.length}</div>
          <div className="text-sm text-primary">총 매핑</div>
        </div>
        <div className="bg-emerald-50 p-4 rounded-lg border border-emerald-200">
          <div className="text-2xl font-bold text-green-900">
            {fieldMappings.filter(m => m.isValid).length}
          </div>
          <div className="text-sm text-emerald-700">유효한 매핑</div>
        </div>
        <div className="bg-destructive/10 p-4 rounded-lg border border-destructive/20">
          <div className="text-2xl font-bold text-red-900">
            {fieldMappings.filter(m => !m.isValid).length}
          </div>
          <div className="text-sm text-destructive">오류 매핑</div>
        </div>
        <div className="bg-amber-50 p-4 rounded-lg border border-amber-200">
          <div className="text-2xl font-bold text-yellow-900">
            {(toTable?.columns.length || 0) - fieldMappings.length}
          </div>
          <div className="text-sm text-yellow-700">미매핑 필드</div>
        </div>
      </div>

      {/* 매핑 영역 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* FROM 테이블 필드들 */}
        <div className="space-y-4">
          <h3 className="text-lg font-semibold text-foreground flex items-center gap-2">
            <div className="w-6 h-6 bg-primary/20 rounded-full flex items-center justify-center">
              <span className="text-primary font-bold text-sm">FROM</span>
            </div>
            {fromTable?.name} 필드들
          </h3>
          
          <div className="space-y-2">
            {fromTable?.columns.map((field) => (
              <div
                key={field.name}
                draggable
                onDragStart={() => handleDragStart(field)}
                className={`p-3 rounded-lg border-2 cursor-move transition-all duration-200 ${
                  isFieldMapped(field.name)
                    ? "border-green-300 bg-emerald-50 opacity-60"
                    : "border-primary/20 bg-accent hover:border-primary/60 hover:bg-primary/20"
                }`}
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-foreground">{field.name}</div>
                    <div className="text-sm text-muted-foreground">{field.type}</div>
                    {field.primaryKey && (
                      <span className="text-xs bg-amber-100 text-yellow-800 px-2 py-1 rounded">
                        PK
                      </span>
                    )}
                  </div>
                  {isFieldMapped(field.name) && (
                    <CheckCircle className="w-5 h-5 text-emerald-600" />
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* TO 테이블 필드들 */}
        <div className="space-y-4">
          <h3 className="text-lg font-semibold text-foreground flex items-center gap-2">
            <div className="w-6 h-6 bg-emerald-100 rounded-full flex items-center justify-center">
              <span className="text-emerald-600 font-bold text-sm">TO</span>
            </div>
            {toTable?.name} 필드들
          </h3>
          
          <div className="space-y-2">
            {toTable?.columns.map((field) => {
              const mappedFromField = getMappedFromField(field.name);
              return (
                <div
                  key={field.name}
                  onDragOver={handleDragOver}
                  onDrop={(e) => handleDrop(e, field)}
                  className={`p-3 rounded-lg border-2 transition-all duration-200 ${
                    mappedFromField
                      ? "border-green-300 bg-emerald-50"
                      : "border-border bg-muted hover:border-green-300 hover:bg-green-25"
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="font-medium text-foreground">{field.name}</div>
                      <div className="text-sm text-muted-foreground">{field.type}</div>
                      {field.primaryKey && (
                        <span className="text-xs bg-amber-100 text-yellow-800 px-2 py-1 rounded">
                          PK
                        </span>
                      )}
                      {mappedFromField && (
                        <div className="text-xs text-emerald-700 mt-1">
                          ← {mappedFromField.name} ({mappedFromField.type})
                        </div>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      {mappedFromField && (
                        <button
                          onClick={() => removeMapping(`${mappedFromField.name}-${field.name}`)}
                          className="text-destructive hover:text-destructive"
                        >
                          <XCircle className="w-4 h-4" />
                        </button>
                      )}
                      {mappedFromField && (
                        <div>
                          {fieldMappings.find(m => m.toField.name === field.name)?.isValid ? (
                            <CheckCircle className="w-5 h-5 text-emerald-600" />
                          ) : (
                            <AlertCircle className="w-5 h-5 text-destructive" />
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* 버튼들 */}
      <div className="flex justify-between">
        <button
          onClick={onBack}
          className="flex items-center gap-2 px-6 py-3 rounded-lg font-medium text-muted-foreground bg-muted hover:bg-muted/80 transition-all duration-200"
        >
          <ArrowLeft className="w-4 h-4" />
          이전 단계
        </button>
        
        <button
          onClick={onSave}
          className="flex items-center gap-2 px-6 py-3 rounded-lg font-medium bg-amber-500 text-white hover:bg-orange-600 shadow-md hover:shadow-lg transition-all duration-200"
        >
          <Save className="w-4 h-4" />
          연결 설정 저장
        </button>
      </div>
    </div>
  );
};