'use client'

import { useState, useTransition } from 'react'
import { cn } from '@/lib/utils'
import { updateAutoPrAction } from '@/actions/products'
import { toast } from 'sonner'

interface AutoPrToggleProps {
  productId: string
  initialValue: boolean
}

export function AutoPrToggle({ productId, initialValue }: AutoPrToggleProps) {
  const [enabled, setEnabled] = useState(initialValue)
  const [isPending, startTransition] = useTransition()

  function handleToggle() {
    const newValue = !enabled
    setEnabled(newValue)
    startTransition(async () => {
      const result = await updateAutoPrAction(productId, newValue)
      if (result.error) {
        setEnabled(!newValue)
        toast.error(typeof result.error === 'string' ? result.error : 'Opslaan mislukt')
      }
    })
  }

  return (
    <div className="flex items-center gap-3">
      <button
        type="button"
        role="switch"
        aria-checked={enabled}
        onClick={handleToggle}
        disabled={isPending}
        className={cn(
          'relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent',
          'transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
          'disabled:cursor-not-allowed disabled:opacity-50',
          enabled ? 'bg-primary' : 'bg-input',
        )}
      >
        <span
          className={cn(
            'pointer-events-none inline-block h-4 w-4 rounded-full bg-background shadow-sm',
            'transition-transform duration-200',
            enabled ? 'translate-x-4' : 'translate-x-0',
          )}
        />
      </button>
      <span className="text-sm text-foreground">Automatisch PR aanmaken na succesvolle agent-job</span>
    </div>
  )
}
