import { Eye, EyeOff, Magnet, Plus, Save, Wrench } from 'lucide-react'
import { memo } from 'react'
import { Button } from 'shared/ui/button'

interface ElementFormulaBarProps {
  elementCount: number
  onAddElement: () => void
  onAutoArrange?: () => void
  disabled?: boolean
  // Пропсы для кнопки сохранения
  hasUnsavedChanges?: boolean
  isSaving?: boolean
  lastSaveError?: string | null
  onManualSave?: () => Promise<void>
  onClearError?: () => void
  // Пропсы для управления сеткой
  showGrid?: boolean
  onToggleGrid?: () => void
  snapToGrid?: boolean
  onToggleSnapToGrid?: () => void
}

export const ElementFormulaBar = memo(
  ({
    elementCount,
    onAddElement,
    onAutoArrange,
    disabled = false,
    hasUnsavedChanges = false,
    isSaving = false,
    lastSaveError = null,
    onManualSave,
    onClearError,
    showGrid = true,
    onToggleGrid,
    snapToGrid = true,
    onToggleSnapToGrid,
  }: ElementFormulaBarProps) => {
    return (
      <div className="formula-bar flex-shrink-0 border-b bg-background px-3 py-1">
        <div className="relative flex items-center">
          <div className="flex items-center space-x-1">
            {onToggleGrid && (
              <Button
                variant={showGrid ? 'default' : 'outline'}
                size="sm"
                onClick={onToggleGrid}
                className="h-7 px-2 text-xs"
              >
                {showGrid ? (
                  <EyeOff className="mr-1 h-3 w-3" />
                ) : (
                  <Eye className="mr-1 h-3 w-3" />
                )}
                {showGrid ? 'Скрыть' : 'Показать'}
              </Button>
            )}
            {onToggleSnapToGrid && (
              <Button
                variant={snapToGrid ? 'default' : 'outline'}
                size="sm"
                onClick={onToggleSnapToGrid}
                className="h-7 px-2 text-xs"
                title={
                  snapToGrid
                    ? 'Отключить привязку к сетке'
                    : 'Включить привязку к сетке'
                }
              >
                <Magnet className="mr-1 h-3 w-3" />
                Привязка
              </Button>
            )}
          </div>

          {/* Центральные кнопки добавления - абсолютное позиционирование */}
          <div className="absolute left-1/2 flex -translate-x-1/2 transform items-center space-x-1">
            <Button
              variant="outline"
              size="sm"
              onClick={onAddElement}
              disabled={disabled}
              className="h-7 px-2 text-xs"
            >
              <Plus className="mr-1 h-3 w-3" />
              Добавить
            </Button>
            {onAutoArrange && (
              <Button
                variant="outline"
                size="sm"
                onClick={onAutoArrange}
                disabled={disabled || elementCount === 0}
                className="h-7 px-2 text-xs"
              >
                <Wrench className="mr-1 h-3 w-3" />
                Упорядочить
              </Button>
            )}
          </div>

          <div className="ml-auto flex items-center gap-2">
            {/* Ошибка сохранения */}
            {lastSaveError && (
              <div className="flex items-center gap-1 rounded-md bg-destructive/10 px-2 py-1">
                <svg
                  className="h-3 w-3 text-destructive"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
                  />
                </svg>
                <span
                  className="text-xs text-destructive"
                  title={lastSaveError}
                >
                  Ошибка сохранения
                </span>
                {onClearError && (
                  <button
                    onClick={onClearError}
                    className="ml-1 text-destructive/60 hover:text-destructive"
                  >
                    <svg
                      className="h-3 w-3"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M6 18L18 6M6 6l12 12"
                      />
                    </svg>
                  </button>
                )}
              </div>
            )}

            {/* Индикатор сохранения */}
            {isSaving && (
              <div className="flex items-center text-muted-foreground">
                <svg
                  className="h-3.5 w-3.5 animate-spin"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  ></path>
                </svg>
                <span className="ml-1 text-xs">Сохранение...</span>
              </div>
            )}

            {/* Кнопка сохранения */}
            {onManualSave && (
              <button
                onClick={onManualSave}
                disabled={isSaving}
                className={`flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors ${
                  hasUnsavedChanges
                    ? 'bg-primary text-primary-foreground hover:bg-primary/90'
                    : lastSaveError
                      ? 'bg-destructive text-destructive-foreground hover:bg-destructive/90'
                      : 'bg-muted text-muted-foreground'
                } disabled:opacity-50`}
                title={
                  lastSaveError
                    ? 'Повторить сохранение'
                    : hasUnsavedChanges
                      ? 'Есть несохраненные изменения'
                      : 'Все изменения сохранены'
                }
              >
                <Save className="h-3 w-3" />
                {lastSaveError
                  ? 'Повторить'
                  : hasUnsavedChanges
                    ? 'Сохранить'
                    : 'Сохранено'}
              </button>
            )}
          </div>
        </div>
      </div>
    )
  }
)
