'use client'

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Send } from 'lucide-react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { debugProps } from '@/lib/debug'
import { createUserQuestionAction } from '@/actions/user-questions'

interface Props {
  ideaId: string
  isDemo?: boolean
}

export function UserChatInput({ ideaId, isDemo = false }: Props) {
  const router = useRouter()
  const [text, setText] = useState('')
  const [pending, startTransition] = useTransition()

  function submit() {
    const trimmed = text.trim()
    if (!trimmed) {
      toast.error('Vraag mag niet leeg zijn')
      return
    }
    startTransition(async () => {
      const r = await createUserQuestionAction(ideaId, trimmed)
      if ('error' in r) {
        toast.error(r.error)
        return
      }
      toast.success('Vraag verzonden — Claude gaat ermee aan de slag.')
      setText('')
      router.refresh()
    })
  }

  if (isDemo) {
    return (
      <div className="rounded-md border border-input bg-surface-container p-3" {...debugProps('user-chat-input', 'UserChatInput', 'components/ideas/user-chat-input.tsx')}>
        <p className="text-xs text-muted-foreground italic">
          Demo-modus: vragen stellen is niet beschikbaar.
        </p>
      </div>
    )
  }

  return (
    <div className="space-y-2 rounded-md border border-input bg-surface-container p-3" {...debugProps('user-chat-input', 'UserChatInput', 'components/ideas/user-chat-input.tsx')}>
      <label className="text-xs font-medium text-muted-foreground">
        Stel een vraag over dit plan
      </label>
      <Textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        rows={3}
        placeholder="Bijv. Waarom is gekozen voor X in plaats van Y?"
        disabled={pending}
        data-debug-id="user-chat-input__textarea"
      />
      <div className="flex justify-end">
        <Button
          size="sm"
          disabled={pending || !text.trim()}
          onClick={submit}
          data-debug-id="user-chat-input__submit"
        >
          <Send className="size-4" />
          {pending ? 'Bezig…' : 'Verzend'}
        </Button>
      </div>
    </div>
  )
}
