'use client'

import { motion } from 'framer-motion'
import { Language, PitchFunding } from '@/lib/types'
import { t } from '@/lib/i18n'
import ProjectionFooter from '../ui/ProjectionFooter'
import GradientText from '../ui/GradientText'
import FadeInView from '../ui/FadeInView'
import AnimatedCounter from '../ui/AnimatedCounter'
import GlassCard from '../ui/GlassCard'
import { Landmark, Banknote, ArrowRightLeft, TrendingUp, ShieldCheck, Target, Calendar, FileText } from 'lucide-react'
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from 'recharts'

interface TheAskSlideProps {
  lang: Language
  funding: PitchFunding
}

const COLORS = ['#6366f1', '#a78bfa', '#60a5fa', '#34d399', '#fbbf24']

function formatFundingAmount(amount: number): { target: number; suffix: string } {
  if (amount >= 1_000_000) {
    return { target: Math.round(amount / 100_000) / 10, suffix: ' Mio.' }
  }
  if (amount >= 1_000) {
    return { target: Math.round(amount / 1_000), suffix: 'k' }
  }
  return { target: amount, suffix: '' }
}

function formatTargetDate(dateStr: string, lang: Language): string {
  if (!dateStr) return 'TBD'
  try {
    const d = new Date(dateStr)
    const quarter = Math.ceil((d.getMonth() + 1) / 3)
    return `Q${quarter} ${d.getFullYear()}`
  } catch {
    return dateStr
  }
}

export default function TheAskSlide({ lang, funding }: TheAskSlideProps) {
  const i = t(lang)
  const de = lang === 'de'
  const isWandeldarlehen = (funding?.instrument || '').toLowerCase().includes('wandeldarlehen')
  const rawFunds = funding?.use_of_funds
  const useOfFunds = Array.isArray(rawFunds) ? rawFunds : (typeof rawFunds === 'string' ? JSON.parse(rawFunds) : [])
  const amount = Number(funding?.amount_eur) || 0
  const { target, suffix } = formatFundingAmount(amount)
  const totalBudget = isWandeldarlehen ? amount * 2 : amount

  const pieData = useOfFunds.map((item: Record<string, unknown>) => ({
    name: (de ? item.label_de : item.label_en) as string || 'N/A',
    value: Number(item.percentage) || 0,
  }))

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

      {/* Main Number — dynamisch aus funding.amount_eur */}
      <FadeInView delay={0.2} className="text-center mb-10">
        <motion.div
          initial={{ scale: 0.5, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ delay: 0.4, type: 'spring', stiffness: 200 }}
        >
          <p className="text-6xl md:text-8xl font-bold text-white mb-2">
            <AnimatedCounter target={target} suffix={suffix} duration={2000} decimals={suffix === ' Mio.' ? 1 : 0} />
            <span className="text-3xl md:text-4xl text-white/50 ml-2">EUR</span>
          </p>
        </motion.div>
        {isWandeldarlehen && (
          <div className="space-y-3 mt-4">
            {/* Row 1: 200k Scenario */}
            <div className="flex items-center justify-center gap-3">
              <div className="text-center px-4 py-2 bg-indigo-500/10 border border-indigo-500/20 rounded-xl">
                <p className="text-xs text-white/40">{de ? 'Ihr Investment' : 'Your Investment'}</p>
                <p className="text-lg font-bold text-indigo-400">40k EUR</p>
                <p className="text-[10px] text-white/30">{de ? 'ab 20% — auch mehr möglich' : 'from 20% — more possible'}</p>
              </div>
              <span className="text-2xl text-white/30 font-light">+</span>
              <div className="text-center px-4 py-2 bg-emerald-500/10 border border-emerald-500/20 rounded-xl">
                <p className="text-xs text-white/40">L-Bank Pre-Seed</p>
                <p className="text-lg font-bold text-emerald-400">160k EUR</p>
              </div>
              <span className="text-2xl text-white/30 font-light">=</span>
              <div className="text-center px-4 py-2 bg-white/5 border border-white/10 rounded-xl">
                <p className="text-xs text-white/40">{de ? 'Gesamtfinanzierung' : 'Total Funding'}</p>
                <p className="text-lg font-bold text-white">200k EUR</p>
              </div>
            </div>
            {/* Row 2: 400k Scenario (optional) */}
            <div className="flex items-center justify-center gap-3 opacity-60">
              <div className="text-center px-3 py-1.5 bg-indigo-500/5 border border-indigo-500/10 rounded-xl">
                <p className="text-[10px] text-white/30">{de ? 'Ihr Investment' : 'Your Investment'}</p>
                <p className="text-sm font-bold text-indigo-400/70">80k EUR</p>
              </div>
              <span className="text-lg text-white/20 font-light">+</span>
              <div className="text-center px-3 py-1.5 bg-emerald-500/5 border border-emerald-500/10 rounded-xl">
                <p className="text-[10px] text-white/30">L-Bank Pre-Seed</p>
                <p className="text-sm font-bold text-emerald-400/70">320k EUR</p>
              </div>
              <span className="text-lg text-white/20 font-light">=</span>
              <div className="text-center px-3 py-1.5 bg-white/5 border border-white/10 rounded-xl">
                <p className="text-[10px] text-white/30">{de ? 'Gesamtfinanzierung' : 'Total Funding'}</p>
                <p className="text-sm font-bold text-white/70">400k EUR</p>
              </div>
            </div>
            <p className="text-[10px] text-white/25 text-center">
              {de ? 'Optional: doppelte Tranche bei höherem Investor-Anteil' : 'Optional: double tranche with higher investor share'}
            </p>
          </div>
        )}
      </FadeInView>

      {/* Details — dynamisch aus funding-Objekt */}
      <div className="grid md:grid-cols-3 gap-4 mb-8">
        <GlassCard delay={0.5} className="text-center p-5">
          <FileText className="w-6 h-6 text-indigo-400 mx-auto mb-2" />
          <p className="text-xs text-white/40 mb-1">{i.theAsk.instrument}</p>
          <p className="text-lg font-bold text-white">{funding?.instrument || 'SAFE'}</p>
        </GlassCard>
        <GlassCard delay={0.6} className="text-center p-5">
          <Calendar className="w-6 h-6 text-purple-400 mx-auto mb-2" />
          <p className="text-xs text-white/40 mb-1">{i.theAsk.targetDate}</p>
          <p className="text-lg font-bold text-white">
            {formatTargetDate(funding?.target_date, lang)}
          </p>
        </GlassCard>
        <GlassCard delay={0.7} className="text-center p-5">
          <Target className="w-6 h-6 text-blue-400 mx-auto mb-2" />
          <p className="text-xs text-white/40 mb-1">{lang === 'de' ? 'Runde' : 'Round'}</p>
          <p className="text-lg font-bold text-white">{funding?.round_name || 'Pre-Seed'}</p>
        </GlassCard>
      </div>

      {/* Wandeldarlehen Explanation — only shown for Wandeldarlehen versions */}
      {isWandeldarlehen && (
        <>
          {/* How it works */}
          <FadeInView delay={0.5} className="mb-6">
            <GlassCard hover={false} className="p-6">
              <h3 className="text-lg font-semibold text-white mb-4 text-center">
                {de ? 'So funktioniert das Wandeldarlehen' : 'How the Convertible Loan Works'}
              </h3>
              <div className="grid md:grid-cols-3 gap-4">
                <div className="text-center p-4 bg-white/5 rounded-xl">
                  <Banknote className="w-6 h-6 text-indigo-400 mx-auto mb-2" />
                  <p className="text-sm font-bold text-white mb-1">
                    {de ? '1. Investition' : '1. Investment'}
                  </p>
                  <p className="text-xs text-white/50 leading-relaxed">
                    {de
                      ? 'Investor stellt Darlehen bereit — keine sofortige Bewertung, keine sofortige Verwässerung.'
                      : 'Investor provides a loan — no immediate valuation, no immediate dilution.'}
                  </p>
                </div>
                <div className="text-center p-4 bg-white/5 rounded-xl">
                  <ArrowRightLeft className="w-6 h-6 text-purple-400 mx-auto mb-2" />
                  <p className="text-sm font-bold text-white mb-1">
                    {de ? '2. Conversion' : '2. Conversion'}
                  </p>
                  <p className="text-xs text-white/50 leading-relaxed">
                    {de
                      ? 'Bei der nächsten Finanzierungsrunde wandelt das Darlehen in Anteile — mit Discount für den Frühphasen-Investor.'
                      : 'At the next funding round, the loan converts to equity — with a discount for the early-stage investor.'}
                  </p>
                </div>
                <div className="text-center p-4 bg-white/5 rounded-xl">
                  <TrendingUp className="w-6 h-6 text-emerald-400 mx-auto mb-2" />
                  <p className="text-sm font-bold text-white mb-1">
                    {de ? '3. Investor-Vorteil' : '3. Investor Advantage'}
                  </p>
                  <p className="text-xs text-white/50 leading-relaxed">
                    {de
                      ? 'Durch den Discount erhält der Investor mehr Anteile pro Euro als spätere Investoren — Prämie für frühes Vertrauen.'
                      : 'The discount gives the investor more shares per euro than later investors — a premium for early trust.'}
                  </p>
                </div>
              </div>
            </GlassCard>
          </FadeInView>

          {/* Pre-Seed BW / L-Bank */}
          <FadeInView delay={0.6} className="mb-6">
            <div className="bg-gradient-to-r from-emerald-500/10 to-blue-500/10 border border-emerald-500/20 rounded-xl px-5 py-3">
              <div className="flex items-start gap-3">
                <ShieldCheck className="w-5 h-5 text-emerald-400 mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-bold text-white mb-1">
                    {de ? 'Pre-Seed BW — Staatliche Co-Finanzierung (L-Bank)' : 'Pre-Seed BW — Government Co-Financing (L-Bank)'}
                  </p>
                  <p className="text-xs text-white/50 leading-relaxed">
                    {de
                      ? 'Das Investment wird über das Pre-Seed-Programm von Start-up BW / L-Bank staatlich co-finanziert. Die L-Bank stellt eine Zuwendung mit Wandlungsvorbehalt bereit — das reduziert das Risiko für private Investoren und signalisiert staatliches Vertrauen in das Geschäftsmodell.'
                      : 'The investment is co-financed through the Pre-Seed BW / L-Bank government program. L-Bank provides a grant with conversion option — reducing risk for private investors and signaling government confidence in the business model.'}
                  </p>
                </div>
              </div>
            </div>
          </FadeInView>

        </>
      )}

      {/* Use of Funds */}
      <FadeInView delay={0.8}>
        <GlassCard hover={false} className="p-6">
          <h3 className="text-lg font-semibold text-white mb-4 text-center">{i.theAsk.useOfFunds}</h3>
          <div className="flex flex-col md:flex-row items-center gap-8">
            {/* Pie Chart */}
            <div className="w-48 h-48">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={pieData}
                    cx="50%"
                    cy="50%"
                    innerRadius={50}
                    outerRadius={80}
                    dataKey="value"
                    stroke="none"
                  >
                    {pieData.map((_, idx) => (
                      <Cell key={idx} fill={COLORS[idx % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    contentStyle={{
                      background: 'rgba(10, 10, 26, 0.9)',
                      border: '1px solid rgba(255,255,255,0.1)',
                      borderRadius: 8,
                      color: '#fff',
                      fontSize: 13,
                    }}
                    formatter={(value: number) => `${value}%`}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>

            {/* Legend */}
            <div className="flex-1 space-y-3">
              {useOfFunds.map((item, idx) => (
                <div key={idx} className="flex items-center gap-3">
                  <div className="w-3 h-3 rounded-full" style={{ backgroundColor: COLORS[idx] }} />
                  <span className="flex-1 text-sm text-white/70">
                    {lang === 'de' ? item.label_de : item.label_en}
                  </span>
                  <span className="text-sm font-bold text-white">{item.percentage}%</span>
                  <span className="text-xs text-white/30">
                    {((totalBudget * item.percentage) / 100).toLocaleString('de-DE')} EUR
                  </span>
                </div>
              ))}
            </div>
          </div>
        </GlassCard>
      </FadeInView>

      {/* INVEST Program Hint */}
      <FadeInView delay={0.6} className="mt-4">
        <div className="bg-gradient-to-r from-indigo-500/10 to-emerald-500/10 border border-indigo-500/20 rounded-xl px-5 py-3">
          <div className="flex items-start gap-3">
            <Landmark className="w-5 h-5 text-indigo-400 mt-0.5 shrink-0" />
            <div>
              <p className="text-sm font-bold text-white mb-1">
                {de
                  ? 'BAFA INVEST — Zuschuss für Wagniskapital (Kombinierbarkeit mit L-Bank Wandeldarlehen muss geprüft werden)'
                  : 'BAFA INVEST — Venture Capital Grant (Compatibility with L-Bank convertible loan must be verified)'}
              </p>
              <p className="text-xs text-white/50 leading-relaxed">
                {de
                  ? 'Investoren erhalten über das BAFA INVEST-Programm bis zu 15% steuerfreien Erwerbszuschuss auf ihr Investment (max. 50.000 EUR pro Einzelinvestment) sowie zusätzlich 25% Exit-Zuschuss auf Veräußerungsgewinne. Effektive Förderung: bis zu 40% (Entry + Exit kombiniert). Voraussetzung: natürliche Person, Mindesthaltedauer 3 Jahre.'
                  : 'Investors receive up to 15% tax-free acquisition grant on their investment through the BAFA INVEST program (max. EUR 50,000 per single investment) plus an additional 25% exit grant on capital gains. Effective support: up to 40% (entry + exit combined). Requirements: natural person, 3-year minimum holding period.'}
              </p>
              <p className="text-[11px] text-white/30 mt-1 italic">
                {de
                  ? '* Programm verlängert bis 31.12.2026. Aktuelle Konditionen auf bafa.de prüfen.'
                  : '* Program extended until 31.12.2026. Verify current terms at bafa.de.'}
              </p>
            </div>
          </div>
        </div>
      </FadeInView>

      <ProjectionFooter lang={lang} />
    </div>
  )
}
