import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { X, GripVertical, Eye, EyeOff, RotateCcw } from 'lucide-react';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import {
  ColumnDefinition,
  ColumnId,
  DEFAULT_COLUMNS,
  getAllColumnsSorted,
  saveColumnConfig,
} from '../../types/columns';

interface Props {
  columns: Record<ColumnId, ColumnDefinition>;
  onSave: (columns: Record<ColumnId, ColumnDefinition>) => void;
  onClose: () => void;
}

function SortableColumn({ 
  column, 
  onToggle,
  onWidthChange,
  t,
}: { 
  column: ColumnDefinition; 
  onToggle: (id: string) => void;
  onWidthChange: (id: string, width: number) => void;
  t: (key: string) => string;
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: column.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`flex items-center gap-3 p-3 bg-white border rounded-lg ${
        isDragging ? 'shadow-lg' : 'hover:bg-gray-50'
      }`}
    >
      {/* Drag handle */}
      <button
        {...attributes}
        {...listeners}
        className="cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600"
      >
        <GripVertical className="w-5 h-5" />
      </button>

      {/* Toggle checkbox */}
      <button
        onClick={() => onToggle(column.id)}
        className={`flex items-center justify-center w-6 h-6 rounded border-2 transition ${
          column.enabled
            ? 'bg-blue-600 border-blue-600 text-white'
            : 'border-gray-300 hover:border-gray-400'
        }`}
      >
        {column.enabled ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
      </button>

      {/* Column info */}
      <div className="flex-1">
        <div className="flex items-center gap-2">
          <span className={`font-medium ${column.enabled ? 'text-gray-900' : 'text-gray-400'}`}>
            {column.id === 'stock_status' ? t('stock_status_label') : t(column.id)}
          </span>
          {column.editable && (
            <span className="px-1.5 py-0.5 text-xs bg-green-100 text-green-700 rounded">
              {t('columns.editable')}
            </span>
          )}
        </div>
        {column.description && (
          <p className="text-xs text-gray-500 mt-0.5">{column.description}</p>
        )}
      </div>

      {/* Width input */}
      <input
        type="number"
        value={column.width || 120}
        onChange={(e) => onWidthChange(column.id, parseInt(e.target.value) || 120)}
        className="w-16 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
        min="50"
        max="500"
        step="10"
      />
      <span className="text-sm text-gray-400">px</span>
    </div>
  );
}

export default function ColumnConfigModal({ columns, onSave, onClose }: Props) {
  const { t } = useTranslation();
  const [localColumns, setLocalColumns] = useState(columns);
  const sortedColumns = getAllColumnsSorted(localColumns);

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (over && active.id !== over.id) {
      const oldIndex = sortedColumns.findIndex((col) => col.id === active.id);
      const newIndex = sortedColumns.findIndex((col) => col.id === over.id);

      const reordered = arrayMove(sortedColumns, oldIndex, newIndex);

      // Update orders
      const updated = { ...localColumns };
      reordered.forEach((col, index) => {
        updated[col.id as ColumnId] = { ...col, order: index };
      });

      setLocalColumns(updated);
    }
  };

  const handleToggle = (columnId: string) => {
    setLocalColumns((prev) => ({
      ...prev,
      [columnId]: {
        ...prev[columnId as ColumnId],
        enabled: !prev[columnId as ColumnId].enabled,
      },
    }));
  };
  
  const handleWidthChange = (columnId: string, width: number) => {
    setLocalColumns((prev) => ({
      ...prev,
      [columnId]: {
        ...prev[columnId as ColumnId],
        width,
      },
    }));
  };

  const handleReset = () => {
    if (confirm(t('columns.confirm_reset'))) {
      setLocalColumns(DEFAULT_COLUMNS);
    }
  };

  const handleSave = () => {
    saveColumnConfig(localColumns);
    onSave(localColumns);
    onClose();
  };

  const enabledCount = sortedColumns.filter((col) => col.enabled).length;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
      <div
        className="bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <div>
            <h2 className="text-xl font-bold text-gray-900">{t('columns.title')}</h2>
            <p className="text-sm text-gray-600 mt-1">
              {t('columns.showing', { enabled: enabledCount, total: sortedColumns.length })}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Instructions */}
        <div className="px-6 py-3 bg-blue-50 border-b border-blue-100">
          <p className="text-sm text-blue-900">
            <strong>{t('columns.usage')}:</strong> {t('columns.usage_description')}
          </p>
        </div>

        {/* Column list */}
        <div className="flex-1 overflow-y-auto p-6">
          <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
            <SortableContext items={sortedColumns.map((col) => col.id)} strategy={verticalListSortingStrategy}>
              <div className="space-y-2">
                {sortedColumns.map((column) => (
                  <SortableColumn 
                    key={column.id} 
                    column={column} 
                    onToggle={handleToggle}
                    onWidthChange={handleWidthChange}
                    t={t}
                  />
                ))}
              </div>
            </SortableContext>
          </DndContext>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-gray-200 bg-gray-50">
          <button
            onClick={handleReset}
            className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 transition"
          >
            <RotateCcw className="w-4 h-4" />
            {t('columns.reset')}
          </button>

          <div className="flex gap-3">
            <button
              onClick={onClose}
              className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 transition"
            >
              {t('columns.cancel')}
            </button>
            <button
              onClick={handleSave}
              className="px-6 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition"
            >
              {t('columns.save')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
