'use client'

import React, { useMemo } from 'react'
import Markdown from 'react-markdown'
import { twMerge } from 'tailwind-merge'
import * as R from 'ramda'


type IMessage = {
  type: 'md' | 'custom';
  role: 'user' | 'assistant';
  content: string;
  isLoading?: boolean;
  isError?: boolean;
  error?: string;
}
type IMessages = IMessage[]

const Chater = ({ messages, node, onAccept }: { messages: IMessages }) => {
  const reversedMessages = useMemo(() => {
    return R.reverse(messages)
  }, [messages])


  return (
    <div className="flex flex-col-reverse w-full overflow-auto pb-[80px]">
      {
        reversedMessages.map((message, i) => (
          <div key={i} className={twMerge("chat ", message.role === 'assistant' ? "chat-start" : 'chat-end')}>
            <div className="chat-image avatar placeholder">
              <div className="w-10 rounded-full bg-neutral text-neutral-content">
                {message.role === 'assistant'
                  ? (
                    <img
                      alt="avatar"
                      src="https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.webp" />
                  )
                  : <span className="text-xl">我</span>}
              </div>
            </div>
            <div className={twMerge("chat-bubble prose prose-sm", message.role === 'assistant' ? "chat-bubble-primary" : "chat-bubble-secondary")}>
              <Markdown>
                {message?.content}
              </Markdown>
              {
                (node.type === 'UserTask' && message.role === 'assistant')
                  ? message?.isLoading
                    ? <span className="loading loading-dots loading-sm"></span>
                    : (
                      <>
                        <button className="btn btn-xs btn-neutral" onClick={() => onAccept?.(message)}>采纳</button>
                      </>
                    )
                  : null
              }
            </div>
          </div>
        ))
      }
    </div>
  )
}

export default React.memo(Chater)