'use client'

import { useState } from 'react'
import moment from 'moment'
import CustomTableHead from '@/Component/Common/Tables/CustomTableHead'
import TableHoc from '@/Utils/HOC/TableHoc'
import NoDataTable from '@/Component/Common/Tables/NoData/NoDataTable'
import ImageWithFallback from '@/Component/Common/ImageWithFallback'
import Modal from '@/Component/Common/Modal'

const MESSAGE_PREVIEW_LIMIT = 20

const formatLabel = (value: string) => {
    if (!value) return '-'
    return value.replace(/_/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase())
}

const stripHtmlTags = (content: string) => content?.replace(/<[^>]*>/g, '') ?? ''

const formatMessageContent = (content: string, isAutoReply?: boolean) => {
    if (!content) return '-'
    if (isAutoReply || content.includes('_')) {
        return formatLabel(content)
    }
    return content
}

const DirectionTag = ({ direction }: { direction: string }) => {
    const isOutbound = direction?.toLowerCase() === 'outbound'

    return (
        <span
            className={`inline-flex items-center gap-1.5 text-xs font-semibold py-1.5 px-3 rounded-full whitespace-nowrap ${isOutbound
                ? 'bg-emerald-500/15 text-emerald-600 ring-1 ring-emerald-500/20'
                : 'bg-sky-500/15 text-sky-600 ring-1 ring-sky-500/20'
                }`}
        >
            {isOutbound ? (
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M7 17L17 7M17 7H9M17 7V15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
            ) : (
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M17 7L7 17M7 17H15M7 17V9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
            )}
            {isOutbound ? 'Sent' : 'Received'}
        </span>
    )
}

const MessageTypeTag = ({ messageType }: { messageType: string }) => {
    const normalizedType = messageType?.toLowerCase()

    const typeStyles: Record<string, string> = {
        webhook: 'bg-violet-500/15 text-violet-600 ring-violet-500/20',
        auto_reply: 'bg-amber-500/15 text-amber-600 ring-amber-500/20',
        inbound: 'bg-indigo-500/15 text-indigo-600 ring-indigo-500/20',
    }

    const style = typeStyles[normalizedType] ?? 'bg-neutral-500/10 text-neutral-600 ring-neutral-500/20'

    return (
        <span className={`inline-flex items-center gap-1 text-xs font-medium py-1.5 px-3 rounded-full capitalize ring-1 whitespace-nowrap ${style}`}>
            {formatLabel(messageType)}
        </span>
    )
}

const MessageCell = ({ content, isAutoReply }: { content: string; isAutoReply?: boolean }) => {
    const [open, setOpen] = useState(false)
    const formatted = formatMessageContent(content, isAutoReply)
    const plainText = stripHtmlTags(formatted)
    const isLong = plainText.length > MESSAGE_PREVIEW_LIMIT

    return (
        <>
            <p className="text-neutral-700 leading-relaxed" title={plainText}>
                {isLong ? (
                    <>
                        {`${plainText.slice(0, MESSAGE_PREVIEW_LIMIT).trim()}... `}
                        <button
                            type="button"
                            onClick={() => setOpen(true)}
                            className="text-primary font-medium hover:underline whitespace-nowrap"
                        >
                            Read more
                        </button>
                    </>
                ) : (
                    <span dangerouslySetInnerHTML={{ __html: formatted }} />
                )}
            </p>
            {open && (
                <Modal setModal={setOpen} modalSize="md:w-2/4 lg:w-2/5" headerTitle="Message">
                    <div
                        className="text-neutral-700 leading-relaxed whitespace-pre-wrap break-words max-h-[60vh] overflow-y-auto"
                        dangerouslySetInnerHTML={{ __html: formatted }}
                    />
                </Modal>
            )}
        </>
    )
}

const WhatsAppMessagesTable = (props) => {
    const { apiData } = props
    const messagesData = apiData?.data?.data

    const tableHeadData = {
        head: [
            { title: 'Sr No.', sorting: false },
            { title: 'User', sorting: false },
            { title: 'Phone Number', apiKey: 'phone_number', sorting: true },
            { title: 'Direction', apiKey: 'direction', sorting: true },
            { title: 'Message', apiKey: 'message_content', sorting: false },
            { title: 'Message Type', apiKey: 'message_type', sorting: true },
            { title: 'Created At', apiKey: 'created_at', sorting: true },
        ],
    }

    const getUserName = (user) => {
        const fullName = [user?.first_name, user?.last_name].filter(Boolean).join(' ').trim()
        return fullName || user?.display_name || user?.customer_name || '-'
    }

    return (
        <table className="w-full text-sm text-left rtl:text-right">
            <CustomTableHead tableHeadData={tableHeadData} params={apiData?.params} setParams={apiData?.setParams} />
            <tbody>
                {
                    messagesData?.length > 0
                        ? messagesData?.map((message, index) => (
                            <tr className="border-b border-lightGray last:border-none font-normal hover:bg-lightGray/20 align-middle" key={message?.id ?? index}>
                                <td className="px-5 py-2.5">
                                    {((apiData?.params.page - 1) * apiData?.params.per_page) + 1 + index}
                                </td>
                                <td className="px-5 py-2.5">
                                    <div className="flex items-center gap-3 min-w-[180px]">
                                        <div className="w-10 h-10 relative rounded-full overflow-hidden bg-neutral-100 ring-2 ring-white shadow-sm shrink-0">
                                            <ImageWithFallback
                                                src={message?.user?.image}
                                                alt={getUserName(message?.user)}
                                                className="absolute w-full h-full object-cover left-0 right-0 top-0 bottom-0"
                                                height={40}
                                                width={40}
                                            />
                                        </div>
                                        <div className="flex flex-col gap-0.5">
                                            <span className="font-medium text-neutral-900 capitalize whitespace-nowrap">
                                                {getUserName(message?.user)}
                                            </span>
                                            <span className="text-[11px] font-medium capitalize text-neutral-500 w-fit">
                                                {message?.user?.role && (message?.user.role)}
                                            </span>
                                        </div>
                                    </div>
                                </td>
                                <td className="px-5 py-2.5">
                                    {message?.phone_number}
                                </td>
                                <td className="px-5 py-2.5">
                                    <DirectionTag direction={message?.direction} />
                                </td>
                                <td className="px-5 py-2.5 min-w-[200px]">
                                    <MessageCell content={message?.message_content} isAutoReply={message?.is_auto_reply} />
                                </td>
                                <td className="px-5 py-2.5">
                                    <MessageTypeTag messageType={message?.message_type} />
                                </td>
                                <td className="px-5 py-2.5 whitespace-nowrap text-neutral-600">
                                    {message?.created_at
                                        ? moment.utc(message.created_at).local().format('DD MMM YYYY, h:mm A')
                                        : '-'}
                                </td>
                            </tr>
                        ))
                        : <NoDataTable colSpan={7} />
                }
            </tbody>
        </table>
    )
}

export default TableHoc(WhatsAppMessagesTable)
