'use client';

import { useState, useCallback } from 'react';
import { cn } from '../utils';
import { useCrmApi } from '../context';
import { EntityCard } from './entity-card';
import type { EntityConfig, KanbanColumn } from '../types';

interface EntityKanbanProps {
  config: EntityConfig;
  columns: Record<string, KanbanColumn>;
  onCardClick: (entityId: string) => void;
  onRefresh: () => void;
}

export function EntityKanban({ config, columns, onCardClick, onRefresh }: EntityKanbanProps) {
  const api = useCrmApi();
  const [dragId, setDragId] = useState<string | null>(null);
  const [dragOverStageId, setDragOverStageId] = useState<string | null>(null);

  const stageEntries = Object.entries(columns).sort(
    ([, a], [, b]) => a.stage.position - b.stage.position,
  );

  const handleDragStart = useCallback((e: React.DragEvent, entityId: string) => {
    setDragId(entityId);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', entityId);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent, stageId: string) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    setDragOverStageId(stageId);
  }, []);

  const handleDragLeave = useCallback(() => {
    setDragOverStageId(null);
  }, []);

  const handleDrop = useCallback(
    async (e: React.DragEvent, targetStageId: string) => {
      e.preventDefault();
      const entityId = e.dataTransfer.getData('text/plain');
      setDragId(null);
      setDragOverStageId(null);

      if (!entityId) return;

      let currentStageId: string | null = null;
      for (const [stageId, col] of Object.entries(columns)) {
        if (col.items.some((d) => d.id === entityId)) {
          currentStageId = stageId;
          break;
        }
      }
      if (currentStageId === targetStageId) return;

      try {
        await api.post(`${config.apiPrefix}/${entityId}/move`, { stageId: targetStageId });
        onRefresh();
      } catch (err) {
        console.error('Failed to move entity:', err);
      }
    },
    [columns, onRefresh, api, config.apiPrefix],
  );

  return (
    <div className="flex gap-4 overflow-x-auto pb-4 min-h-[calc(100vh-220px)]">
      {stageEntries.map(([stageId, col]) => (
        <div
          key={stageId}
          className={cn(
            'flex-shrink-0 w-72 bg-background/50 rounded-xl border border-border/50',
            'flex flex-col',
            dragOverStageId === stageId && 'ring-2 ring-primary/40 bg-primary/5',
          )}
          onDragOver={(e) => handleDragOver(e, stageId)}
          onDragLeave={handleDragLeave}
          onDrop={(e) => void handleDrop(e, stageId)}
        >
          <div className="px-3 py-3 border-b border-border/50 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span
                className="w-3 h-3 rounded-full shrink-0"
                style={{ backgroundColor: col.stage.color }}
              />
              <h3 className="text-sm font-medium text-text truncate">{col.stage.name}</h3>
            </div>
            <span className="text-xs text-muted bg-background px-2 py-0.5 rounded-full">
              {col.items.length}
            </span>
          </div>

          <div className="flex-1 overflow-y-auto p-2 space-y-2">
            {col.items.map((item) => (
              <div
                key={item.id}
                draggable
                onDragStart={(e) => handleDragStart(e, item.id)}
                className={cn('transition-opacity', dragId === item.id && 'opacity-40')}
              >
                <EntityCard
                  config={config}
                  data={item}
                  onClick={() => onCardClick(item.id)}
                  compact
                />
              </div>
            ))}

            {col.items.length === 0 && (
              <div className="text-center py-8 text-xs text-muted">Нет {config.label.genitive}</div>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}
