import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence, useReducedMotion } 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';
import { useDialog } from './hooks/useDialog';
// @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<{ isOpen: boolean; onClose: () => void }> = ({ isOpen, onClose }) => {
  const { dialogRef, handleBackdropClick, close } = useDialog(isOpen, { 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' },
  ];

  if (!isOpen) return null;

  return (
    <dialog
      ref={dialogRef}
      onClick={handleBackdropClick}
      aria-labelledby="shortcuts-title"
      className="fixed inset-0 z-50 p-4"
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        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" aria-hidden="true">
              <Keyboard size={20} />
            </div>
            <h2 id="shortcuts-title" className="text-xl font-bold text-white">Keyboard Shortcuts</h2>
          </div>
          <button
            onClick={close}
            className="p-2 min-w-[44px] min-h-[44px] flex items-center justify-center hover:bg-zinc-800 rounded-lg text-zinc-400 hover:text-white transition-colors"
            aria-label="Close shortcuts"
          >
            <X size={20} />
          </button>
        </div>
        <dl className="space-y-3">
          {shortcuts.map((shortcut) => (
            <div
              key={shortcut.key}
              className="flex justify-between items-center py-2 border-b border-zinc-800 last:border-0"
            >
              <dt className="text-zinc-400">{shortcut.description}</dt>
              <dd className="ml-4">
                <kbd className="px-2 py-1 bg-zinc-800 rounded text-sm font-mono text-zinc-300 border border-zinc-700">
                  {shortcut.key}
                </kbd>
              </dd>
            </div>
          ))}
        </dl>
        <p className="mt-6 text-xs text-zinc-400 text-center">
          Press Escape or click outside to close
        </p>
      </motion.div>
    </dialog>
  );
};

const App: React.FC = () => {
  const prefersReducedMotion = useReducedMotion();
  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 [statusMessage, setStatusMessage] = useState('');

  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

  // Announce state changes to screen readers
  useEffect(() => {
    const messages: Record<string, string> = {
      [AppState.UPLOAD]: 'Upload screen',
      [AppState.CONFIG]: 'Style configuration',
      [AppState.GENERATING]: 'Generating document',
      [AppState.PREVIEW]: 'Document preview',
    };
    setStatusMessage(messages[appState] || '');
  }, [appState]);

  // Global keydown listener for shortcuts help
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement)?.tagName;
      const isEditable = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement)?.isContentEditable;
      if (isEditable) return;

      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 (
      <div className="h-screen w-screen flex items-center justify-center bg-zinc-950" role="status" aria-live="polite">
        <span className="sr-only">Loading TypoGenie</span>
      </div>
    );
  }

  if (appState === AppState.PREVIEW) {
    return (
      <div
        className="h-screen w-screen overflow-hidden"
        style={{ fontSize: `${uiZoom}%` }}
      >
        <div role="status" aria-live="polite" className="sr-only">{statusMessage}</div>
        <main id="main-content" 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}
          />
        </main>
      </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}%` }}
    >
      <div role="status" aria-live="polite" className="sr-only">{statusMessage}</div>

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

      {/* 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.button
            className="flex items-center gap-2 cursor-pointer bg-transparent border-none"
            onClick={handleReset}
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            aria-label="TypoGenie - Reset to home"
          >
            <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 } }}
              aria-hidden="true"
            >
              <FileType className="text-white" size={20} />
            </motion.div>
            <h1 className="text-xl font-bold tracking-tight text-white">TypoGenie</h1>
          </motion.button>

          <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-400 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} aria-hidden="true" />
                <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-400 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} aria-hidden="true" />
              <span>Shortcuts</span>
              <kbd className="px-1.5 py-0.5 bg-zinc-800 rounded text-zinc-400 font-mono">?</kbd>
            </motion.button>

            <kbd className="sm:hidden px-1.5 py-0.5 bg-zinc-800 rounded text-zinc-400 font-mono text-xs border border-zinc-700 cursor-pointer" onClick={() => setShowShortcuts(true)} role="button" aria-label="Show keyboard shortcuts">?</kbd>

            <AnimatePresence mode="wait">
              {appState !== AppState.UPLOAD && (
                <motion.nav
                  aria-label="Progress"
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -20 }}
                >
                  <ol className="flex items-center gap-4 text-sm text-zinc-400">
                    <li className={appState === AppState.CONFIG ? "text-indigo-400 font-medium" : ""} aria-current={appState === AppState.CONFIG ? "step" : undefined}>Configure</li>
                    <li aria-hidden="true">/</li>
                    <li className={appState === AppState.GENERATING ? "text-indigo-400 font-medium" : ""} aria-current={appState === AppState.GENERATING ? "step" : undefined}>Generate</li>
                    <li aria-hidden="true">/</li>
                    <li className={appState === AppState.PREVIEW ? "text-indigo-400 font-medium" : ""} aria-current={appState === AppState.PREVIEW ? "step" : undefined}>Preview</li>
                  </ol>
                </motion.nav>
              )}
            </AnimatePresence>
          </div>
        </div>
      </motion.header>

      {/* Main Content - Takes remaining space */}
      <main id="main-content" className="flex-1 relative overflow-hidden">
        {/* Animated background blobs */}
        <div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
          <motion.div
            className="absolute -top-[20%] -left-[10%] w-[50%] h-[50%] bg-indigo-900/10 rounded-full blur-3xl"
            animate={prefersReducedMotion ? {} : {
              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={prefersReducedMotion ? {} : {
              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={prefersReducedMotion ? {} : {
                        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"
                    >
                      {error}
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            )}

            {appState === AppState.GENERATING && (
              <motion.div
                key="generating"
                role="status"
                aria-busy="true"
                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={prefersReducedMotion ? {} : { rotate: 360 }}
                  transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
                >
                  <motion.div
                    className="absolute inset-0 bg-indigo-500 blur-xl opacity-20"
                    animate={prefersReducedMotion ? {} : { 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" aria-hidden="true" />
                </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-400 text-sm border-t border-zinc-900 bg-zinc-950"
      >
        <p>TypoGenie - Professional Typesetting Engine</p>
      </motion.footer>
    </div>
  );
};

export default App;
