import React, { useState } from 'react';
import { MentionsInput, Mention } from 'react-mentions';
import { Button } from './ui/button';
import Loader from './common/loader';
import { Icons } from './icons';
import { useSearchParams } from 'next/navigation';
import enums from '@/utils/enums';
import apis from '@/utils/apis';

const UserMentionsInput = ({ setQuery, query, options, setMessage }: any) => {

    const searchParams = useSearchParams();
    const queryParams = Object.fromEntries(searchParams.entries());
    const [mentionedUsers, setMentionedUsers] = React.useState<any>([]);
    const [plainText, setPlainText] = React.useState('');
    const [value, setValue] = React.useState("");
    const [loading, setLoading] = useState(false)


    const extractMentionedUsers = (newValue: any) => {
        debugger
        const mentionRegex = /@\[(.*?)\]\((.*?)\)/g;
        const matches: any = [...newValue.matchAll(mentionRegex)];
        // const uniqueUsers = Array.from(
        //     new Set(
        //         matches.map((match: any) => ({
        //             id: match[2],
        //             name: match[1],
        //         }))
        //     )
        // );

        const uniqueUsers = Array.from(new Set(matches.map((match: any) => match[2])));
        setMentionedUsers(uniqueUsers);

        const plainTextWithoutMentions = newValue.replace(mentionRegex, '').replace(/\s+/g, ' ').trim();
        setPlainText(plainTextWithoutMentions);
    };


    const mentionStyle = {
        control: {
            backgroundColor: '#fff',
            fontSize: 14,
            fontWeight: 'normal',
        },
        input: {
            margin: 0,
            padding: '8px 12px',
            border: '1px solid #E5E7EB',
            borderRadius: '6px',
            minHeight: '100px',
        },
        suggestions: {
            list: {
                backgroundColor: 'white',
                border: '1px solid #E5E7EB',
                borderRadius: '6px',
                fontSize: 14,
                overflow: 'auto',
                maxHeight: '200px',
            },
            item: {
                padding: '8px 12px',
                borderBottom: '1px solid #E5E7EB',
                '&focused': {
                    backgroundColor: '#EFF6FF',
                },
            },
        },
        highlighter: {
            overflow: 'hidden',
        },
        mention: {
            backgroundColor: '#DBEAFE',
            color: '#2563EB',
            padding: '2px 4px',
            borderRadius: '4px',
        },
    };
    const handleChange = (event: any, newValue: string) => {
        setValue(newValue);
        extractMentionedUsers(newValue);
    };


    const handleAddMention = (id: any) => {
    };

    const handleSendMessage = async (msg: any) => {
        try {
            let payload: any = {
                message: msg,
                job_id: queryParams?.id,
                type: mentionedUsers?.length > 0 ? enums?.Chat?.MENTIONS : enums?.Chat?.NORMAL,
            };
            if (mentionedUsers?.length > 0) {
                payload["user_ids"] = mentionedUsers
            }
            setLoading(true)
            const apiRes = await apis.Chat.create(payload);
            setMessage((prevMessages: any) => [...prevMessages, apiRes]);
            // chatForm?.reset()
            setValue("")
        } catch (error) {
            console.log(error);
        } finally {
            setLoading(false)
        }
    };

    return (
        <div className="w-full">
            <div className="w-full flex gap-2">
                <MentionsInput
                    value={value}
                    onChange={(event, newValue) => handleChange(event, newValue)}
                    placeholder="Type a message..."
                    className="h-12 bg-white border-0 outline-none w-full shadow-none"
                    style={mentionStyle}
                >
                    <Mention
                        trigger="@"
                        data={options?.map((user: any) => ({
                            id: user._id,
                            display: user.full_name,
                            email: user.email,
                        }))}

                        onAdd={handleAddMention}
                        appendSpaceOnAdd={true}
                        displayTransform={(id, display) => `@${display}`}
                        renderSuggestion={(suggestion: any, search, highlightedDisplay) => (
                            <div className="flex flex-col">
                                <span className="font-medium">{highlightedDisplay}</span>
                                <span className="text-sm text-gray-500">{suggestion.email}</span>
                            </div>
                        )}
                        className="mention-container"
                    />
                </MentionsInput>
                <Button variant="default" disabled={loading} type="button" className="theme-background h-12" onClick={() => handleSendMessage(plainText)}>
                    <Loader loading={loading} />
                    <span>
                        <Icons.SendIcon />
                    </span>
                </Button>
            </div>

        </div>
    );
};

export default UserMentionsInput;
