'use client'

import { useActionState, useState, useTransition } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { addProductMemberAction, removeProductMemberAction } from '@/actions/products'
import { debugProps } from '@/lib/debug'

interface Member {
  id: string
  username: string
}

interface TeamManagerProps {
  productId: string
  members: Member[]
}

export function TeamManager({ productId, members }: TeamManagerProps) {
  const [state, formAction, isPending] = useActionState(addProductMemberAction, null)
  const [removingId, setRemovingId] = useState<string | null>(null)
  const [, startTransition] = useTransition()

  function handleRemove(memberId: string) {
    setRemovingId(memberId)
    startTransition(async () => {
      await removeProductMemberAction(productId, memberId)
      setRemovingId(null)
    })
  }

  return (
    <div className="space-y-4" {...debugProps('team-manager', 'TeamManager', 'components/products/team-manager.tsx')}>
      {members.length === 0 ? (
        <p className="text-sm text-muted-foreground">Nog geen teamleden toegevoegd.</p>
      ) : (
        <ul className="space-y-2" data-debug-id="team-manager__members">
          {members.map(m => (
            <li key={m.id} className="flex items-center justify-between gap-3 rounded-lg bg-surface-container px-3 py-2">
              <span className="text-sm font-medium text-foreground">{m.username}</span>
              <Button
                variant="ghost"
                size="sm"
                className="text-error hover:bg-error/10 h-7 px-2 text-xs"
                disabled={removingId === m.id}
                onClick={() => handleRemove(m.id)}
              >
                {removingId === m.id ? 'Verwijderen…' : 'Verwijder'}
              </Button>
            </li>
          ))}
        </ul>
      )}

      <form action={formAction} className="flex gap-2" data-debug-id="team-manager__invite">
        <input type="hidden" name="productId" value={productId} />
        <Input
          name="username"
          placeholder="Gebruikersnaam van Developer"
          className="flex-1"
          disabled={isPending}
        />
        <Button type="submit" size="sm" disabled={isPending}>
          {isPending ? 'Toevoegen…' : 'Toevoegen'}
        </Button>
      </form>

      {state && 'error' in state && typeof state.error === 'string' && (
        <p className="text-xs text-error">{state.error}</p>
      )}
      {state && 'success' in state && (
        <p className="text-xs text-success">Teamlid toegevoegd.</p>
      )}
    </div>
  )
}
