'use client';

import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { Send } from 'lucide-react';
import MainPageBackground from '@/app/components/landing/MainPageBackground';
import TelegramLoginModal from '@/app/components/landing/TelegramLoginModal';
import NotebookWorkspace from '@/app/components/notebook/NotebookWorkspace';
import { config } from '@/lib/config';
import { getRuntimeClientConfig } from '@/lib/runtime-client-config';
import type { PlanFeatures } from '@/lib/plans/types';

type PublicNotesPlanState = {
  features?: PlanFeatures;
} | null;

function LinkIcon() {
  return (
    <svg className="h-4 w-4 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
      <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
    </svg>
  );
}

function TelegramIcon() {
  return (
    <svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M21.8 4.1a1.7 1.7 0 0 0-1.8-.26L3.1 10.8a1.5 1.5 0 0 0 .1 2.8l4.2 1.5 1.7 5.2a1.5 1.5 0 0 0 2.6.5l2.6-3 4.6 3.4a1.7 1.7 0 0 0 2.7-1l2.2-14.2a1.7 1.7 0 0 0-.9-1.9Zm-3.1 3-8.4 7.7a.7.7 0 0 0-.2.3l-.8 2.4-.8-2.5a.8.8 0 0 0-.5-.5l-2.7-1 13.4-5.4Z" />
    </svg>
  );
}

function Navbar({
  onOpenLogin,
  isAuthenticated,
}: {
  onOpenLogin: () => void;
  isAuthenticated: boolean;
}) {
  const runtimeConfig = getRuntimeClientConfig();
  const projectName = runtimeConfig.projectName || config.projectName;

  return (
    <motion.nav
      initial={{ y: -20, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      className="fixed top-0 inset-x-0 z-50 h-20 flex items-center px-6 lg:px-12 backdrop-blur-xl border-b border-white/5 bg-black/40"
    >
      <div className="w-full max-w-7xl mx-auto flex items-center justify-between">
        <Link href="/" className="flex items-center gap-3">
          <div className="h-8 w-8 rounded-lg bg-gradient-to-br from-violet-500 to-[#2AABEE] flex items-center justify-center shadow-lg shadow-violet-500/20">
            <LinkIcon />
          </div>
          <span className="text-xl font-bold tracking-tight text-white">{projectName}</span>
        </Link>

        <button
          type="button"
          onClick={onOpenLogin}
          className="px-4 py-2 text-sm font-medium rounded-xl bg-white/[0.03] border border-white/10 text-white hover:bg-white/10 transition-all flex items-center gap-2"
        >
          {isAuthenticated ? <Send className="h-4 w-4" /> : <TelegramIcon />}
          <span className="hidden sm:inline">{isAuthenticated ? 'Панель' : 'Войти через Telegram'}</span>
          <span className="sm:hidden">{isAuthenticated ? 'Панель' : 'Войти'}</span>
        </button>
      </div>
    </motion.nav>
  );
}

export default function PublicNotesPage() {
  const router = useRouter();
  const { status } = useSession();
  const isAuthenticated = status === 'authenticated';
  const [isLoginModalOpen, setIsLoginModalOpen] = useState(false);
  const [planState, setPlanState] = useState<PublicNotesPlanState>(null);

  const handleOpenLogin = useCallback(() => {
    if (isAuthenticated) {
      router.push('/profile', { scroll: false });
      return;
    }
    setIsLoginModalOpen(true);
  }, [isAuthenticated, router]);

  useEffect(() => {
    if (!isAuthenticated) {
      setPlanState(null);
      return;
    }

    let cancelled = false;

    const loadPlan = async () => {
      try {
        const response = await fetch('/api/profile/plan', { cache: 'no-store' });
        if (!response.ok) return;
        const data = await response.json() as PublicNotesPlanState;
        if (!cancelled) {
          setPlanState(data);
        }
      } catch {
        if (!cancelled) {
          setPlanState(null);
        }
      }
    };

    void loadPlan();

    return () => {
      cancelled = true;
    };
  }, [isAuthenticated]);

  return (
    <div className="relative min-h-screen text-white selection:bg-violet-500/30">
      <MainPageBackground />
      <Navbar onOpenLogin={handleOpenLogin} isAuthenticated={isAuthenticated} />

      <main className="relative z-10 mx-auto w-full max-w-4xl px-4 pb-24 pt-32">
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          className="space-y-6"
        >
          <NotebookWorkspace
            isAuthenticated={isAuthenticated}
            planState={planState}
            unauthenticatedActiveNotesMessage="Вы не зарегистрированы, поэтому список активных записок недоступен."
          />
        </motion.div>
      </main>

      <AnimatePresence>
        {isLoginModalOpen ? (
          <TelegramLoginModal
            onClose={() => setIsLoginModalOpen(false)}
            returnTo="/profile"
          />
        ) : null}
      </AnimatePresence>
    </div>
  );
}
