'use client'
import type {FunctionComponent} from 'react'
import {useState} from 'react'
import Combobox from '@/components/custom/combobox'
import {useParams} from 'next/navigation'
import ActionButton from '@/components/custom/actionButton'
import type {Contact} from '@/generated/prisma/client'
import {linkTagsToContactsServerFunction} from '@/serverFunctions/tags'

interface TagContactFormProps {
  contacts: Contact[]
}

const TagContactForm: FunctionComponent<TagContactFormProps> = ({contacts}) => {
  const [contactId, setContactId] = useState<string | null>(null)
  const {tagId} = useParams<{tagId: string}>()

  return (
    <div className="flex gap-4">
      <Combobox
        data={[
          ...contacts.map(c => ({
            label: `${c.firstName} ${c.lastName ?? ''}`,
            value: c.id,
          })),
        ]}
        onValueChange={x => {
          if (x === 'new') {
            setContactId(null)
          } else {
            setContactId(x)
          }
        }}
        label="Choose a contact"
        placeholder="John Doe"
        noResultText="No contacts found"
      />
      <ActionButton
        className="grow"
        disabled={contactId === null}
        action={() => linkTagsToContactsServerFunction({contactIds: [contactId!], tagId})}
        pendingContent="Adding contact to tag...">
        Add contact to tag
      </ActionButton>
    </div>
  )
}

export default TagContactForm
