'use client';

import { useState, useCallback } from 'react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';
import { DealCard, type DealCardData } from './deal-card';

interface KanbanStage {
  stage: {
    id: string;
    name: string;
    color: string;
    type: string;
  };
  deals: DealCardData[];
}

interface DealKanbanProps {
  columns: Record<string, KanbanStage>;
  onDealClick: (dealIdOrNumber: string) => void;
  onRefresh: () => void;
}

export function DealKanban({ columns, onDealClick, onRefresh }: DealKanbanProps) {
  const [dragDealId, setDragDealId] = useState<string | null>(null);
  const [dragOverStageId, setDragOverStageId] = useState<string | null>(null);

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

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

  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 dealId = e.dataTransfer.getData('text/plain');
      setDragDealId(null);
      setDragOverStageId(null);

      if (!dealId) return;

      // Find current stage
      let currentStageId: string | null = null;
      for (const [stageId, col] of Object.entries(columns)) {
        if (col.deals.some((d) => d.id === dealId)) {
          currentStageId = stageId;
          break;
        }
      }

      if (currentStageId === targetStageId) return;

      try {
        await api.post(`/crm/deals/${dealId}/move`, { stageId: targetStageId });
        onRefresh();
      } catch (err) {
        console.error('Failed to move deal:', err);
      }
    },
    [columns, onRefresh],
  );

  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) => handleDrop(e, stageId)}
        >
          {/* Column header */}
          <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.deals.length}
            </span>
          </div>

          {/* Cards */}
          <div className="flex-1 overflow-y-auto p-2 space-y-2">
            {col.deals.map((deal) => (
              <div
                key={deal.id}
                draggable
                onDragStart={(e) => handleDragStart(e, deal.id)}
                className={cn('transition-opacity', dragDealId === deal.id && 'opacity-40')}
              >
                <DealCard
                  deal={deal}
                  onClick={() => onDealClick(deal.number != null ? String(deal.number) : deal.id)}
                  compact
                />
              </div>
            ))}

            {col.deals.length === 0 && (
              <div className="text-center py-8 text-xs text-muted">Нет сделок</div>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}
