import { notFound, redirect } from 'next/navigation'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { SessionData, sessionOptions } from '@/lib/session'
import { prisma } from '@/lib/prisma'
import { ProductForm } from '@/components/products/product-form'
import { ArchiveProductButton } from '@/components/products/archive-product-button'
import { TeamManager } from '@/components/products/team-manager'
import { updateProductFormAction } from '@/actions/products'
import { AutoPrToggle } from '@/components/products/auto-pr-toggle'
import { PrStrategySelect } from '@/components/products/pr-strategy-select'
import Link from 'next/link'

interface Props {
  params: Promise<{ id: string }>
}

export default async function ProductSettingsPage({ params }: Props) {
  const { id } = await params
  const session = await getIronSession<SessionData>(await cookies(), sessionOptions)

  if (session.isDemo) redirect(`/products/${id}`)

  const product = await prisma.product.findFirst({
    where: { id, user_id: session.userId },
    include: {
      members: {
        include: { user: { select: { id: true, username: true } } },
        orderBy: { created_at: 'asc' },
      },
    },
  })
  if (!product) notFound()

  const members = product.members.map(m => ({ id: m.user.id, username: m.user.username }))

  return (
    <div className="p-6 max-w-2xl mx-auto w-full">
      <div className="flex items-center gap-3 mb-6">
        <Link href={`/products/${id}`} className="text-muted-foreground hover:text-foreground text-sm">
          ← {product.name}
        </Link>
        <span className="text-muted-foreground">/</span>
        <h1 className="text-xl font-medium text-foreground">Instellingen</h1>
      </div>

      <ProductForm
        action={updateProductFormAction}
        submitLabel="Opslaan"
        defaultValues={{
          id: product.id,
          name: product.name,
          code: product.code,
          description: product.description ?? '',
          repo_url: product.repo_url ?? '',
          definition_of_done: product.definition_of_done,
        }}
      />

      <div className="mt-8 pt-6 border-t border-border space-y-3">
        <div>
          <h2 className="text-sm font-medium text-foreground">Agent-instellingen</h2>
          <p className="text-xs text-muted-foreground mt-0.5">
            Automatiseer acties na een succesvolle agent-job.
          </p>
        </div>
        <AutoPrToggle productId={id} initialValue={product.auto_pr} />
      </div>

      <div className="mt-8 pt-6 border-t border-border space-y-3">
        <div>
          <h2 className="text-sm font-medium text-foreground">PR-strategie</h2>
          <p className="text-xs text-muted-foreground mt-0.5">
            Bepaalt hoe de sprint zijn werk oplevert: één PR voor de hele sprint
            of een PR per story die automatisch wordt gemerged na groene CI.
          </p>
        </div>
        <PrStrategySelect productId={id} initialValue={product.pr_strategy} />
      </div>

      <div className="mt-8 pt-6 border-t border-border space-y-3">
        <div>
          <h2 className="text-sm font-medium text-foreground">Team</h2>
          <p className="text-xs text-muted-foreground mt-0.5">
            Voeg Developers toe die aan dit product mogen werken. Alleen gebruikers met de rol Developer kunnen worden toegevoegd.
          </p>
        </div>
        <TeamManager productId={id} members={members} />
      </div>

      <div className="mt-8 pt-6 border-t border-border">
        <h2 className="text-sm font-medium text-foreground mb-3">Gevaarlijke zone</h2>
        <div className="bg-error-container/30 border border-error/20 rounded-xl p-4 flex items-center justify-between gap-4">
          <div>
            <p className="text-sm font-medium text-foreground">Product archiveren</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              Het product wordt verborgen uit het dashboard. Je kunt het later herstellen.
            </p>
          </div>
          <ArchiveProductButton productId={id} />
        </div>
      </div>
    </div>
  )
}
