import { Save, ArrowLeft, Undo2, Redo2, Pencil, Loader2, Check } from 'lucide-react';
import { Button } from '../ui/button';
import { Switch } from '../ui/switch';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip';
import { VersionBadge } from '../versioning';
import { __, sprintf, _n } from '../../lib/i18n';

/** Status of the workflow name auto-save */
export type NameSaveStatus = 'idle' | 'saving' | 'saved';

/**
 * Props for the FlowBuilder Toolbar component
 */
export interface ToolbarProps {
  /** Current workflow name */
  workflowName: string;
  /** Callback when workflow name changes */
  onNameChange: (name: string) => void;
  /** Callback when workflow name field loses focus */
  onNameBlur: () => void;
  /** Status of name auto-save operation */
  nameSaveStatus: NameSaveStatus;
  /** Callback when back button is clicked */
  onBack: () => void;
  /** Callback when save button is clicked */
  onSave: () => void;
  /** Whether undo is available */
  canUndo: boolean;
  /** Whether redo is available */
  canRedo: boolean;
  /** Callback for undo action */
  onUndo: () => void;
  /** Callback for redo action */
  onRedo: () => void;
  /** Number of undo steps available */
  undoCount: number;
  /** Number of redo steps available */
  redoCount: number;
  /** Whether workflow is currently being saved */
  isSaving: boolean;
  /** Whether there are unsaved changes */
  hasUnsavedChanges: boolean;
  /** Whether workflow is active */
  isActive: boolean;
  /** Whether workflow is currently activating/deactivating */
  isActivating: boolean;
  /** Callback when active toggle changes */
  onToggleActive: (active: boolean) => void;
  /** Whether toggle can be changed */
  canToggleActive: boolean;
  /** Whether the workflow has been published at least once */
  isPublished: boolean;
  /** Whether there are unpublished changes */
  hasUnpublishedChanges: boolean;
  /** Whether a publish operation is in progress */
  isPublishing: boolean;
  /** Callback to open version history panel */
  onOpenHistory: () => void;
  /** Callback to trigger publish */
  onPublish: () => void;
}

/**
 * Toolbar component for the FlowBuilder
 *
 * Displays workflow name input, navigation, undo/redo controls,
 * save button, and active toggle.
 */
export function Toolbar({
  workflowName,
  onNameChange,
  onNameBlur,
  nameSaveStatus,
  onBack,
  onSave,
  canUndo,
  canRedo,
  onUndo,
  onRedo,
  undoCount,
  redoCount,
  isSaving,
  hasUnsavedChanges,
  isActive,
  isActivating,
  onToggleActive,
  canToggleActive,
  isPublished,
  hasUnpublishedChanges,
  isPublishing,
  onOpenHistory,
  onPublish,
}: ToolbarProps) {
  return (
    <TooltipProvider delayDuration={300}>
      <div className="border-b border-slate-200 bg-white px-4 md:px-6 py-3 flex items-center gap-4">
        {/* Zone 1: Navigation */}
        <div className="flex items-center gap-2 pr-4 border-r border-slate-200">
          <Button
            onClick={onBack}
            variant="ghost"
            size="sm"
            className="gap-2 text-slate-600 hover:text-slate-900"
          >
            <ArrowLeft className="w-4 h-4" />
            <span className="hidden lg:inline text-sm font-normal">{__('Workflows')}</span>
          </Button>
        </div>

        {/* Zone 2: Identity */}
        <div className="flex-1 flex justify-center px-4">
          <div className="relative w-full max-w-md">
            <Input
              type="text"
              value={workflowName}
              onChange={(e) => onNameChange(e.target.value)}
              onBlur={onNameBlur}
              className="font-display text-base font-semibold border-transparent bg-transparent text-center hover:bg-slate-50 focus:bg-white focus:border-cyan-300 focus:shadow-focus transition-all"
            />
            <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
              {nameSaveStatus === 'saving' && (
                <Loader2 className="h-4 w-4 text-cyan-600 animate-spin" />
              )}
              {nameSaveStatus === 'saved' && <Check className="h-4 w-4 text-green-500" />}
              {nameSaveStatus === 'idle' && <Pencil className="h-4 w-4 text-slate-400" />}
            </div>
          </div>
        </div>

        {/* Zone 3: Controls */}
        <div className="flex items-center gap-3">
          {/* History group */}
          <div className="flex items-center bg-slate-50 rounded-md p-0.5 gap-0.5">
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  onClick={onUndo}
                  variant="ghost"
                  size="xs"
                  className="text-slate-600 hover:text-slate-900 hover:bg-slate-100 disabled:opacity-40"
                  disabled={!canUndo}
                >
                  <Undo2 className="w-4 h-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="bottom">
                {canUndo
                  ? sprintf(
                      __('Undo (Ctrl+Z) - %s available'),
                      sprintf(_n('%d step', '%d steps', undoCount), undoCount),
                    )
                  : __('Undo (Ctrl+Z)')}
              </TooltipContent>
            </Tooltip>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  onClick={onRedo}
                  variant="ghost"
                  size="xs"
                  className="text-slate-600 hover:text-slate-900 hover:bg-slate-100 disabled:opacity-40"
                  disabled={!canRedo}
                >
                  <Redo2 className="w-4 h-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="bottom">
                {canRedo
                  ? sprintf(
                      __('Redo (Ctrl+Y) - %s available'),
                      sprintf(_n('%d step', '%d steps', redoCount), redoCount),
                    )
                  : __('Redo (Ctrl+Y)')}
              </TooltipContent>
            </Tooltip>
          </div>

          {/* Save button */}
          <Button
            data-testid="save-workflow"
            onClick={onSave}
            variant={hasUnsavedChanges ? 'accent' : 'outline'}
            size="sm"
            className="min-w-[80px] transition-all"
            disabled={isSaving || !hasUnsavedChanges}
          >
            {isSaving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                <span className="hidden md:inline">{__('Saving')}</span>
              </>
            ) : (
              <>
                <Save className="w-4 h-4 md:mr-2" />
                <span className="hidden md:inline">{__('Save')}</span>
              </>
            )}
          </Button>

          {/* Version status */}
          <VersionBadge
            isPublished={isPublished}
            hasUnpublishedChanges={hasUnpublishedChanges}
            isPublishing={isPublishing}
            onOpenHistory={onOpenHistory}
            onPublish={onPublish}
            publishDisabled={isSaving || hasUnsavedChanges}
          />

          {/* Status group */}
          <div className="flex items-center gap-2 pl-3 border-l border-slate-200">
            <Switch
              checked={isActive}
              onCheckedChange={onToggleActive}
              disabled={!canToggleActive || isActivating || isSaving}
              className="data-[state=checked]:bg-success disabled:opacity-50"
            />
            <Badge
              variant={isActive ? 'success' : 'secondary'}
              className="min-w-[70px] justify-center"
            >
              {isActivating ? __('Updating...') : isActive ? __('Active') : __('Inactive')}
            </Badge>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}
