"use client";

import { useId, useRef, useState } from "react";
import { ArrowLeft, Save, Globe, Download, Upload, Undo, Redo } from "lucide-react";

import { Button } from "@/components/ui/button";
import { serializeBuilderState, deserializeFunnelDefinition } from "@/lib/admin/builder/utils";
import { useBuilderDispatch, useBuilderState } from "@/lib/admin/builder/context";
import { useBuilderUndoRedo } from "../providers/BuilderUndoRedoProvider";
import type { BuilderState } from "@/lib/admin/builder/context";
import { cn } from "@/lib/utils";

interface FunnelInfo {
  name: string;
  status: 'draft' | 'published' | 'archived';
  version: number;
  lastSaved: string;
}

interface BuilderTopBarProps {
  onNew?: () => void;
  onSave?: (state: BuilderState) => Promise<boolean>;
  onPublish?: (state: BuilderState) => Promise<boolean>;
  onBackToCatalog?: () => void;
  saving?: boolean;
  funnelInfo?: FunnelInfo;
  onLoadError?: (error: string) => void;
}

export function BuilderTopBar({
  onNew,
  onSave,
  onPublish,
  onBackToCatalog,
  saving,
  funnelInfo,
  onLoadError
}: BuilderTopBarProps) {
  const dispatch = useBuilderDispatch();
  const state = useBuilderState();
  const fileInputId = useId();
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  
  const [publishing, setPublishing] = useState(false);
  
  // Use undo/redo from context
  const undoRedo = useBuilderUndoRedo();

  const handleExport = () => {
    const json = JSON.stringify(serializeBuilderState(state), null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `funnel-${state.meta.id || 'export'}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) {
      return;
    }

    try {
      const text = await file.text();
      const parsed = JSON.parse(text);
      const builderState = deserializeFunnelDefinition(parsed);
      dispatch({ type: "reset", payload: builderState as BuilderState });
    } catch (error) {
      onLoadError?.(error instanceof Error ? error.message : "Не удалось загрузить JSON");
    } finally {
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const handleSave = async () => {
    if (onSave && !saving) {
      const success = await onSave(state);
      if (success) {
        undoRedo.resetDirty();
      }
    }
  };

  const handlePublish = async () => {
    if (onPublish && !publishing && !saving) {
      setPublishing(true);
      try {
        const success = await onPublish(state);
        if (success) {
          undoRedo.resetDirty();
        }
      } finally {
        setPublishing(false);
      }
    }
  };

  // Статус badge
  const getStatusBadge = (status: string) => {
    const variants = {
      draft: 'bg-yellow-100 text-yellow-800 border-yellow-200',
      published: 'bg-green-100 text-green-800 border-green-200', 
      archived: 'bg-gray-100 text-gray-800 border-gray-200'
    };
    
    const labels = {
      draft: 'Черновик',
      published: 'Опубликована',
      archived: 'Архивирована'
    };

    return (
      <span className={cn(
        'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium border',
        variants[status as keyof typeof variants]
      )}>
        {labels[status as keyof typeof labels]}
      </span>
    );
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="flex items-center justify-between px-6 py-4 bg-white border-b border-gray-200">
      
      {/* Left section */}
      <div className="flex items-center gap-4">
        
        {/* Back to catalog */}
        {onBackToCatalog && (
          <Button variant="ghost" onClick={onBackToCatalog} className="flex items-center gap-2">
            <ArrowLeft className="h-4 w-4" />
            Каталог
          </Button>
        )}

        {/* Funnel info */}
        <div className="flex flex-col">
          <div className="flex items-center gap-3">
            <h1 className="text-lg font-semibold text-gray-900">
              {funnelInfo?.name || state.meta.title || 'Новая воронка'}
            </h1>
            {funnelInfo && getStatusBadge(funnelInfo.status)}
            {state.isDirty && (
              <span className="text-xs text-orange-600 font-medium">
                • Несохраненные изменения
              </span>
            )}
          </div>
          {funnelInfo && (
            <div className="text-xs text-gray-500">
              v{funnelInfo.version} • Сохранено {formatDate(funnelInfo.lastSaved)}
            </div>
          )}
        </div>
      </div>

      {/* Right section */}
      <div className="flex items-center gap-3">
        
        {/* Undo/Redo */}
        <div className="flex items-center gap-1">
          <Button 
            variant="ghost" 
            disabled={!undoRedo.canUndo}
            onClick={undoRedo.undo}
            title="Отменить (Ctrl+Z)" 
            className="h-8 w-8 p-0"
          >
            <Undo className="h-4 w-4" />
          </Button>
          <Button 
            variant="ghost" 
            disabled={!undoRedo.canRedo}
            onClick={undoRedo.redo}
            title="Повторить (Ctrl+Y)" 
            className="h-8 w-8 p-0"
          >
            <Redo className="h-4 w-4" />
          </Button>
        </div>

        {/* Import/Export */}
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            onClick={() => fileInputRef.current?.click()}
            title="Загрузить JSON"
            className="h-8 w-8 p-0"
          >
            <Upload className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            onClick={handleExport}
            title="Экспорт JSON"
            className="h-8 w-8 p-0"
          >
            <Download className="h-4 w-4" />
          </Button>
        </div>

        <input
          ref={fileInputRef}
          id={fileInputId}
          type="file"
          accept="application/json"
          className="hidden"
          onChange={handleFileChange}
        />

        {/* Save/Publish */}
        {onSave && (
          <Button 
            variant="outline" 
            onClick={handleSave}
            disabled={saving || publishing || !state.isDirty}
            className="flex items-center gap-2"
          >
            <Save className="h-4 w-4" />
            {saving ? 'Сохранение...' : 'Сохранить'}
          </Button>
        )}

        {onPublish && (
          <Button 
            onClick={handlePublish}
            disabled={saving || publishing}
            className="flex items-center gap-2"
          >
            <Globe className="h-4 w-4" />
            {publishing ? 'Публикация...' : 'Опубликовать'}
          </Button>
        )}

        {/* Create new */}
        <Button variant="ghost" onClick={onNew}>
          Создать заново
        </Button>
      </div>
    </div>
  );
}
