import { Routes, Route, Link, useLocation } from 'react-router-dom';
import { RecipeListPage } from './pages/RecipeListPage';
import { RecipeDetailPage } from './pages/RecipeDetailPage';
import { CookModePage } from './pages/CookModePage';
import { NotFoundPage } from './pages/NotFoundPage';
import { ImportUrlPage } from './pages/ImportUrlPage';
import { ErrorBoundary } from './components/ErrorBoundary';
import { ToastContainer } from './components/Toast';
import { useToast } from './hooks/useToast';
import { createContext, useContext } from 'react';
import { UiPage } from './components/ui/primitives';
import { cn } from './components/ui/cn';

interface ToastContextType {
  success: (message: string, duration?: number) => string;
  error: (message: string, duration?: number) => string;
  info: (message: string, duration?: number) => string;
  warning: (message: string, duration?: number) => string;
}

const ToastContext = createContext<ToastContextType | null>(null);

function BookIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4" aria-hidden="true">
      <path d="M5 5.5A2.5 2.5 0 0 1 7.5 3H19v16H7.5A2.5 2.5 0 0 0 5 21V5.5Z" />
      <path d="M5 21h14" />
    </svg>
  );
}

function PlusIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-4 w-4" aria-hidden="true">
      <path d="M12 5v14" />
      <path d="M5 12h14" />
    </svg>
  );
}

function LinkIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4" aria-hidden="true">
      <path d="M10 13a5 5 0 0 0 7.07 0l2.12-2.12a5 5 0 0 0-7.07-7.07L10.7 5.23" />
      <path d="M14 11a5 5 0 0 0-7.07 0L4.8 13.12a5 5 0 0 0 7.07 7.07l1.42-1.42" />
    </svg>
  );
}

export function useToastContext() {
  const context = useContext(ToastContext);
  if (!context) {
    throw new Error('useToastContext must be used within ToastProvider');
  }
  return context;
}

function App() {
  const location = useLocation();
  const toast = useToast();

  const isActive = (path: string) => {
    if (path === '/' && location.pathname === '/') return true;
    if (path !== '/' && location.pathname.startsWith(path)) return true;
    return false;
  };

  const linkClass = (path: string) =>
    cn(
      'ui-btn min-h-0 rounded-full border border-transparent px-4 py-2 text-sm font-semibold shadow-none',
      isActive(path)
        ? 'bg-[var(--color-primary-light)] text-[var(--color-primary-dark)]'
        : 'bg-transparent text-[var(--text-dim)] hover:bg-[var(--surface-muted)] hover:text-[var(--text)]',
    );

  return (
    <ErrorBoundary>
      <ToastContext.Provider value={toast}>
        <div className="min-h-screen text-[var(--text)]">
          <ToastContainer messages={toast.messages} onClose={toast.removeToast} />

          <header className="sticky top-0 z-20 border-b border-[var(--border)]/70 bg-[var(--surface)]/85 shadow-sm backdrop-blur-md">
            <UiPage className="px-4 py-0">
              <div className="flex h-16 items-center justify-between gap-3">
                <div className="flex items-center">
                  <Link
                    to="/"
                    className="group inline-flex items-center gap-2 rounded-lg px-2 py-1.5 outline-none transition-colors duration-200 hover:text-[var(--color-primary-dark)]"
                  >
                    <span className="text-xl" aria-hidden="true">🍽️</span>
                    <h1 className="text-xl font-bold tracking-tight text-[var(--text-h)] sm:text-2xl">Recipe Manager</h1>
                  </Link>
                </div>
                <nav aria-label="Primary" className="flex flex-wrap items-center justify-end gap-2 sm:gap-3">
                  <Link to="/" className={linkClass('/')}>
                    <BookIcon />
                    <span>Recipes</span>
                  </Link>
                  <Link to="/recipe/new" className={linkClass('/recipe/new')}>
                    <PlusIcon />
                    <span>Add Recipe</span>
                  </Link>
                  <Link to="/import/url" className={linkClass('/import/url')}>
                    <LinkIcon />
                    <span>Import URL</span>
                  </Link>
                </nav>
              </div>
            </UiPage>
          </header>

          <main className="ui-page min-h-[70vh] px-4 py-8">
            <Routes>
              <Route path="/" element={<RecipeListPage />} />
              <Route path="/recipe/new" element={<RecipeDetailPage />} />
              <Route path="/recipe/:id" element={<RecipeDetailPage />} />
              <Route path="/recipe/:id/cook" element={<CookModePage />} />
              <Route path="/import/url" element={<ImportUrlPage />} />
              <Route path="*" element={<NotFoundPage />} />
            </Routes>
          </main>

          <footer className="mt-10 border-t border-[var(--border)]/80 bg-gradient-to-br from-[var(--surface)]/95 to-[var(--surface-muted)]/90 backdrop-blur-sm">
            <UiPage className="grid grid-cols-1 gap-6 px-4 py-8 sm:grid-cols-2 lg:grid-cols-3">
              <div>
                <p className="text-sm font-semibold uppercase tracking-wide text-[var(--color-primary-dark)]">Recipe Manager</p>
                <p className="mt-2 text-sm text-[var(--text-dim)]">Save recipes, organize by tags, and keep your kitchen workflow simple.</p>
              </div>
              <div>
                <p className="text-sm font-semibold uppercase tracking-wide text-[var(--text)]">Quick Links</p>
                <div className="mt-2 flex flex-wrap gap-2 text-sm text-[var(--text-dim)]">
                  <Link to="/" className="ui-chip bg-[var(--surface)] px-3 py-1 hover:bg-[var(--surface-muted)]">Browse</Link>
                  <Link to="/recipe/new" className="ui-chip bg-[var(--surface)] px-3 py-1 hover:bg-[var(--surface-muted)]">Add Recipe</Link>
                  <Link to="/import/url" className="ui-chip bg-[var(--surface)] px-3 py-1 hover:bg-[var(--surface-muted)]">Import URL</Link>
                </div>
              </div>
              <div className="sm:col-span-2 lg:col-span-1">
                <p className="text-sm font-semibold uppercase tracking-wide text-[var(--text)]">Built for everyday cooking</p>
                <p className="mt-2 text-sm text-[var(--text-dim)]">React + Vite + TypeScript · Visual redesign in progress</p>
              </div>
            </UiPage>
          </footer>
        </div>
      </ToastContext.Provider>
    </ErrorBoundary>
  );
}

export default App;
