'use client';

import { useState, useEffect } from 'react';
import { api } from '@/lib/api';

interface Stage {
  id: string;
  name: string;
  color: string;
  order: number;
  type: string;
}

interface BitrixStageSwitcherProps {
  dealId: string;
  currentStageId: string;
  pipelineId: string;
  onStageChanged: () => void;
}

export function BitrixStageSwitcher({
  dealId,
  currentStageId,
  pipelineId,
  onStageChanged,
}: BitrixStageSwitcherProps) {
  const [stages, setStages] = useState<Stage[]>([]);
  const [movingTo, setMovingTo] = useState<string | null>(null);

  useEffect(() => {
    api
      .get<Stage[]>(`/crm/pipelines/${pipelineId}/stages`)
      .then(setStages)
      .catch(() => {});
  }, [pipelineId]);

  const handleMove = async (stageId: string) => {
    if (stageId === currentStageId || movingTo) return;
    setMovingTo(stageId);
    try {
      await api.post(`/crm/deals/${dealId}/move`, { stageId });
      onStageChanged();
    } catch {
      // ignore
    } finally {
      setMovingTo(null);
    }
  };

  if (stages.length === 0) return null;

  const currentIdx = stages.findIndex((s) => s.id === currentStageId);

  return (
    <div className="flex gap-0.5 mb-6 overflow-x-auto">
      {stages.map((stage, idx) => {
        const isCurrent = stage.id === currentStageId;
        const isPassed = idx < currentIdx;
        const isMoving = movingTo === stage.id;

        return (
          <button
            key={stage.id}
            onClick={() => handleMove(stage.id)}
            disabled={isCurrent || !!movingTo}
            className={`
              flex-1 min-w-0 px-3 py-2 text-xs font-medium truncate transition-all
              ${isCurrent ? 'text-white' : isPassed ? 'text-white/90' : 'text-gray-500 bg-gray-100'}
              ${!isCurrent && !movingTo ? 'hover:brightness-95 cursor-pointer' : ''}
              ${isCurrent ? 'cursor-default' : ''}
              ${isMoving ? 'animate-pulse' : ''}
              ${idx === 0 ? 'rounded-l-lg' : ''}
              ${idx === stages.length - 1 ? 'rounded-r-lg' : ''}
            `}
            style={
              isCurrent
                ? { backgroundColor: stage.color }
                : isPassed
                  ? { backgroundColor: stage.color, opacity: 0.7 }
                  : undefined
            }
            title={stage.name}
          >
            {stage.name}
          </button>
        );
      })}
    </div>
  );
}
