'use client';

import { useState } from 'react';
import { useCrmApi } from '../context';
import { cn } from '../utils';
import type { StageData, PipelineData } from '../types';

interface StageSwitcherProps {
  entityType: string;
  entityId: string;
  currentStageId: string;
  pipeline: PipelineData;
  onStageChanged?: (newStageId: string) => void;
  compact?: boolean;
}

export function StageSwitcher({
  entityType,
  entityId,
  currentStageId,
  pipeline,
  onStageChanged,
  compact = false,
}: StageSwitcherProps) {
  const api = useCrmApi();
  const [loading, setLoading] = useState<string | null>(null);

  const stages = [...pipeline.stages].sort((a, b) => a.position - b.position);
  const currentIndex = stages.findIndex((s) => s.id === currentStageId);

  const handleStageClick = async (stage: StageData) => {
    if (stage.id === currentStageId || loading) return;

    setLoading(stage.id);
    try {
      const apiPrefix = entityType === 'deal' ? '/crm/deals' : `/crm/${entityType}s`;
      await api.post(`${apiPrefix}/${entityId}/move`, { stageId: stage.id });
      onStageChanged?.(stage.id);
    } catch {
      //
    } finally {
      setLoading(null);
    }
  };

  if (compact) {
    return (
      <div className="flex items-center gap-1">
        {stages.map((stage, index) => {
          const isCurrent = stage.id === currentStageId;
          const isPast = index < currentIndex;
          const isLoading = loading === stage.id;

          return (
            <button
              key={stage.id}
              onClick={() => void handleStageClick(stage)}
              disabled={isLoading || isCurrent}
              title={stage.name}
              className={cn(
                'h-2 rounded-full transition-all',
                isCurrent ? 'w-6' : 'w-2',
                isLoading && 'animate-pulse',
              )}
              style={{
                backgroundColor: isCurrent || isPast ? stage.color : '#e5e7eb',
                opacity: isCurrent ? 1 : isPast ? 0.6 : 0.3,
              }}
            />
          );
        })}
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-1">
      {stages.map((stage, index) => {
        const isCurrent = stage.id === currentStageId;
        const isPast = index < currentIndex;
        const isLoading = loading === stage.id;

        return (
          <button
            key={stage.id}
            onClick={() => void handleStageClick(stage)}
            disabled={isLoading || isCurrent}
            className={cn(
              'flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs transition-all text-left',
              isCurrent ? 'font-medium' : 'hover:bg-gray-50 cursor-pointer',
              isLoading && 'opacity-50',
            )}
          >
            <span
              className={cn('w-2.5 h-2.5 rounded-full shrink-0', isLoading && 'animate-pulse')}
              style={{
                backgroundColor: stage.color,
                opacity: isCurrent || isPast ? 1 : 0.4,
              }}
            />
            <span
              className={cn(
                isCurrent ? 'text-gray-900' : isPast ? 'text-gray-500' : 'text-gray-400',
              )}
            >
              {stage.name}
            </span>
            {isCurrent && (
              <span className="text-[9px] px-1.5 py-0.5 rounded-full bg-gray-100 text-gray-500 ml-auto">
                текущая
              </span>
            )}
          </button>
        );
      })}
    </div>
  );
}
