---
import { isInputError } from 'astro:actions'

import { SUGGESTION_MESSAGE_CONTENT_MAX_LENGTH } from '../actions/serviceSuggestion'
import Button from '../components/Button.astro'
import Tooltip from '../components/Tooltip.astro'
import { cn } from '../lib/cn'
import { baseInputClassNames } from '../lib/formInputs'

import ChatMessages, { type ChatMessage } from './ChatMessages.astro'

import type { ActionInputNoFormData, AnyAction } from '../lib/astroActions'
import type { HTMLAttributes } from 'astro/types'

export type Props<TAction extends AnyAction | undefined = AnyAction | undefined> =
  HTMLAttributes<'section'> & {
    messages: ChatMessage[]
    title?: string
    userId: number | null
    action: TAction
    formData?: TAction extends AnyAction
      ? ActionInputNoFormData<TAction> extends Record<string, unknown>
        ? Omit<ActionInputNoFormData<TAction>, 'content'>
        : ActionInputNoFormData<TAction>
      : undefined
  }

const { messages, title, userId, action, formData, class: className, ...htmlProps } = Astro.props

const result = action ? Astro.getActionResult(action) : undefined
const inputErrors = isInputError(result?.error) ? result.error.fields : {}
---

<div class={cn(className)} {...htmlProps}>
  {!!title && <h3 class="text-day-200 font-title mb-2 text-center text-xl font-bold">{title}</h3>}

  <ChatMessages
    id="chat-messages"
    messages={messages}
    userId={userId}
    hx-trigger="every 10s"
    hx-get={Astro.url.pathname}
    hx-target="#chat-messages"
    hx-select="#chat-messages>*"
  />

  {
    !!action && (
      <>
        <form
          method="POST"
          action={action}
          class="flex items-end gap-2"
          hx-post={`${Astro.url.pathname}${action}`}
          hx-target="#chat-messages"
          hx-select="#chat-messages>*"
          hx-push-url="true"
          {...{ 'hx-on::after-request': 'if(event.detail.successful) this.reset()' }}
        >
          {typeof formData === 'object' &&
            formData !== null &&
            Object.entries(formData).map(([key, value]) => (
              <input type="hidden" name={key} value={String(value)} />
            ))}
          <textarea
            name="content"
            placeholder="Add a message..."
            class={cn(
              baseInputClassNames.input,
              baseInputClassNames.textarea,
              'max-h-64',
              !!inputErrors.content && baseInputClassNames.error
            )}
            required
            maxlength={SUGGESTION_MESSAGE_CONTENT_MAX_LENGTH}
          />

          <Tooltip text="Send">
            <Button type="submit" icon="ri:send-plane-fill" size="lg" color="success" class="h-16" />
          </Tooltip>
        </form>
        {!!inputErrors.content && <div class="text-sm text-red-500">{inputErrors.content}</div>}
      </>
    )
  }
</div>
