'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, RefreshCw, Save } from 'lucide-react'

interface Assumption {
  id: string
  scenario_id: string
  key: string
  label_de: string
  label_en: string
  value: number | number[]
  value_type: 'scalar' | 'step' | 'timeseries'
  unit: string
  min_value: number | null
  max_value: number | null
  step_size: number | null
  category: string
  sort_order: number
}

interface Scenario {
  id: string
  name: string
  description: string
  is_default: boolean
  color: string
  assumptions: Assumption[]
}

export default function EditScenarioPage() {
  const { scenarioId } = useParams<{ scenarioId: string }>()
  const [scenario, setScenario] = useState<Scenario | null>(null)
  const [loading, setLoading] = useState(true)
  const [edits, setEdits] = useState<Record<string, string>>({})
  const [savingId, setSavingId] = useState<string | null>(null)
  const [recomputing, setRecomputing] = useState(false)
  const [toast, setToast] = useState<string | null>(null)

  function flashToast(msg: string) {
    setToast(msg)
    setTimeout(() => setToast(null), 3000)
  }

  async function load() {
    setLoading(true)
    const res = await fetch('/api/admin/fm/scenarios')
    if (res.ok) {
      const d = await res.json()
      const found = (d.scenarios as Scenario[]).find(s => s.id === scenarioId)
      setScenario(found || null)
    }
    setLoading(false)
  }

  useEffect(() => { if (scenarioId) load() }, [scenarioId])

  async function forceRecompute() {
    setRecomputing(true)
    const res = await fetch('/api/financial-model/compute', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ scenarioId, force: true }),
    })
    setRecomputing(false)
    flashToast(res.ok ? 'Recomputed successfully' : 'Recompute failed')
  }

  function setEdit(id: string, val: string) {
    setEdits(prev => ({ ...prev, [id]: val }))
  }

  async function saveAssumption(a: Assumption) {
    const raw = edits[a.id]
    if (raw === undefined) return
    let parsed: number | number[]
    try {
      parsed = a.value_type === 'timeseries' ? JSON.parse(raw) : Number(raw)
      if (a.value_type !== 'timeseries' && !Number.isFinite(parsed)) throw new Error('not a number')
    } catch {
      flashToast('Invalid value')
      return
    }

    setSavingId(a.id)
    const res = await fetch(`/api/admin/fm/assumptions/${a.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ value: parsed }),
    })
    setSavingId(null)
    if (res.ok) {
      flashToast('Saved')
      setEdits(prev => {
        const next = { ...prev }
        delete next[a.id]
        return next
      })
      load()
    } else {
      flashToast('Save failed')
    }
  }

  if (loading) return <div className="flex items-center justify-center h-64"><div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" /></div>
  if (!scenario) return <div className="text-rose-400">Scenario not found</div>

  // Group by category
  const byCategory: Record<string, Assumption[]> = {}
  scenario.assumptions.forEach(a => {
    if (!byCategory[a.category]) byCategory[a.category] = []
    byCategory[a.category].push(a)
  })

  return (
    <div className="space-y-6">
      <Link href="/pitch-admin/financial-model" className="inline-flex items-center gap-2 text-sm text-white/50 hover:text-white/80">
        <ArrowLeft className="w-4 h-4" /> Back to scenarios
      </Link>

      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <div className="w-4 h-4 rounded-full" style={{ backgroundColor: scenario.color }} />
            <h1 className="text-2xl font-semibold text-white">{scenario.name}</h1>
            {scenario.is_default && (
              <span className="text-[9px] px-1.5 py-0.5 rounded bg-indigo-500/20 text-indigo-300 uppercase font-semibold">
                Default
              </span>
            )}
          </div>
          {scenario.description && <p className="text-sm text-white/50">{scenario.description}</p>}
        </div>
        <button
          onClick={forceRecompute}
          disabled={recomputing}
          className="flex items-center gap-2 text-sm px-3 py-1.5 rounded-lg bg-white/[0.06] hover:bg-white/[0.1] text-white/70 hover:text-white disabled:opacity-40 disabled:cursor-wait transition-colors"
          title="Clear cache and recompute financial model results"
        >
          <RefreshCw className={`w-3.5 h-3.5 ${recomputing ? 'animate-spin' : ''}`} />
          {recomputing ? 'Computing…' : 'Force Recompute'}
        </button>
      </div>

      <div className="space-y-6">
        {Object.entries(byCategory).map(([cat, items]) => (
          <section key={cat} className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5">
            <h2 className="text-xs font-semibold uppercase tracking-wider text-white/50 mb-4">{cat}</h2>
            <div className="space-y-3">
              {items.map(a => {
                const isEdited = edits[a.id] !== undefined
                // Detect arrays of objects for structured editing
                const isObjectArray = Array.isArray(a.value) && a.value.length > 0 && typeof a.value[0] === 'object' && a.value[0] !== null

                if (isObjectArray) {
                  const rows = isEdited ? (JSON.parse(edits[a.id]) as Record<string, unknown>[]) : (a.value as unknown as Record<string, unknown>[])
                  const cols = Object.keys(rows[0] || {})

                  return (
                    <div key={a.id} className="border border-white/[0.06] rounded-xl overflow-hidden">
                      <div className="flex items-center justify-between px-4 py-2.5 bg-white/[0.02]">
                        <div>
                          <span className="text-sm text-white/90">{a.label_en || a.label_de}</span>
                          <span className="text-xs text-white/40 font-mono ml-2">{a.key}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => {
                              const newRow: Record<string, unknown> = {}
                              cols.forEach(c => { newRow[c] = typeof rows[0][c] === 'number' ? 0 : '' })
                              const updated = [...rows, newRow]
                              setEdit(a.id, JSON.stringify(updated))
                            }}
                            className="text-[10px] px-2 py-1 rounded bg-white/[0.06] text-white/60 hover:text-white hover:bg-white/[0.1]"
                          >
                            + Row
                          </button>
                          {isEdited && (
                            <button
                              onClick={() => saveAssumption(a)}
                              disabled={savingId === a.id}
                              className="bg-indigo-500 hover:bg-indigo-600 text-white text-[10px] px-2.5 py-1 rounded flex items-center gap-1 disabled:opacity-50"
                            >
                              <Save className="w-3 h-3" /> Save
                            </button>
                          )}
                        </div>
                      </div>
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="border-b border-white/[0.06]">
                            {cols.map(c => (
                              <th key={c} className="text-left py-2 px-3 text-white/40 font-medium uppercase tracking-wider">{c}</th>
                            ))}
                            <th className="w-8" />
                          </tr>
                        </thead>
                        <tbody>
                          {rows.map((row, ri) => (
                            <tr key={ri} className="border-b border-white/[0.04] hover:bg-white/[0.02]">
                              {cols.map(c => (
                                <td key={c} className="py-1.5 px-3">
                                  <input
                                    type={typeof row[c] === 'number' ? 'number' : 'text'}
                                    value={row[c] as string | number}
                                    onChange={e => {
                                      const updated = rows.map((r, i) => {
                                        if (i !== ri) return r
                                        const val = typeof r[c] === 'number' ? Number(e.target.value) || 0 : e.target.value
                                        return { ...r, [c]: val }
                                      })
                                      setEdit(a.id, JSON.stringify(updated))
                                    }}
                                    className="w-full bg-transparent border-b border-transparent hover:border-white/10 focus:border-indigo-500/50 text-white font-mono py-0.5 focus:outline-none"
                                  />
                                </td>
                              ))}
                              <td className="py-1.5 px-1">
                                <button
                                  onClick={() => {
                                    const updated = rows.filter((_, i) => i !== ri)
                                    setEdit(a.id, JSON.stringify(updated))
                                  }}
                                  className="text-white/30 hover:text-rose-400 p-1"
                                  title="Remove row"
                                >
                                  ×
                                </button>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )
                }

                const currentValue = isEdited
                  ? edits[a.id]
                  : typeof a.value === 'object'
                    ? JSON.stringify(a.value)
                    : String(a.value)

                return (
                  <div key={a.id} className="grid grid-cols-12 gap-3 items-center">
                    <div className="col-span-5 min-w-0">
                      <div className="text-sm text-white/90 truncate">{a.label_en || a.label_de}</div>
                      <div className="text-xs text-white/40 font-mono truncate">{a.key}</div>
                    </div>
                    <div className="col-span-4 flex items-center gap-2">
                      <input
                        type="text"
                        value={currentValue}
                        onChange={e => setEdit(a.id, e.target.value)}
                        className={`flex-1 bg-black/30 border rounded-lg px-3 py-1.5 text-sm text-white font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500/40 ${
                          isEdited ? 'border-amber-500/50' : 'border-white/10'
                        }`}
                      />
                      {a.unit && <span className="text-xs text-white/40">{a.unit}</span>}
                    </div>
                    <div className="col-span-2 text-xs text-white/30 font-mono">
                      {a.min_value !== null && a.max_value !== null ? `${a.min_value}–${a.max_value}` : ''}
                    </div>
                    <div className="col-span-1 flex justify-end">
                      {isEdited && (
                        <button
                          onClick={() => saveAssumption(a)}
                          disabled={savingId === a.id}
                          className="bg-indigo-500 hover:bg-indigo-600 text-white p-1.5 rounded-lg disabled:opacity-50"
                          title="Save"
                        >
                          <Save className="w-3.5 h-3.5" />
                        </button>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>
          </section>
        ))}
      </div>

      {toast && (
        <div className="fixed bottom-6 right-6 bg-indigo-500/20 border border-indigo-500/40 text-indigo-200 text-sm px-4 py-2 rounded-lg backdrop-blur-sm">
          {toast}
        </div>
      )}
    </div>
  )
}
