'use client'

import { useState } from 'react'
import { Language } from '@/lib/types'
import { t } from '@/lib/i18n'
import ProjectionFooter from '../ui/ProjectionFooter'
import { useFinancialModel } from '@/lib/hooks/useFinancialModel'
import { useFpKPIs } from '@/lib/hooks/useFpKPIs'
import GradientText from '../ui/GradientText'
import FadeInView from '../ui/FadeInView'
import FinancialChart from '../ui/FinancialChart'
import FinancialSliders from '../ui/FinancialSliders'
import KPICard from '../ui/KPICard'
import RunwayGauge from '../ui/RunwayGauge'
import WaterfallChart from '../ui/WaterfallChart'
import UnitEconomicsCards from '../ui/UnitEconomicsCards'
import ScenarioSwitcher from '../ui/ScenarioSwitcher'
import AnnualPLTable from '../ui/AnnualPLTable'
import AnnualCashflowChart from '../ui/AnnualCashflowChart'

type FinTab = 'overview' | 'guv' | 'cashflow'

interface FinancialsSlideProps {
  lang: Language
  investorId: string | null
  preferredScenarioId?: string | null
  isWandeldarlehen?: boolean
}

export default function FinancialsSlide({ lang, investorId, preferredScenarioId, isWandeldarlehen }: FinancialsSlideProps) {
  const i = t(lang)
  const fm = useFinancialModel(investorId, preferredScenarioId)
  const [activeTab, setActiveTab] = useState<FinTab>('overview')
  const de = lang === 'de'

  const activeResults = fm.activeResults
  const summary = activeResults?.summary
  const lastResult = activeResults?.results[activeResults.results.length - 1]

  // KPI cards from fp_* tables (source of truth)
  const { last: fpLast, kpis: fpKPIs } = useFpKPIs(isWandeldarlehen)
  const kpiArr = fpLast?.arr || summary?.final_arr || 0
  const kpiCustomers = fpLast?.customers || summary?.final_customers || 0
  const kpiEbit = fpKPIs?.y2029?.ebit  // First profitable year
  const kpiBreakEven = (() => {
    for (const y of [2026, 2027, 2028, 2029, 2030]) {
      if ((fpKPIs[`y${y}`]?.ebit || 0) > 0) return y
    }
    return 0
  })()

  // Build scenario color map
  const scenarioColors: Record<string, string> = {}
  fm.scenarios.forEach(s => { scenarioColors[s.id] = s.color })

  // Build compare results (exclude active scenario)
  const compareResults = new Map(
    Array.from(fm.results.entries()).filter(([id]) => id !== fm.activeScenarioId)
  )

  // Initial funding from assumptions
  const initialFunding = (fm.activeScenario?.assumptions.find(a => a.key === 'initial_funding')?.value as number) || 200000

  const tabs: { id: FinTab; label: string }[] = [
    { id: 'overview', label: de ? 'Übersicht' : 'Overview' },
    { id: 'guv', label: de ? 'GuV (Jahres)' : 'P&L (Annual)' },
    { id: 'cashflow', label: de ? 'Cashflow & Finanzbedarf' : 'Cashflow & Funding' },
  ]

  if (fm.loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <div className="max-w-6xl mx-auto px-4">
      <FadeInView className="text-center mb-3">
        <h2 className="text-3xl md:text-4xl font-bold mb-1">
          <GradientText>{i.financials.title}</GradientText>
        </h2>
        <p className="text-sm text-white/50 max-w-2xl mx-auto">{i.financials.subtitle}</p>
      </FadeInView>

      {/* Hero KPI Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-2 mb-3">
        <KPICard
          label={`ARR 2030`}
          value={kpiArr >= 1_000_000 ? Math.round(kpiArr / 1_000_000 * 10) / 10 : Math.round(kpiArr / 1000)}
          suffix={kpiArr >= 1_000_000 ? ' Mio.' : 'k'}
          decimals={kpiArr >= 1_000_000 ? 1 : 0}
          trend="up"
          color="#6366f1"
          delay={0.1}
          subLabel="EUR"
        />
        <KPICard
          label={de ? 'Kunden 2030' : 'Customers 2030'}
          value={kpiCustomers}
          trend="up"
          color="#22c55e"
          delay={0.15}
        />
        <FadeInView delay={0.2}>
          <div className="bg-white/[0.06] backdrop-blur-xl border border-white/10 rounded-2xl p-3 text-center">
            <p className="text-[10px] uppercase tracking-wider text-white/40 mb-1">Break-Even</p>
            <p className="text-2xl font-bold text-white">{kpiBreakEven || '—'}</p>
            <span className={`text-xs ${kpiBreakEven && kpiBreakEven <= 2029 ? 'text-emerald-400' : 'text-red-400'}`}>
              {kpiBreakEven && kpiBreakEven <= 2029 ? '↑' : kpiBreakEven ? '↓' : ''}
            </span>
          </div>
        </FadeInView>
        <KPICard
          label="EBIT 2030"
          value={fpLast?.ebit ? Math.round(fpLast.ebit / 1_000_000 * 10) / 10 : 0}
          suffix=" Mio."
          decimals={1}
          trend={(fpLast?.ebit || 0) > 0 ? 'up' : 'down'}
          color="#a855f7"
          delay={0.25}
          subLabel="EUR"
        />
      </div>

      {/* Tab Navigation */}
      <div className="flex items-center gap-1 mb-3">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-3 py-1.5 rounded-lg text-xs transition-all
              ${activeTab === tab.id
                ? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/30'
                : 'bg-white/[0.04] text-white/40 border border-transparent hover:text-white/60 hover:bg-white/[0.06] animate-[pulse_3s_ease-in-out_infinite]'
              }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Main content: full width */}
      <div className="space-y-3">

          {/* TAB: Overview — monatlicher Chart + Waterfall + Unit Economics */}
          {activeTab === 'overview' && (
            <>
              <FadeInView delay={0.1}>
                <div className="bg-white/[0.05] backdrop-blur-xl border border-white/10 rounded-2xl p-3">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs text-white/40">
                      {de ? 'Umsatz vs. Kosten (60 Monate)' : 'Revenue vs. Costs (60 months)'}
                    </p>
                    <div className="flex items-center gap-3 text-[9px]">
                      <span className="flex items-center gap-1"><span className="w-2 h-0.5 bg-indigo-500 inline-block" /> {de ? 'Umsatz' : 'Revenue'}</span>
                      <span className="flex items-center gap-1"><span className="w-2 h-0.5 bg-red-400 inline-block" style={{ borderBottom: '1px dashed' }} /> {de ? 'Kosten' : 'Costs'}</span>
                      <span className="flex items-center gap-1"><span className="w-2 h-0.5 bg-emerald-500 inline-block" /> {de ? 'Kunden' : 'Customers'}</span>
                    </div>
                  </div>
                  <FinancialChart
                    activeResults={activeResults}
                    compareResults={compareResults}
                    compareMode={fm.compareMode}
                    scenarioColors={scenarioColors}
                    lang={lang}
                  />
                </div>
              </FadeInView>

              <div className="grid md:grid-cols-2 gap-3">
                <FadeInView delay={0.2}>
                  <div className="bg-white/[0.05] backdrop-blur-xl border border-white/10 rounded-2xl p-3">
                    <p className="text-xs text-white/40 mb-2">
                      {de ? 'Cash-Flow (Quartal)' : 'Cash Flow (Quarterly)'}
                    </p>
                    {activeResults && <WaterfallChart results={activeResults.results} lang={lang} />}
                  </div>
                </FadeInView>

                <FadeInView delay={0.25}>
                  <div className="space-y-3">
                    <div className="bg-white/[0.05] backdrop-blur-xl border border-white/10 rounded-2xl p-3 flex justify-center">
                      <RunwayGauge
                        months={lastResult?.runway_months || 0}
                        size={120}
                        label={de ? 'Runway (Monate)' : 'Runway (months)'}
                      />
                    </div>
                    {lastResult && (
                      <UnitEconomicsCards
                        cac={lastResult.cac_eur}
                        ltv={lastResult.ltv_eur}
                        ltvCacRatio={lastResult.ltv_cac_ratio}
                        grossMargin={lastResult.gross_margin_pct}
                        churnRate={fm.activeScenario?.assumptions.find(a => a.key === 'churn_rate_monthly')?.value as number || 3}
                        lang={lang}
                      />
                    )}
                  </div>
                </FadeInView>
              </div>
            </>
          )}

          {/* TAB: GuV — from fp_guv */}
          {activeTab === 'guv' && (
            <FadeInView delay={0.1}>
              <div className="bg-white/[0.05] backdrop-blur-xl border border-white/10 rounded-2xl p-4">
                <div className="flex items-center justify-between mb-3">
                  <p className="text-xs text-white/40">
                    {de ? 'Gewinn- und Verlustrechnung (5 Jahre)' : 'Profit & Loss Statement (5 Years)'}
                  </p>
                  <p className="text-[9px] text-white/20">
                    {de ? 'Alle Werte in EUR · Quelle: Finanzplan' : 'All values in EUR · Source: Financial Plan'}
                  </p>
                </div>
                <table className="w-full text-xs">
                  <thead>
                    <tr className="border-b border-white/10">
                      <th className="text-left py-2 text-white/40 font-medium"></th>
                      {[2026,2027,2028,2029,2030].map(y => <th key={y} className="text-right py-2 px-2 text-white/40 font-medium">{y}</th>)}
                    </tr>
                  </thead>
                  <tbody>
                    {[
                      { label: de ? 'Umsatzerlöse' : 'Revenue', key: 'revenue', bold: true },
                      { label: de ? 'Personalkosten' : 'Personnel', key: 'personal', bold: false },
                      { label: 'EBIT', key: 'ebit', bold: true },
                      { label: de ? 'Steuern' : 'Taxes', key: 'steuern', bold: false },
                      { label: de ? 'Jahresüberschuss' : 'Net Income', key: 'netIncome', bold: true },
                    ].map((row, idx) => (
                      <tr key={idx} className={`border-b border-white/[0.03] ${row.bold ? 'bg-white/[0.02]' : ''}`}>
                        <td className={`py-1.5 ${row.bold ? 'font-bold text-white/70' : 'text-white/50'}`}>{row.label}</td>
                        {[2026,2027,2028,2029,2030].map(y => {
                          const v = fpKPIs[`y${y}`]?.[row.key as keyof typeof fpKPIs['y2026']] || 0
                          const num = typeof v === 'number' ? v : 0
                          return (
                            <td key={y} className={`text-right py-1.5 px-2 font-mono ${num < 0 ? 'text-red-400' : row.bold ? 'text-white/70 font-bold' : 'text-white/50'}`}>
                              {num === 0 ? '—' : (num >= 1000000 || num <= -1000000) ? `${(num/1000000).toFixed(1)}M` : `${Math.round(num/1000)}k`}
                            </td>
                          )
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </FadeInView>
          )}

          {/* TAB: Cashflow — from fp_* */}
          {activeTab === 'cashflow' && (
            <FadeInView delay={0.1}>
              <div className="bg-white/[0.05] backdrop-blur-xl border border-white/10 rounded-2xl p-4">
                <p className="text-xs text-white/40 mb-3">
                  {de ? 'Liquidität & Cashflow (5 Jahre) · Quelle: Finanzplan' : 'Liquidity & Cash Flow (5 Years) · Source: Financial Plan'}
                </p>
                <div className="grid grid-cols-5 gap-2 items-end h-48">
                  {[2026,2027,2028,2029,2030].map((y, idx) => {
                    const liq = fpKPIs[`y${y}`]?.liquiditaet || 0
                    const ebit = fpKPIs[`y${y}`]?.ebit || 0
                    const maxAbs = Math.max(...[2026,2027,2028,2029,2030].map(yr => Math.abs(fpKPIs[`y${yr}`]?.liquiditaet || 0)), 1)
                    const h = Math.abs(liq) / maxAbs * 140
                    return (
                      <div key={idx} className="flex flex-col items-center">
                        <div className="text-[8px] text-white/40 mb-1">{liq >= 1000000 ? `${(liq/1000000).toFixed(1)}M` : liq <= -1000000 ? `${(liq/1000000).toFixed(1)}M` : `${Math.round(liq/1000)}k`}</div>
                        <div className="w-12 flex flex-col justify-end" style={{ height: '150px' }}>
                          <div className={`${liq >= 0 ? 'bg-emerald-500/60 rounded-t' : 'bg-red-500/60 rounded-b'} w-full`} style={{ height: `${Math.max(h, 4)}px` }} />
                        </div>
                        <span className="text-[10px] text-white/40 mt-1">{y}</span>
                        <span className={`text-[8px] mt-0.5 ${ebit >= 0 ? 'text-emerald-400/60' : 'text-red-400/60'}`}>
                          EBIT: {ebit >= 1000000 ? `${(ebit/1000000).toFixed(1)}M` : `${Math.round(ebit/1000)}k`}
                        </span>
                      </div>
                    )
                  })}
                </div>
                <div className="flex justify-center gap-6 mt-3 text-[10px]">
                  <span className="flex items-center gap-1"><span className="w-3 h-2 bg-emerald-500/60 rounded inline-block" /> {de ? 'Liquidität (positiv)' : 'Cash (positive)'}</span>
                  <span className="flex items-center gap-1"><span className="w-3 h-2 bg-red-500/60 rounded inline-block" /> {de ? 'Liquidität (negativ)' : 'Cash (negative)'}</span>
                </div>
              </div>
            </FadeInView>
          )}
      </div>
      <ProjectionFooter lang={lang} />
    </div>
  )
}
