'use client'

import {
  SheetRow, MONTH_LABELS, MONTH_LABELS_EN, FORMULA_TOOLTIPS, FORMULA_TOOLTIPS_EN, ROW_LABEL_MAP,
  getLabel, getValues, formatCell,
} from './FinanzplanSlide.helpers'

/* ── Tooltip for formula-linked labels ── */

function LabelWithTooltip({ label, de }: { label: string; de: boolean }) {
  const displayLabel = de ? label : (ROW_LABEL_MAP[label] ?? label)
  const tooltip = de ? FORMULA_TOOLTIPS[label] : (FORMULA_TOOLTIPS_EN[label] ?? FORMULA_TOOLTIPS[label])
  if (!tooltip) return <span>{displayLabel}</span>
  return (
    <span className="group relative cursor-help">
      {displayLabel}
      <span className="invisible group-hover:visible absolute left-0 top-full mt-1 z-50 bg-slate-800 border border-white/10 text-[9px] text-white/70 px-2 py-1 rounded shadow-lg whitespace-nowrap">
        {tooltip}
      </span>
    </span>
  )
}

/* ── GuV Annual Table (y2026-y2030) ── */

interface GuvTableProps {
  rows: SheetRow[]
  de: boolean
}

export function GuvTable({ rows, de }: GuvTableProps) {
  return (
    <table className="w-full text-[10px]">
      <thead>
        <tr className="border-b border-white/10">
          <th className="text-left py-1.5 px-2 text-white/60 font-medium sticky left-0 bg-slate-900/90 backdrop-blur min-w-[220px]">
            {de ? 'GuV-Position' : 'P&L Item'}
          </th>
          {[2026, 2027, 2028, 2029, 2030].map(y => (
            <th key={y} className="text-right py-1.5 px-3 text-white/60 font-medium min-w-[100px]">{y}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map(row => {
          const values = getValues(row)
          const label = getLabel(row)
          const isMajorSum = label === 'EBIT' || label.includes('Rohergebnis') || label.includes('Jahresüberschuss') || label.includes('Ergebnis nach Steuern')
          const isMinorSum = row.is_sum_row || label.includes('Summe') || label.includes('Gesamtleistung') || label.includes('Steuern gesamt')
          const isSumRow = isMajorSum || isMinorSum

          return (
            <tr key={row.id} className={`${isMajorSum ? 'border-t-2 border-t-white/20 border-b border-b-white/[0.05] bg-white/[0.05]' : isMinorSum ? 'border-t border-t-white/10 border-b border-b-white/[0.03] bg-white/[0.03]' : 'border-b border-white/[0.03]'} hover:bg-white/[0.02]`}>
              <td className={`py-1.5 px-2 sticky left-0 bg-slate-900/90 backdrop-blur ${isMajorSum ? 'font-bold text-white text-xs' : isMinorSum ? 'font-semibold text-white/80' : 'text-white/60'}`}>
                <LabelWithTooltip label={label} de={de} />
              </td>
              {[2026, 2027, 2028, 2029, 2030].map(y => {
                const v = values[`y${y}`] || 0
                return (
                  <td key={y} className={`text-right py-1.5 px-3 ${v < 0 ? 'text-red-400' : v > 0 ? (isMajorSum ? 'text-white' : isSumRow ? 'text-white/80' : 'text-white/50') : 'text-white/15'} ${isMajorSum ? 'font-bold text-xs' : isSumRow ? 'font-semibold' : ''}`}>
                    {v === 0 ? '—' : Math.round(v).toLocaleString('de-DE', { maximumFractionDigits: 0 })}
                  </td>
                )
              })}
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}

/* ── Monthly / Annual Grid (all sheets except GuV) ── */

interface MonthlyGridProps {
  rows: SheetRow[]
  activeSheet: string
  de: boolean
  yearOffset: number
  openCats: Set<string>
  toggleCat: (cat: string) => void
}

export function MonthlyGrid({ rows, activeSheet, de, yearOffset, openCats, toggleCat }: MonthlyGridProps) {
  const currentYear = 2026 + yearOffset
  const monthStart = yearOffset * 12 + 1
  const monthEnd = monthStart + 11

  /* ── Compute sum rows from detail rows (like Excel formulas) ── */
  const computeRows = (): SheetRow[] => {
    const computedRows = rows.map(row => {
      const label = getLabel(row)
      const cat = row.category as string || ''
      const isSumLabel = row.is_sum_row || label.includes('Summe') || label.includes('SUMME') || label.includes('ÜBERSCHUSS') || label.includes('UEBERSCHUSS')

      if (!isSumLabel) return row

      let sourceRows: SheetRow[] = []

      // === Betriebliche Aufwendungen: category-based sums ===
      if (cat && cat !== 'summe') {
        sourceRows = rows.filter(r => (r.category as string) === cat && !r.is_sum_row && getLabel(r) !== label)
      } else if (label.includes('Summe sonstige')) {
        sourceRows = rows.filter(r => {
          const rCat = r.category as string || ''
          const rLabel = getLabel(r)
          return !r.is_sum_row && rCat !== 'personal' && rCat !== 'abschreibungen' && rCat !== 'summe' &&
            !rLabel.includes('Personalkosten') && !rLabel.includes('Abschreibungen') && !rLabel.includes('Summe') && !rLabel.includes('SUMME')
        })
      } else if (label.includes('SUMME Betriebliche')) {
        sourceRows = rows.filter(r => {
          const rCat = r.category as string || ''
          const rLabel = getLabel(r)
          if (rLabel === 'Personalkosten' || rLabel === 'Abschreibungen') return true
          return !r.is_sum_row && rCat !== 'summe' && !rLabel.includes('Summe') && !rLabel.includes('SUMME')
        })
      }

      // === Liquidität: keep DB values (engine computed) ===
      else if (activeSheet === 'liquiditaet' && (
        label.includes('Summe') || label.includes('ÜBERSCHUSS') || label.includes('UEBERSCHUSS') ||
        label.includes('LIQUIDITÄT') || label.includes('LIQUIDITAET') || label.includes('Kontostand')
      )) {
        return row
      }

      // === Umsatzerlöse: GESAMTUMSATZ = sum of revenue rows only ===
      else if (label.includes('GESAMTUMSATZ')) {
        sourceRows = rows.filter(r => {
          const sec = (r as Record<string, unknown>).section as string || ''
          return sec === 'revenue' && !getLabel(r).includes('GESAMTUMSATZ')
        })
      }

      // === Materialaufwand: SUMME = sum of cost rows only ===
      else if (label.includes('SUMME Material') || (activeSheet === 'materialaufwand' && label === 'SUMME')) {
        sourceRows = rows.filter(r => {
          const sec = (r as Record<string, unknown>).section as string || ''
          return sec === 'cost' && getLabel(r) !== 'SUMME'
        })
      }

      // === Kunden GESAMT rows — trust DB values ===
      else if (label.includes('GESAMT') || label.includes('Bestandskunden gesamt')) {
        return row
      }

      if (sourceRows.length === 0) return row

      const computed: Record<string, number> = {}
      for (let m = 1; m <= 60; m++) {
        const key = `m${m}`
        computed[key] = Math.round(sourceRows.reduce((sum, r) => sum + (getValues(r)[key] || 0), 0))
      }

      return { ...row, values: computed, values_total: computed }
    })

    // For betriebliche: reorder so category header comes BEFORE detail rows
    if (activeSheet === 'betriebliche') {
      const grouped: SheetRow[] = []
      const cats = new Map<string, { header: SheetRow | null; details: SheetRow[] }>()
      for (const row of computedRows) {
        const cat = row.category as string || ''
        if (!cats.has(cat)) cats.set(cat, { header: null, details: [] })
        const g = cats.get(cat)!
        if (row.is_sum_row) g.header = row
        else g.details.push(row)
      }
      for (const [cat, g] of cats) {
        if (g.header) grouped.push(g.header)
        if (openCats.has(cat) || cat === 'summe' || cat === 'personal' || cat === 'abschreibungen') {
          grouped.push(...g.details)
        }
      }
      return grouped
    }
    return computedRows
  }

  const displayRows = computeRows()

  return (
    <table className="w-full text-[10px]">
      <thead>
        <tr className="border-b border-white/10">
          <th className="text-left py-1.5 px-2 text-white/60 font-medium sticky left-0 bg-slate-900/90 backdrop-blur min-w-[160px]">
            {de ? 'Position' : 'Item'}
          </th>
          {yearOffset === -1 ? (
            [2026, 2027, 2028, 2029, 2030].map(y => (
              <th key={y} className="text-right py-1.5 px-3 text-white/60 font-medium min-w-[80px]">{y}</th>
            ))
          ) : (
            <>
              <th className="text-right py-1.5 px-2 text-white/60 font-medium min-w-[70px]">
                {currentYear}
              </th>
              {(de ? MONTH_LABELS : MONTH_LABELS_EN).map((label, idx) => (
                <th key={idx} className="text-right py-1.5 px-1.5 text-white/50 font-normal min-w-[55px]">
                  {label}
                </th>
              ))}
            </>
          )}
        </tr>
      </thead>
      <tbody>
        {displayRows.map(row => {
          const values = getValues(row)
          const label = getLabel(row)
          const isSumRow = row.is_sum_row || label.includes('GESAMT') || label.includes('Summe') || label.includes('ÜBERSCHUSS') || label.includes('LIQUIDITÄT') || label.includes('UEBERSCHUSS') || label.includes('LIQUIDITAET')
          const isTotalRow = label.includes('GESAMT') || label.includes('Bestandskunden gesamt') || label.includes('GESAMTUMSATZ') || label.includes('SUMME')
          const isEditable = false // read-only for investors
          const cat = row.category as string || ''
          const isCatHeader = activeSheet === 'betriebliche' && row.is_sum_row && cat !== 'summe' && cat !== 'personal' && cat !== 'abschreibungen'
          const isCatOpen = openCats.has(cat)
          const section = (row as Record<string, unknown>).section as string || ''
          const isBalanceRow = label.includes('Kontostand') || label === 'LIQUIDITÄT' || label === 'LIQUIDITAET'
            || label.includes('Bestandskunden') || (activeSheet === 'kunden' && row.row_label === 'Bestandskunden')
            || label.includes('Anzahl Kunden') || section === 'quantity'
          const isUnitPrice = section === 'unit_cost' || section === 'einkauf' || label.includes('Einkaufspreis')
            || section === 'price' || label.includes('Preis/Monat')

          let annual = 0
          if (isUnitPrice) {
            annual = values[`m${monthEnd}`] || values[`m${monthStart}`] || 0
          } else if (isBalanceRow) {
            annual = values[`m${monthEnd}`] || 0
          } else {
            for (let m = monthStart; m <= monthEnd; m++) annual += values[`m${m}`] || 0
          }

          return (
            <tr
              key={row.id}
              className={`${isTotalRow ? 'border-t-2 border-t-white/20 border-b border-b-white/[0.03]' : 'border-b border-white/[0.03]'} ${isSumRow ? 'bg-white/[0.03]' : ''} hover:bg-white/[0.02]`}
            >
              <td className={`py-1 px-2 sticky left-0 bg-slate-900/90 backdrop-blur ${isSumRow ? 'font-bold text-white/80' : 'text-white/60'} ${isCatHeader ? 'cursor-pointer select-none' : ''}`}
                onClick={isCatHeader ? () => toggleCat(cat) : undefined}
              >
                <div className="flex items-center gap-1">
                  {isCatHeader && <span className="text-[10px] text-indigo-400 w-3 shrink-0">{isCatOpen ? '▾' : '▸'}</span>}
                  {isEditable && <span className="w-1 h-1 rounded-full bg-indigo-400 flex-shrink-0" />}
                  <span className="truncate"><LabelWithTooltip label={label} de={de} /></span>
                  {row.position && <span className="text-white/50 ml-1">({row.position})</span>}
                </div>
              </td>
              {yearOffset === -1 ? (
                [2026, 2027, 2028, 2029, 2030].map(y => {
                  const yStart = (y - 2026) * 12 + 1
                  const yEnd = yStart + 11
                  let yVal = 0
                  if (isUnitPrice) {
                    yVal = values[`m${yEnd}`] || 0
                  } else if (isBalanceRow) {
                    yVal = values[`m${yEnd}`] || 0
                  } else {
                    for (let m = yStart; m <= yEnd; m++) yVal += values[`m${m}`] || 0
                  }
                  return (
                    <td key={y} className={`text-right py-1 px-3 ${yVal < 0 ? 'text-red-400' : yVal > 0 ? (isSumRow ? 'text-white/80' : 'text-white/50') : 'text-white/15'} ${isSumRow ? 'font-bold' : ''}`}>
                      {formatCell(Math.round(yVal))}
                    </td>
                  )
                })
              ) : (
                <>
                  <td className={`text-right py-1 px-2 font-medium ${annual < 0 ? 'text-red-400' : isSumRow ? 'text-white/80' : 'text-white/50'}`}>
                    {formatCell(annual)}
                  </td>
                  {Array.from({ length: 12 }, (_, idx) => {
                    const mKey = `m${monthStart + idx}`
                    const v = values[mKey] || 0
                    return (
                      <td
                        key={idx}
                        className={`text-right py-1 px-1.5 ${
                          v < 0 ? 'text-red-400/70' : v > 0 ? (isSumRow ? 'text-white/70' : 'text-white/50') : 'text-white/15'
                        }`}
                      >
                        {formatCell(v)}
                      </td>
                    )
                  })}
                </>
              )}
            </tr>
          )
        })}
      </tbody>
      {/* Footer sum row for personalkosten, investitionen */}
      {['personalkosten', 'investitionen'].includes(activeSheet) && rows.length > 0 && (() => {
        const nonSumRows = rows.filter(r => {
          const l = getLabel(r)
          return !(r.is_sum_row || l.includes('GESAMT') || l.includes('Summe') || l.includes('Gesamtkosten') || l === 'SUMME')
        })
        return (
          <tfoot>
            <tr className="border-t-2 border-white/20 bg-white/[0.05]">
              <td className="py-1.5 px-2 sticky left-0 bg-slate-900/90 backdrop-blur font-bold text-white/80 text-xs">
                {de ? 'SUMME' : 'TOTAL'}
              </td>
              {yearOffset === -1 ? (
                [2026, 2027, 2028, 2029, 2030].map(y => {
                  const yStart = (y - 2026) * 12 + 1
                  const yEnd = yStart + 11
                  let yVal = 0
                  for (let m = yStart; m <= yEnd; m++) {
                    for (const row of nonSumRows) yVal += getValues(row)[`m${m}`] || 0
                  }
                  return (
                    <td key={y} className={`text-right py-1.5 px-3 font-bold text-xs ${yVal < 0 ? 'text-red-400' : 'text-white/80'}`}>
                      {formatCell(Math.round(yVal))}
                    </td>
                  )
                })
              ) : (
                <>
                  {(() => {
                    let sumAnnual = 0
                    for (let m = monthStart; m <= monthEnd; m++) {
                      for (const row of nonSumRows) sumAnnual += getValues(row)[`m${m}`] || 0
                    }
                    return (
                      <td className={`text-right py-1.5 px-2 font-bold text-xs ${sumAnnual < 0 ? 'text-red-400' : 'text-white/80'}`}>
                        {formatCell(sumAnnual)}
                      </td>
                    )
                  })()}
                  {Array.from({ length: 12 }, (_, idx) => {
                    const mKey = `m${monthStart + idx}`
                    let v = 0
                    for (const row of nonSumRows) v += getValues(row)[mKey] || 0
                    return (
                      <td key={idx} className={`text-right py-1.5 px-1.5 font-bold text-xs ${v < 0 ? 'text-red-400' : v > 0 ? 'text-white/70' : 'text-white/15'}`}>
                        {formatCell(v)}
                      </td>
                    )
                  })}
                </>
              )}
            </tr>
          </tfoot>
        )
      })()}
    </table>
  )
}
