'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
  fpBaseScenarioId?: string | null
}

export default function FinancialsSlide({ lang, investorId, preferredScenarioId, isWandeldarlehen, fpBaseScenarioId }: 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(fpBaseScenarioId)
  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 — annual charts from fp_* */}
          {activeTab === 'overview' && (
            <>
              {/* Revenue vs Costs */}
              <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 ? 'Umsatz vs. Kosten (pro Jahr) · Quelle: Finanzplan' : 'Revenue vs. Costs (per year) · Source: Financial Plan'}</p>
                  <div className="grid grid-cols-5 gap-3 items-end h-40">
                    {[2026,2027,2028,2029,2030].map((y, idx) => {
                      const rev = fpKPIs[`y${y}`]?.revenue || 0
                      const costs = rev - (fpKPIs[`y${y}`]?.ebit || 0)
                      const cust = fpKPIs[`y${y}`]?.customers || 0
                      const maxVal = Math.max(...[2026,2027,2028,2029,2030].map(yr => Math.max(fpKPIs[`y${yr}`]?.revenue || 0, (fpKPIs[`y${yr}`]?.revenue || 0) - (fpKPIs[`y${yr}`]?.ebit || 0))), 1)
                      return (
                        <div key={idx} className="flex flex-col items-center gap-1">
                          <div className="flex items-end gap-1 w-full justify-center" style={{ height: '110px' }}>
                            <div className="w-7 bg-indigo-500/60 rounded-t" style={{ height: `${(rev / maxVal) * 100}px` }}>
                              <div className="text-[10px] text-indigo-300 text-center -mt-4 whitespace-nowrap font-semibold">{rev >= 1000000 ? `${(rev/1000000).toFixed(1)}M` : `${Math.round(rev/1000)}k`}</div>
                            </div>
                            <div className="w-7 bg-red-500/40 rounded-t" style={{ height: `${(costs / maxVal) * 100}px` }}>
                              <div className="text-[10px] text-red-300 text-center -mt-4 whitespace-nowrap font-semibold">{costs >= 1000000 ? `${(costs/1000000).toFixed(1)}M` : `${Math.round(costs/1000)}k`}</div>
                            </div>
                          </div>
                          <span className="text-xs text-white/50 font-medium">{y}</span>
                          <span className="text-[9px] text-emerald-400/60">{cust} {de ? 'Kd.' : 'cust.'}</span>
                        </div>
                      )
                    })}
                  </div>
                  <div className="flex justify-center gap-6 mt-2 text-[10px]">
                    <span className="flex items-center gap-1"><span className="w-3 h-2 bg-indigo-500/60 rounded inline-block" /> {de ? 'Umsatz' : 'Revenue'}</span>
                    <span className="flex items-center gap-1"><span className="w-3 h-2 bg-red-500/40 rounded inline-block" /> {de ? 'Kosten' : 'Costs'}</span>
                  </div>
                </div>
              </FadeInView>

              <div className="grid md:grid-cols-2 gap-3">
                {/* EBIT + Liquidität */}
                <FadeInView delay={0.2}>
                  <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">EBIT & {de ? 'Liquidität' : 'Cash'}</p>
                    <div className="grid grid-cols-5 gap-1 items-end h-28">
                      {[2026,2027,2028,2029,2030].map((y, idx) => {
                        const ebit = fpKPIs[`y${y}`]?.ebit || 0
                        const liq = fpKPIs[`y${y}`]?.liquiditaet || 0
                        const maxAbs = Math.max(...[2026,2027,2028,2029,2030].map(yr => Math.max(Math.abs(fpKPIs[`y${yr}`]?.ebit || 0), Math.abs(fpKPIs[`y${yr}`]?.liquiditaet || 0))), 1)
                        return (
                          <div key={idx} className="flex flex-col items-center gap-0.5">
                            <div className="flex items-end gap-0.5 justify-center" style={{ height: '80px' }}>
                              <div className={`w-5 ${ebit >= 0 ? 'bg-emerald-500/60 rounded-t' : 'bg-red-500/60 rounded-b'}`} style={{ height: `${Math.max(Math.abs(ebit)/maxAbs * 70, 2)}px` }} />
                              <div className={`w-5 ${liq >= 0 ? 'bg-cyan-500/60 rounded-t' : 'bg-red-500/40 rounded-b'}`} style={{ height: `${Math.max(Math.abs(liq)/maxAbs * 70, 2)}px` }} />
                            </div>
                            <span className="text-[9px] text-white/40">{y}</span>
                          </div>
                        )
                      })}
                    </div>
                    <div className="flex justify-center gap-4 mt-2 text-[9px]">
                      <span className="flex items-center gap-1"><span className="w-2 h-2 bg-emerald-500/60 rounded inline-block" /> EBIT</span>
                      <span className="flex items-center gap-1"><span className="w-2 h-2 bg-cyan-500/60 rounded inline-block" /> {de ? 'Liquidität' : 'Cash'}</span>
                    </div>
                  </div>
                </FadeInView>

                {/* Key Metrics */}
                <FadeInView delay={0.25}>
                  <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">Unit Economics (2030)</p>
                    <div className="grid grid-cols-2 gap-3">
                      {[
                        { label: 'ACV', value: fpLast?.arpu ? `${fpLast.arpu.toLocaleString('de-DE')} EUR` : '—', color: 'text-indigo-300' },
                        { label: 'Gross Margin', value: fpLast?.grossMargin ? `${fpLast.grossMargin}%` : '—', color: 'text-emerald-300' },
                        { label: 'NRR', value: fpLast?.nrr ? `${fpLast.nrr}%` : '—', color: 'text-purple-300' },
                        { label: 'EBIT Margin', value: fpLast?.ebitMargin ? `${fpLast.ebitMargin}%` : '—', color: 'text-amber-300' },
                      ].map((m, idx) => (
                        <div key={idx} className="text-center bg-white/[0.03] rounded-lg p-2">
                          <p className="text-[10px] text-white/40 uppercase tracking-wider">{m.label}</p>
                          <p className={`text-lg font-bold ${m.color}`}>{m.value}</p>
                        </div>
                      ))}
                    </div>
                  </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>
  )
}
