'use client'

import { useCallback, useEffect, useState } from 'react'
import { AnimatePresence } from 'framer-motion'
import { useSlideNavigation } from '@/lib/hooks/useSlideNavigation'
import { useKeyboard } from '@/lib/hooks/useKeyboard'
import { usePitchData } from '@/lib/hooks/usePitchData'
import { usePresenterMode } from '@/lib/hooks/usePresenterMode'
import { useAuditTracker } from '@/lib/hooks/useAuditTracker'
import { Language, PitchData } from '@/lib/types'
import { Investor } from '@/lib/hooks/useAuth'

import ParticleBackground from './ParticleBackground'
import ProgressBar from './ProgressBar'
import NavigationControls from './NavigationControls'
import NavigationFAB from './NavigationFAB'
import ChatFAB from './ChatFAB'
import SlideOverview from './SlideOverview'
import SlideContainer from './SlideContainer'
import PresenterOverlay from './presenter/PresenterOverlay'
import AvatarPlaceholder from './presenter/AvatarPlaceholder'
import Watermark from './Watermark'

import IntroPresenterSlide from './slides/IntroPresenterSlide'
import CoverSlide from './slides/CoverSlide'
import ProblemSlide from './slides/ProblemSlide'
import SolutionSlide from './slides/SolutionSlide'
import ProductSlide from './slides/ProductSlide'
import HowItWorksSlide from './slides/HowItWorksSlide'
import MarketSlide from './slides/MarketSlide'
import BusinessModelSlide from './slides/BusinessModelSlide'
import TractionSlide from './slides/TractionSlide'
import CompetitionSlide from './slides/CompetitionSlide'
import TeamSlide from './slides/TeamSlide'
import FinancialsSlide from './slides/FinancialsSlide'
import TheAskSlide from './slides/TheAskSlide'
import AIQASlide from './slides/AIQASlide'
import AssumptionsSlide from './slides/AssumptionsSlide'
import ArchitectureSlide from './slides/ArchitectureSlide'
import GTMSlide from './slides/GTMSlide'
import RegulatorySlide from './slides/RegulatorySlide'
import EngineeringSlide from './slides/EngineeringSlide'
import AIPipelineSlide from './slides/AIPipelineSlide'
import USPSlide from './slides/USPSlide'
import DisclaimerSlide from './slides/DisclaimerSlide'
import ExecutiveSummarySlide from './slides/ExecutiveSummarySlide'
import RegulatoryLandscapeSlide from './slides/RegulatoryLandscapeSlide'
import CapTableSlide from './slides/CapTableSlide'
import SavingsSlide from './slides/SavingsSlide'
import SDKDemoSlide from './slides/SDKDemoSlide'
import StrategySlide from './slides/StrategySlide'
import FinanzplanSlide from './slides/FinanzplanSlide'
import GlossarySlide from './slides/GlossarySlide'
import RiskSlide from './slides/RiskSlide'

interface PitchDeckProps {
  lang: Language
  onToggleLanguage: () => void
  investor: Investor | null
  onLogout: () => void
  previewData?: PitchData | null
}

export default function PitchDeck({ lang, onToggleLanguage, investor, onLogout, previewData }: PitchDeckProps) {
  const fetched = usePitchData()
  const data = previewData || fetched.data
  const loading = previewData ? false : fetched.loading
  const error = previewData ? null : fetched.error
  const nav = useSlideNavigation()
  const [fabOpen, setFabOpen] = useState(false)
  const isWandeldarlehen = (data?.funding?.instrument || '').toLowerCase() === 'wandeldarlehen'

  // For version previews: use the version's default FM scenario instead of base table default
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const fmScenarios = (previewData as any)?.fm_scenarios as Array<{ id: string; is_default?: boolean }> | undefined
  const preferredScenarioId = fmScenarios?.[0]?.is_default
    ? fmScenarios[0].id
    : fmScenarios?.length === 1
      ? fmScenarios[0].id
      : null

  // Skip cap-table slide for Wandeldarlehen versions
  useEffect(() => {
    if (nav.currentSlide === 'cap-table' && isWandeldarlehen) {
      nav.nextSlide()
    }
  }, [nav.currentSlide, isWandeldarlehen, nav.nextSlide])

  const presenter = usePresenterMode({
    goToSlide: nav.goToSlide,
    currentSlide: nav.currentIndex,
    totalSlides: nav.totalSlides,
    language: lang,
  })

  // Audit tracking
  useAuditTracker({
    investorId: investor?.id || null,
    currentSlide: nav.currentSlide,
    enabled: !!investor,
  })

  const toggleFullscreen = useCallback(() => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen()
    } else {
      document.exitFullscreen()
    }
  }, [])

  const toggleMenu = useCallback(() => {
    setFabOpen(prev => !prev)
  }, [])

  useKeyboard({
    onNext: nav.nextSlide,
    onPrev: nav.prevSlide,
    onFirst: nav.goToFirst,
    onLast: nav.goToLast,
    onOverview: nav.toggleOverview,
    onFullscreen: toggleFullscreen,
    onLanguageToggle: onToggleLanguage,
    onMenuToggle: toggleMenu,
    onPresenterToggle: presenter.toggle,
    onGoToSlide: nav.goToSlide,
    enabled: !nav.showOverview,
  })

  if (loading) {
    return (
      <div className="h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="w-12 h-12 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
          <p className="text-white/40 text-sm">{lang === 'de' ? 'Lade Pitch-Daten...' : 'Loading pitch data...'}</p>
        </div>
      </div>
    )
  }

  if (error || !data) {
    return (
      <div className="h-screen flex items-center justify-center">
        <div className="text-center max-w-md">
          <p className="text-red-400 mb-2">{lang === 'de' ? 'Fehler beim Laden' : 'Loading error'}</p>
          <p className="text-white/40 text-sm">{error || 'No data'}</p>
        </div>
      </div>
    )
  }

  function renderSlide() {
    if (!data) return null

    switch (nav.currentSlide) {
      case 'intro-presenter':
        return (
          <IntroPresenterSlide
            lang={lang}
            onStartPresenter={presenter.start}
            isPresenting={presenter.state !== 'idle'}
          />
        )
      case 'executive-summary':
        return <ExecutiveSummarySlide lang={lang} data={data} investorId={investor?.id || null} preferredScenarioId={preferredScenarioId} isWandeldarlehen={isWandeldarlehen} />
      case 'cover':
        return <CoverSlide lang={lang} onNext={nav.nextSlide} funding={data.funding} />
      case 'problem':
        return <ProblemSlide lang={lang} />
      case 'solution':
        return <SolutionSlide lang={lang} />
      case 'usp':
        return <USPSlide lang={lang} />
      case 'regulatory-landscape':
        return <RegulatoryLandscapeSlide lang={lang} />
      case 'product':
        return <ProductSlide lang={lang} products={data.products} />
      case 'how-it-works':
        return <HowItWorksSlide lang={lang} />
      case 'market':
        return <MarketSlide lang={lang} market={data.market} />
      case 'business-model':
        return <BusinessModelSlide lang={lang} products={data.products} investorId={investor?.id || null} preferredScenarioId={preferredScenarioId} isWandeldarlehen={isWandeldarlehen} />
      case 'traction':
        return <TractionSlide lang={lang} milestones={data.milestones} metrics={data.metrics} />
      case 'competition':
        return <CompetitionSlide lang={lang} features={data.features} competitors={data.competitors} />
      case 'team':
        return <TeamSlide lang={lang} team={data.team} />
      case 'financials':
        return <FinancialsSlide lang={lang} investorId={investor?.id || null} preferredScenarioId={preferredScenarioId} isWandeldarlehen={isWandeldarlehen} />
      case 'the-ask':
        return <TheAskSlide lang={lang} funding={data.funding} />
      case 'cap-table':
        if (isWandeldarlehen) return null
        return <CapTableSlide lang={lang} />
      case 'customer-savings':
        return <SavingsSlide lang={lang} />
      case 'ai-qa':
        return <AIQASlide lang={lang} />
      case 'annex-assumptions':
        return <AssumptionsSlide lang={lang} investorId={investor?.id || null} preferredScenarioId={preferredScenarioId} isWandeldarlehen={isWandeldarlehen} />
      case 'annex-architecture':
        return <ArchitectureSlide lang={lang} />
      case 'annex-gtm':
        return <GTMSlide lang={lang} isWandeldarlehen={isWandeldarlehen} />
      case 'annex-regulatory':
        return <RegulatorySlide lang={lang} />
      case 'annex-engineering':
        return <EngineeringSlide lang={lang} />
      case 'annex-aipipeline':
        return <AIPipelineSlide lang={lang} />
      case 'annex-sdk-demo':
        return <SDKDemoSlide lang={lang} />
      case 'annex-strategy':
        return <StrategySlide lang={lang} isWandeldarlehen={isWandeldarlehen} />
      case 'annex-finanzplan':
        return <FinanzplanSlide lang={lang} investorId={investor?.id || null} preferredScenarioId={preferredScenarioId} />
      case 'annex-glossary':
        return <GlossarySlide lang={lang} />
      case 'risks':
        return <RiskSlide lang={lang} />
      case 'legal-disclaimer':
        return <DisclaimerSlide lang={lang} />
      default:
        return null
    }
  }

  return (
    <div
      className="h-screen relative overflow-hidden bg-gradient-to-br from-slate-950 via-[#0a0a1a] to-slate-950 select-none"
      onContextMenu={(e) => e.preventDefault()}
    >
      <ParticleBackground />
      <ProgressBar current={nav.currentIndex} total={nav.totalSlides} />

      {/* Investor watermark */}
      {investor && <Watermark text={investor.email} />}

      <SlideContainer slideKey={nav.currentSlide} direction={nav.direction}>
        {renderSlide()}
      </SlideContainer>

      <NavigationControls
        onPrev={nav.prevSlide}
        onNext={nav.nextSlide}
        isFirst={nav.isFirst}
        isLast={nav.isLast}
        current={nav.currentIndex}
        total={nav.totalSlides}
      />

      <ChatFAB
        lang={lang}
        currentSlide={nav.currentSlide}
        currentIndex={nav.currentIndex}
        visitedSlides={nav.visitedSlides}
        onGoToSlide={nav.goToSlide}
        presenterState={presenter.state}
        onPresenterInterrupt={presenter.pause}
      />

      <NavigationFAB
        currentIndex={nav.currentIndex}
        totalSlides={nav.totalSlides}
        visitedSlides={nav.visitedSlides}
        onGoToSlide={nav.goToSlide}
        lang={lang}
        onToggleLanguage={onToggleLanguage}
      />

      {/* Presenter UI */}
      <AvatarPlaceholder state={presenter.state} />
      <PresenterOverlay
        state={presenter.state}
        currentIndex={nav.currentIndex}
        totalSlides={nav.totalSlides}
        progress={presenter.progress}
        displayText={presenter.displayText}
        lang={lang}
        onPause={presenter.pause}
        onResume={presenter.resume}
        onStop={presenter.stop}
        onSkip={presenter.skipSlide}
      />

      <AnimatePresence>
        {nav.showOverview && (
          <SlideOverview
            currentIndex={nav.currentIndex}
            onGoToSlide={nav.goToSlide}
            onClose={() => nav.setShowOverview(false)}
            lang={lang}
          />
        )}
      </AnimatePresence>
    </div>
  )
}
