'use client'

import { useState, useTransition } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { updateRolesAction } from '@/actions/settings'
import { debugProps } from '@/lib/debug'

const ALL_ROLES = [
  { value: 'PRODUCT_OWNER', label: 'Product Owner' },
  { value: 'SCRUM_MASTER', label: 'Scrum Master' },
  { value: 'DEVELOPER', label: 'Developer' },
]

interface RoleManagerProps {
  currentRoles: string[]
  isDemo: boolean
}

export function RoleManager({ currentRoles, isDemo }: RoleManagerProps) {
  const [selected, setSelected] = useState<Set<string>>(new Set(currentRoles))
  const [error, setError] = useState<string | null>(null)
  const [saved, setSaved] = useState(false)
  const [, startTransition] = useTransition()

  function toggle(role: string) {
    setSelected(prev => {
      const next = new Set(prev)
      if (next.has(role)) { next.delete(role) } else { next.add(role) }
      return next
    })
    setSaved(false)
    setError(null)
  }

  function handleSave() {
    if (selected.size === 0) {
      setError('Minimaal één rol is verplicht')
      return
    }
    startTransition(async () => {
      const result = await updateRolesAction([...selected])
      if (result.success) { setSaved(true); toast.success('Rollen opgeslagen') }
      else { setError(result.error ?? 'Opslaan mislukt'); toast.error(result.error ?? 'Opslaan mislukt') }
    })
  }

  return (
    <div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-4" {...debugProps('role-manager', 'RoleManager', 'components/settings/role-manager.tsx')}>
      <h2 className="text-sm font-medium text-foreground">Mijn rollen</h2>
      <div className="flex flex-wrap gap-3" data-debug-id="role-manager__roles">
        {ALL_ROLES.map(role => (
          <label key={role.value} className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={selected.has(role.value)}
              onChange={() => toggle(role.value)}
              disabled={isDemo}
              className="w-4 h-4 rounded accent-primary"
            />
            <span className="text-sm">{role.label}</span>
          </label>
        ))}
      </div>
      {error && <p className="text-xs text-error">{error}</p>}
      {saved && <p className="text-xs text-success">Rollen opgeslagen.</p>}
      <DemoTooltip show={isDemo}>
        <Button size="sm" onClick={handleSave} disabled={isDemo} data-debug-id="role-manager__add">Opslaan</Button>
      </DemoTooltip>
    </div>
  )
}
