'use client'

// IdeaDetailLayout — top-level container voor /ideas/[id].
// Bevat: header (titel + status-badge + row-actions), tab-switcher
// (Idee/Grill/Plan/Timeline), en per-tab content.
//
// URL-based tabs (?tab=grill) — bookmarkable + refresh-safe.
// Md-editor (T-511), timeline (T-512), pbi-link-card (T-512) komen later.

import { useState, useTransition } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, ExternalLink } from 'lucide-react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { getIdeaStatusBadge } from '@/lib/idea-status-colors'
import type { IdeaStatusApi } from '@/lib/idea-status'
import { isIdeaEditable } from '@/lib/idea-status'
import type { IdeaDto } from '@/lib/idea-dto'
import { updateIdeaAction, archiveIdeaAction } from '@/actions/ideas'
import { IdeaRowActions } from '@/components/ideas/idea-row-actions'
import { IdeaMdEditor } from '@/components/ideas/idea-md-editor'
import { IdeaPbiLinkCard } from '@/components/ideas/idea-pbi-link-card'
import { IdeaTimeline } from '@/components/ideas/idea-timeline'
import { DownloadMdButton } from '@/components/ideas/download-md-button'

const API_TO_DB: Record<IdeaStatusApi, Parameters<typeof getIdeaStatusBadge>[0]> = {
  draft: 'DRAFT',
  grilling: 'GRILLING',
  grill_failed: 'GRILL_FAILED',
  grilled: 'GRILLED',
  planning: 'PLANNING',
  plan_failed: 'PLAN_FAILED',
  plan_ready: 'PLAN_READY',
  planned: 'PLANNED',
}

type TabKey = 'idee' | 'grill' | 'plan' | 'timeline'

const TABS: { key: TabKey; label: string }[] = [
  { key: 'idee', label: 'Idee' },
  { key: 'grill', label: 'Grill' },
  { key: 'plan', label: 'Plan' },
  { key: 'timeline', label: 'Chat & Timeline' },
]

interface IdeaLog {
  id: string
  type: string
  content: string
  metadata: unknown
  created_at: string
}

interface IdeaQuestion {
  id: string
  question: string
  options: string[] | null
  status: 'open' | 'answered' | 'cancelled' | 'expired'
  answer: string | null
  created_at: string
  expires_at: string
}

interface ProductOption {
  id: string
  name: string
  repo_url: string | null
}

export interface IdeaUserQuestionDto {
  id: string
  question: string
  answer: string | null
  status: 'pending' | 'answered'
  created_at: string
}

interface Props {
  idea: IdeaDto
  grill_md: string | null
  plan_md: string | null
  products: ProductOption[]
  logs: IdeaLog[]
  questions: IdeaQuestion[]
  userQuestions: IdeaUserQuestionDto[]
  isDemo: boolean
  initialTab: string
}

export function IdeaDetailLayout({
  idea,
  grill_md,
  plan_md,
  products,
  logs,
  questions,
  userQuestions,
  isDemo,
  initialTab,
}: Props) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [pending, startTransition] = useTransition()

  const tab = (TABS.some((t) => t.key === initialTab) ? initialTab : 'idee') as TabKey

  function setTab(key: TabKey) {
    const params = new URLSearchParams(searchParams.toString())
    params.set('tab', key)
    router.replace(`/ideas/${idea.id}?${params.toString()}`, { scroll: false })
  }

  function handleArchive() {
    if (isDemo) return
    if (!confirm('Idee archiveren?')) return
    startTransition(async () => {
      const r = await archiveIdeaAction(idea.id)
      if ('error' in r) {
        toast.error(r.error)
        return
      }
      toast.success('Idee gearchiveerd')
      router.push('/ideas')
    })
  }

  const badge = getIdeaStatusBadge(API_TO_DB[idea.status])

  return (
    <div className="p-6 max-w-5xl mx-auto w-full space-y-6">
      {/* Breadcrumb / back-link */}
      <Link
        href="/ideas"
        className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="size-4" />
        Alle ideeën
      </Link>

      {/* Header */}
      <header className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-1">
          <p className="font-mono text-xs text-muted-foreground">{idea.code}</p>
          <h1 className="text-2xl font-medium text-foreground">{idea.title}</h1>
          <div className="flex items-center gap-2">
            <span className={badge.classes + (badge.pulse ? ' animate-pulse' : '')}>
              {badge.label}
            </span>
            {idea.product ? (
              <Link
                href={`/products/${idea.product.id}`}
                className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
              >
                {idea.product.name}
                <ExternalLink className="size-3" />
              </Link>
            ) : (
              <span className="text-sm italic text-muted-foreground">geen product</span>
            )}
          </div>
        </div>
        <IdeaRowActions idea={idea} isDemo={isDemo} onArchive={handleArchive} />
      </header>

      {/* PBI-link card / Re-link banner bij PLANNED */}
      <IdeaPbiLinkCard idea={idea} isDemo={isDemo} />

      {/* Tab-switcher */}
      <nav className="border-b border-input flex gap-1">
        {TABS.map((t) => (
          <button
            key={t.key}
            type="button"
            onClick={() => setTab(t.key)}
            className={`px-4 py-2 text-sm border-b-2 transition-colors ${
              tab === t.key
                ? 'border-primary text-foreground'
                : 'border-transparent text-muted-foreground hover:text-foreground'
            }`}
          >
            {t.label}
            {t.key === 'timeline' && (logs.length > 0 || questions.length > 0) ? (
              <span className="ml-1.5 text-xs text-muted-foreground">
                ({logs.length + questions.length})
              </span>
            ) : null}
          </button>
        ))}
      </nav>

      {/* Tab content */}
      {tab === 'idee' && (
        <IdeaFormSection
          idea={idea}
          products={products}
          isDemo={isDemo}
          pending={pending}
        />
      )}
      {tab === 'grill' && (
        <MdSection
          kind="grill"
          markdown={grill_md}
          // M12 grill-keuze 12: grill_md editable in GRILLED + PLAN_READY.
          editable={
            !isDemo && (idea.status === 'grilled' || idea.status === 'plan_ready')
          }
          ideaId={idea.id}
        />
      )}
      {tab === 'plan' && (
        <MdSection
          kind="plan"
          markdown={plan_md}
          // M12 grill-keuze 12: plan_md editable alleen in PLAN_READY.
          editable={!isDemo && idea.status === 'plan_ready'}
          ideaId={idea.id}
        />
      )}
      {tab === 'timeline' && (
        <IdeaTimeline
          logs={logs}
          questions={questions}
          userQuestions={userQuestions}
          planMd={plan_md}
          ideaId={idea.id}
        />
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------
// Idee-tab: inline form (geen modal — de detailpagina IS de form).

interface FormProps {
  idea: IdeaDto
  products: ProductOption[]
  isDemo: boolean
  pending: boolean
}

function IdeaFormSection({ idea, products, isDemo, pending }: FormProps) {
  const router = useRouter()
  const editable =
    !isDemo &&
    isIdeaEditable(API_TO_DB[idea.status])
  const [title, setTitle] = useState(idea.title)
  const [description, setDescription] = useState(idea.description ?? '')
  const [productId, setProductId] = useState(idea.product_id ?? '')
  const [submitting, startSubmit] = useTransition()

  const dirty =
    title !== idea.title ||
    description !== (idea.description ?? '') ||
    productId !== (idea.product_id ?? '')

  function save() {
    startSubmit(async () => {
      const r = await updateIdeaAction(idea.id, {
        title,
        description: description || null,
        product_id: productId || null,
      })
      if ('error' in r) {
        toast.error(r.error)
        return
      }
      toast.success('Opgeslagen')
      router.refresh()
    })
  }

  return (
    <div className="space-y-4">
      <div className="space-y-1">
        <label className="text-xs font-medium text-muted-foreground">Titel</label>
        <Input
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          disabled={!editable || pending || submitting}
        />
      </div>
      <div className="space-y-1">
        <label className="text-xs font-medium text-muted-foreground">Beschrijving</label>
        <Textarea
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          rows={5}
          disabled={!editable || pending || submitting}
          placeholder="Korte beschrijving — wordt door Grill Me als startpunt gebruikt."
        />
      </div>
      <div className="space-y-1">
        <label className="text-xs font-medium text-muted-foreground">Product</label>
        <select
          value={productId}
          onChange={(e) => setProductId(e.target.value)}
          disabled={!editable || pending || submitting}
          className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
        >
          <option value="">Geen product</option>
          {products.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
              {p.repo_url ? '' : ' (geen repo — vereist voor Grill/Make Plan)'}
            </option>
          ))}
        </select>
      </div>

      {!editable && (
        <p className="text-xs text-muted-foreground italic">
          Idee is niet bewerkbaar in status {idea.status.toUpperCase()}.
        </p>
      )}

      {editable && (
        <div className="flex justify-end gap-2 pt-2">
          <Button
            variant="outline"
            size="sm"
            disabled={!dirty || submitting}
            onClick={() => {
              setTitle(idea.title)
              setDescription(idea.description ?? '')
              setProductId(idea.product_id ?? '')
            }}
          >
            Reset
          </Button>
          <Button size="sm" disabled={!dirty || submitting} onClick={save}>
            Opslaan
          </Button>
        </div>
      )}
    </div>
  )
}

// ---------------------------------------------------------------------------
// Grill / Plan tab — read-only render. T-511 voegt edit-mode toe.

interface MdProps {
  kind: 'grill' | 'plan'
  markdown: string | null
  editable: boolean
  ideaId: string
}

function MdSection({ kind, markdown, editable, ideaId }: MdProps) {
  const [editing, setEditing] = useState(false)

  if (editing) {
    return (
      <IdeaMdEditor
        ideaId={ideaId}
        kind={kind}
        initialValue={markdown ?? ''}
        onCancel={() => setEditing(false)}
      />
    )
  }

  if (!markdown) {
    return (
      <div className="space-y-3 py-6">
        <p className="text-sm text-muted-foreground text-center italic">
          {kind === 'grill'
            ? 'Nog geen grill-resultaat. Klik "Grill" in de header om te starten.'
            : 'Nog geen plan. Voltooi eerst de grill-fase en klik dan "Plan".'}
        </p>
        {editable && (
          <div className="flex justify-center">
            <Button size="sm" variant="outline" onClick={() => setEditing(true)}>
              Schrijf zelf
            </Button>
          </div>
        )}
      </div>
    )
  }

  return (
    <div className="space-y-3">
      <div className="flex justify-end gap-2">
        <DownloadMdButton ideaId={ideaId} kind={kind} hasContent={markdown !== null} />
        {editable && (
          <Button size="sm" variant="outline" onClick={() => setEditing(true)}>
            Bewerk
          </Button>
        )}
      </div>
      <pre className="rounded-md border border-input bg-surface-container p-4 text-sm whitespace-pre-wrap font-mono leading-relaxed overflow-x-auto">
        {markdown}
      </pre>
    </div>
  )
}
