import React, { useEffect, useState, useCallback } from 'react';
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { FiCommand, FiSave, FiRefreshCw, FiSearch } from 'react-icons/fi';
import { useToast } from '@chakra-ui/react';

/**
 * AdminEnhancer - Adds admin-specific functionality
 * - Keyboard shortcuts (Ctrl+S, Ctrl+K, etc.)
 * - Auto-save drafts
 * - Unsaved changes warning
 * - Quick search
 * - Keyboard shortcuts help
 */

interface AdminEnhancerProps {
  children: React.ReactNode;
  onSave?: () => void | Promise<void>;
  onRefresh?: () => void | Promise<void>;
  onSearch?: () => void;
  hasUnsavedChanges?: boolean;
}

const AdminEnhancer: React.FC<AdminEnhancerProps> = ({
  children,
  onSave,
  onRefresh,
  onSearch,
  hasUnsavedChanges = false,
}) => {
  const [showShortcuts, setShowShortcuts] = useState(false);
  const [lastSaved, setLastSaved] = useLocalStorage('admin-last-saved', '');
  const toast = useToast();

  // Warn before leaving with unsaved changes
  useEffect(() => {
    if (!hasUnsavedChanges) return;

    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
      return '';
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges]);

  // Handle save
  const handleSave = useCallback(async () => {
    if (!onSave) return;

    try {
      await onSave();
      const now = new Date().toISOString();
      setLastSaved(now);
      toast({
        title: 'Uloženo',
        description: 'Změny byly úspěšně uloženy',
        status: 'success',
        duration: 2000,
        position: 'bottom-right',
      });
    } catch (error) {
      toast({
        title: 'Chyba',
        description: 'Nepodařilo se uložit změny',
        status: 'error',
        duration: 3000,
        position: 'bottom-right',
      });
    }
  }, [onSave, setLastSaved, toast]);

  // Handle refresh
  const handleRefresh = useCallback(async () => {
    if (!onRefresh) return;

    try {
      await onRefresh();
      toast({
        title: 'Obnoveno',
        description: 'Data byla aktualizována',
        status: 'info',
        duration: 2000,
        position: 'bottom-right',
      });
    } catch (error) {
      toast({
        title: 'Chyba',
        description: 'Nepodařilo se obnovit data',
        status: 'error',
        duration: 3000,
        position: 'bottom-right',
      });
    }
  }, [onRefresh, toast]);

  // Admin keyboard shortcuts
  useKeyboardShortcuts([
    {
      key: 's',
      ctrlKey: true,
      callback: () => {
        handleSave();
      },
      description: 'Uložit změny',
    },
    {
      key: 'k',
      ctrlKey: true,
      callback: () => {
        if (onSearch) onSearch();
      },
      description: 'Otevřít vyhledávání',
    },
    {
      key: 'r',
      ctrlKey: true,
      callback: () => {
        handleRefresh();
      },
      description: 'Obnovit data',
    },
    {
      key: '?',
      shiftKey: true,
      callback: () => setShowShortcuts(true),
      description: 'Zobrazit klávesové zkratky',
    },
    {
      key: 'Escape',
      callback: () => setShowShortcuts(false),
    },
  ]);

  return (
    <>
      {children}

      {/* Unsaved changes indicator */}
      {hasUnsavedChanges && (
        <div
          style={{
            position: 'fixed',
            bottom: 24,
            left: 24,
            padding: '12px 16px',
            background: '#f59e0b',
            color: 'white',
            borderRadius: 8,
            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            zIndex: 9999,
            animation: 'pulse 2s infinite',
          }}
        >
          <span style={{ fontSize: 14, fontWeight: 600 }}>
            Máte neuložené změny
          </span>
          {onSave && (
            <button
              onClick={handleSave}
              style={{
                background: 'white',
                color: '#f59e0b',
                border: 'none',
                padding: '6px 12px',
                borderRadius: 4,
                fontSize: 14,
                fontWeight: 600,
                cursor: 'pointer',
              }}
            >
              Uložit nyní
            </button>
          )}
        </div>
      )}

      {/* Keyboard shortcuts modal */}
      {showShortcuts && (
        <>
          <div
            style={{
              position: 'fixed',
              inset: 0,
              background: 'rgba(0,0,0,0.6)',
              backdropFilter: 'blur(4px)',
              zIndex: 10000,
            }}
            onClick={() => setShowShortcuts(false)}
          />
          <div
            style={{
              position: 'fixed',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              background: 'white',
              borderRadius: 12,
              padding: 24,
              maxWidth: 500,
              width: '90%',
              maxHeight: '80vh',
              overflow: 'auto',
              zIndex: 10001,
              boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
              <FiCommand size={24} />
              <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>
                Klávesové zkratky
              </h2>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <ShortcutItem keys={['Ctrl', 'S']} description="Uložit změny" icon={<FiSave />} />
              <ShortcutItem keys={['Ctrl', 'K']} description="Vyhledávání" icon={<FiSearch />} />
              <ShortcutItem keys={['Ctrl', 'R']} description="Obnovit data" icon={<FiRefreshCw />} />
              <ShortcutItem keys={['?']} description="Zobrazit zkratky" icon={<FiCommand />} />
              <ShortcutItem keys={['Esc']} description="Zavřít modál" />
              <ShortcutItem keys={['Home']} description="Na začátek stránky" />
              <ShortcutItem keys={['End']} description="Na konec stránky" />
            </div>

            <button
              onClick={() => setShowShortcuts(false)}
              style={{
                marginTop: 20,
                width: '100%',
                padding: '10px 20px',
                background: 'var(--primary, #C53030)',
                color: 'white',
                border: 'none',
                borderRadius: 8,
                fontSize: 14,
                fontWeight: 600,
                cursor: 'pointer',
              }}
            >
              Zavřít
            </button>
          </div>
        </>
      )}

      {/* Shortcut hint button */}
      <button
        onClick={() => setShowShortcuts(true)}
        style={{
          position: 'fixed',
          bottom: 24,
          right: 24,
          width: 48,
          height: 48,
          borderRadius: '50%',
          background: 'white',
          border: '2px solid #e2e8f0',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
          transition: 'all 0.3s ease',
          zIndex: 9998,
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.transform = 'translateY(-4px)';
          e.currentTarget.style.boxShadow = '0 6px 16px rgba(0,0,0,0.15)';
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.transform = 'translateY(0)';
          e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
        }}
        title="Klávesové zkratky (Shift + ?)"
      >
        <FiCommand size={24} color="#4a5568" />
      </button>
    </>
  );
};

const ShortcutItem: React.FC<{ keys: string[]; description: string; icon?: React.ReactNode }> = ({
  keys,
  description,
  icon,
}) => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 0' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      {icon && <span style={{ color: '#718096' }}>{icon}</span>}
      <span style={{ fontSize: 14, color: '#2d3748' }}>{description}</span>
    </div>
    <div style={{ display: 'flex', gap: 4 }}>
      {keys.map((key, i) => (
        <React.Fragment key={key}>
          <kbd
            style={{
              padding: '4px 8px',
              background: '#e2e8f0',
              borderRadius: 4,
              fontSize: 12,
              fontFamily: 'monospace',
              fontWeight: 600,
              color: '#4a5568',
              border: '1px solid #cbd5e0',
            }}
          >
            {key}
          </kbd>
          {i < keys.length - 1 && <span style={{ color: '#a0aec0' }}>+</span>}
        </React.Fragment>
      ))}
    </div>
  </div>
);

export default AdminEnhancer;
