import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { AppState, PaperSize } from './types';
import { FileUpload } from './components/FileUpload';
import { StyleSelector } from './components/StyleSelector';
import { Preview } from './components/Preview';
import { ZoomControl } from './components/ZoomControl';
import { useSettings } from './hooks/useSettings';
import { useTemplates } from './hooks/useTemplates';
// @ts-ignore
import { parse } from 'marked';
import { Sparkles, Loader2, FileType, Keyboard, X, RefreshCw } from 'lucide-react';

import { useKeyboardNavigation } from './hooks/useKeyboardNavigation';

// Keyboard shortcuts help component
const KeyboardShortcutsHelp: React.FC<{ onClose: () => void }> = ({ onClose }) => {
  const shortcuts = [
    { key: '↑ / ↓', description: 'Navigate styles' },
    { key: '← / →', description: 'Navigate categories (when focused)' },
    { key: 'Enter', description: 'Select style or category' },
    { key: 'Home / End', description: 'First/last item' },
    { key: 'PgUp / PgDn', description: 'Jump 5 items' },
    { key: 'Tab', description: 'Switch between sections' },
    { key: 'Ctrl + Enter', description: 'Generate document' },
    { key: 'Escape', description: 'Go back / Close' },
  ];

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.9, opacity: 0 }}
        className="bg-zinc-900 border border-zinc-700 rounded-2xl p-6 max-w-md w-full shadow-2xl"
        onClick={e => e.stopPropagation()}
      >
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-indigo-500/10 rounded-lg text-indigo-400">
              <Keyboard size={20} />
            </div>
            <h2 className="text-xl font-bold text-white">Keyboard Shortcuts</h2>
          </div>
          <button
            onClick={onClose}
            className="p-1 hover:bg-zinc-800 rounded-lg text-zinc-400 hover:text-white transition-colors"
          >
            <X size={20} />
          </button>
        </div>
        <div className="space-y-3">
          {shortcuts.map((shortcut, index) => (
            <motion.div
              key={shortcut.key}
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: index * 0.05 }}
              className="flex justify-between items-center py-2 border-b border-zinc-800 last:border-0"
            >
              <span className="text-zinc-400">{shortcut.description}</span>
              <kbd className="px-2 py-1 bg-zinc-800 rounded text-sm font-mono text-zinc-300 border border-zinc-700">
                {shortcut.key}
              </kbd>
            </motion.div>
          ))}
        </div>
        <p className="mt-6 text-xs text-zinc-500 text-center">
          Press Escape or click outside to close
        </p>
      </motion.div>
    </motion.div>
  );
};

const App: React.FC = () => {
  const [appState, setAppState] = useState<AppState>(AppState.UPLOAD);
  const [content, setContent] = useState<string>('');
  const [inputFileName, setInputFileName] = useState<string>('');
  const [selectedStyle, setSelectedStyle] = useState<string | null>(null);
  const [paperSize, setPaperSize] = useState<PaperSize>('Letter');
  const [generatedHtml, setGeneratedHtml] = useState<string>('');
  const [error, setError] = useState<string | null>(null);
  const [showShortcuts, setShowShortcuts] = useState(false);

  const { uiZoom, setUiZoom, isLoaded } = useSettings();
  const { templates, categories, isLoading: templatesLoading, error: templatesError, refresh, openFolder } = useTemplates();

  // Global keyboard shortcut: Toggle help with ? or /
  useKeyboardNavigation({
    onEnter: undefined,
  }, []);

  // Note: Native file drop is handled by the FileUpload component
  // The Tauri file drop is disabled to allow the webview to handle drag events
  // This preserves the drag hover animations in the FileUpload component

  // Global keydown listener for shortcuts help
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === '?' || e.key === '/') {
        e.preventDefault();
        setShowShortcuts(prev => !prev);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);



  const handleFileLoaded = (text: string, fileName: string = '') => {
    setContent(text);
    setInputFileName(fileName);
    setAppState(AppState.CONFIG);
  };

  const handleGenerate = useCallback(async () => {
    if (!selectedStyle || !content) return;

    setAppState(AppState.GENERATING);
    setError(null);

    try {
      await new Promise(resolve => setTimeout(resolve, 800));
      const html = await parse(content);

      if (!html) throw new Error("No content generated");

      console.log('--- STAGE 1: MARKDOWN GENERATION ---');
      console.log('First 500 chars of HTML:', html.substring(0, 500));
      console.log('Contains h1?', html.includes('<h1'));
      console.log('Contains h3?', html.includes('<h3'));
      console.log('Contains table?', html.includes('<table'));

      setGeneratedHtml(html);
      setAppState(AppState.PREVIEW);
    } catch (err) {
      console.error(err);
      setError("Failed to process the document. Please check your file format and try again.");
      setAppState(AppState.CONFIG);
    }
  }, [selectedStyle, content]);

  const handleReset = () => {
    setAppState(AppState.UPLOAD);
    setContent('');
    setGeneratedHtml('');
    setSelectedStyle(null);
    setInputFileName('');
  };

  const handleBackToConfig = () => {
    setAppState(AppState.CONFIG);
  };

  if (!isLoaded) {
    return null;
  }

  if (appState === AppState.PREVIEW) {
    return (
      <div
        className="h-screen w-screen overflow-hidden"
        style={{ fontSize: `${uiZoom}%` }}
      >
        <div className="h-full w-full flex flex-col">
          <Preview
            htmlContent={generatedHtml}
            onBack={handleBackToConfig}
            paperSize={paperSize}
            selectedStyleId={selectedStyle}
            inputFileName={inputFileName}
            uiZoom={uiZoom}
            onZoomChange={setUiZoom}
            templates={templates}
          />
        </div>
      </div>
    );
  }

  return (
    <div
      className="h-screen bg-zinc-950 text-zinc-100 flex flex-col font-sans selection:bg-indigo-500/30 overflow-hidden"
      style={{ fontSize: `${uiZoom}%` }}
    >

      {/* Keyboard Shortcuts Modal */}
      <AnimatePresence>
        {showShortcuts && (
          <KeyboardShortcutsHelp onClose={() => setShowShortcuts(false)} />
        )}
      </AnimatePresence>

      {/* Header - Fixed height */}
      <motion.header
        initial={{ y: -20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
        className="flex-none border-b border-zinc-800 bg-zinc-950/50 backdrop-blur-sm z-40"
      >
        <div className="max-w-7xl mx-auto px-6 h-16 flex items-center justify-between">
          <motion.div
            className="flex items-center gap-2 cursor-pointer"
            onClick={handleReset}
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
          >
            <motion.div
              className="bg-gradient-to-br from-indigo-500 to-violet-600 p-2 rounded-lg"
              whileHover={{ rotate: [0, -10, 10, 0], transition: { duration: 0.5 } }}
            >
              <FileType className="text-white" size={20} />
            </motion.div>
            <h1 className="text-xl font-bold tracking-tight text-white">TypoGenie</h1>
          </motion.div>

          <div className="flex items-center gap-4">
            {/* UI Zoom Control */}
            <ZoomControl zoom={uiZoom} onZoomChange={setUiZoom} />

            {/* Refresh templates button */}
            {appState === AppState.CONFIG && (
              <motion.button
                onClick={refresh}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="hidden sm:flex items-center gap-2 px-3 py-1.5 text-xs text-zinc-500 hover:text-zinc-300 bg-zinc-900 hover:bg-zinc-800 rounded-lg transition-colors border border-zinc-800"
                title="Reload templates from disk"
              >
                <RefreshCw size={14} />
                <span>Refresh</span>
              </motion.button>
            )}

            {/* Keyboard shortcuts hint */}
            <motion.button
              onClick={() => setShowShortcuts(true)}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              className="hidden sm:flex items-center gap-2 px-3 py-1.5 text-xs text-zinc-500 hover:text-zinc-300 bg-zinc-900 hover:bg-zinc-800 rounded-lg transition-colors border border-zinc-800"
              title="Show keyboard shortcuts"
            >
              <Keyboard size={14} />
              <span>Shortcuts</span>
              <kbd className="px-1.5 py-0.5 bg-zinc-800 rounded text-zinc-400 font-mono">?</kbd>
            </motion.button>

            <AnimatePresence mode="wait">
              {appState !== AppState.UPLOAD && (
                <motion.div
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -20 }}
                  className="flex items-center gap-4 text-sm text-zinc-500"
                >
                  <span className={appState === AppState.CONFIG ? "text-indigo-400 font-medium" : ""}>Configure</span>
                  <span>/</span>
                  <span className={appState === AppState.GENERATING ? "text-indigo-400 font-medium" : ""}>Generate</span>
                  <span>/</span>
                  <span>Preview</span>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
      </motion.header>

      {/* Main Content - Takes remaining space */}
      <main className="flex-1 relative overflow-hidden">
        {/* Animated background blobs */}
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          <motion.div
            className="absolute -top-[20%] -left-[10%] w-[50%] h-[50%] bg-indigo-900/10 rounded-full blur-3xl"
            animate={{
              x: [0, 30, 0],
              y: [0, -20, 0],
              scale: [1, 1.1, 1]
            }}
            transition={{ duration: 8, repeat: Infinity, ease: "easeInOut" }}
          />
          <motion.div
            className="absolute top-[20%] -right-[10%] w-[40%] h-[40%] bg-violet-900/10 rounded-full blur-3xl"
            animate={{
              x: [0, -20, 0],
              y: [0, 30, 0],
              scale: [1, 1.15, 1]
            }}
            transition={{ duration: 10, repeat: Infinity, ease: "easeInOut" }}
          />
        </div>

        <div className="relative z-10 w-full h-full max-w-7xl mx-auto px-6 py-6">
          <AnimatePresence mode="wait">
            {appState === AppState.UPLOAD && (
              <motion.div
                key="upload"
                initial={{ opacity: 0, y: 20, scale: 0.95 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: -20, scale: 1.05 }}
                transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
                className="h-full flex flex-col items-center justify-center space-y-8"
              >
                <motion.div
                  className="text-center space-y-4 max-w-2xl"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.1, duration: 0.5 }}
                >
                  <motion.h2
                    className="text-4xl md:text-5xl font-extrabold tracking-tight text-white"
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2, duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
                  >
                    Turn Markdown into <br />
                    <motion.span
                      className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-400 to-violet-400"
                      animate={{
                        backgroundPosition: ["0% 50%", "100% 50%", "0% 50%"]
                      }}
                      transition={{ duration: 5, repeat: Infinity, ease: "linear" }}
                      style={{ backgroundSize: "200% 200%" }}
                    >
                      Professional Word Docs.
                    </motion.span>
                  </motion.h2>
                  <motion.p
                    className="text-lg text-zinc-400 leading-relaxed"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.4, duration: 0.5 }}
                  >
                    Upload your raw text. Select a style.
                    Get a formatted DOCX file ready for Microsoft Word.
                  </motion.p>
                </motion.div>
                <FileUpload onFileLoaded={handleFileLoaded} />
              </motion.div>
            )}

            {appState === AppState.CONFIG && (
              <motion.div
                key="config"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
                className="h-full"
              >
                <StyleSelector
                  templates={templates}
                  categories={categories}
                  selectedStyle={selectedStyle}
                  onSelectStyle={setSelectedStyle}
                  selectedPaperSize={paperSize}
                  onSelectPaperSize={setPaperSize}
                  onGenerate={handleGenerate}
                  isLoading={templatesLoading}
                  error={templatesError}
                  onOpenTemplatesFolder={openFolder}
                />
                <AnimatePresence>
                  {error && (
                    <motion.div
                      initial={{ opacity: 0, y: -10, scale: 0.95 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: -10, scale: 0.95 }}
                      className="mt-4 p-4 bg-red-900/20 border border-red-800 rounded-xl text-center text-red-300"
                      role="alert"
                      aria-live="polite"
                    >
                      {error}
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            )}

            {appState === AppState.GENERATING && (
              <motion.div
                key="generating"
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 1.1 }}
                transition={{ duration: 0.3 }}
                className="h-full flex flex-col items-center justify-center text-center"
              >
                <motion.div
                  className="relative"
                  animate={{ rotate: 360 }}
                  transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
                >
                  <motion.div
                    className="absolute inset-0 bg-indigo-500 blur-xl opacity-20"
                    animate={{ scale: [1, 1.2, 1], opacity: [0.2, 0.4, 0.2] }}
                    transition={{ duration: 1.5, repeat: Infinity }}
                  />
                  <Loader2 size={64} className="text-indigo-400 relative z-10" />
                </motion.div>
                <motion.h3
                  className="mt-8 text-2xl font-bold text-white"
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.2 }}
                >
                  Formatting Document
                </motion.h3>
                <motion.p
                  className="mt-2 text-zinc-400 max-w-md"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: 0.3 }}
                >
                  Applying typographic rules and preparing print-ready layout...
                </motion.p>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </main>

      {/* Footer - Fixed height, always visible */}
      <motion.footer
        initial={{ y: 20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ delay: 0.5, duration: 0.5 }}
        className="flex-none py-4 text-center text-zinc-600 text-sm border-t border-zinc-900 bg-zinc-950"
      >
        <p>TypoGenie - Professional Typesetting Engine</p>
      </motion.footer>
    </div>
  );
};

export default App;
