'use client'

import { useState, useTransition } from 'react'
import { toast } from 'sonner'
import type { PrStrategy } from '@prisma/client'
import { updatePrStrategyAction } from '@/actions/products'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from '@/components/ui/select'
import { debugProps } from '@/lib/debug'

interface PrStrategySelectProps {
  productId: string
  initialValue: PrStrategy
}

const STRATEGY_LABELS: Record<PrStrategy, string> = {
  SPRINT:
    'Per sprint — één PR voor de hele sprint, klaar voor review aan eind. Per task een eigen claude-sessie.',
  STORY:
    'Per story — auto-merge na CI groen, één PR per story. Per task een eigen claude-sessie.',
  SPRINT_BATCH:
    'Sprint batch — één claude-sessie voor de hele sprint, sneller en behoudt context. Vereist alle tasks in de product-hoofdrepo.',
}

const VALID_VALUES: ReadonlyArray<PrStrategy> = ['SPRINT', 'STORY', 'SPRINT_BATCH']

export function PrStrategySelect({ productId, initialValue }: PrStrategySelectProps) {
  const [value, setValue] = useState<PrStrategy>(initialValue)
  const [isPending, startTransition] = useTransition()

  function handleChange(next: string | null) {
    if (!next || !VALID_VALUES.includes(next as PrStrategy)) return
    if (next === value) return
    const previous = value
    setValue(next as PrStrategy)
    startTransition(async () => {
      const result = await updatePrStrategyAction(productId, next as PrStrategy)
      if ('error' in result && result.error) {
        setValue(previous)
        toast.error(typeof result.error === 'string' ? result.error : 'Opslaan mislukt')
      }
    })
  }

  return (
    <div className="flex flex-col gap-2" {...debugProps('pr-strategy-select', 'PrStrategySelect', 'components/products/pr-strategy-select.tsx')}>
      <Select value={value} onValueChange={handleChange} disabled={isPending}>
        <SelectTrigger className="w-full max-w-xl" data-debug-id="pr-strategy-select__trigger">
          {STRATEGY_LABELS[value]}
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="SPRINT">{STRATEGY_LABELS.SPRINT}</SelectItem>
          <SelectItem value="STORY">{STRATEGY_LABELS.STORY}</SelectItem>
          <SelectItem value="SPRINT_BATCH">{STRATEGY_LABELS.SPRINT_BATCH}</SelectItem>
        </SelectContent>
      </Select>
    </div>
  )
}
