import {createPortal, useEffect, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Input from "../../../../../../fields/input";
// import Textarea from "../../../../../fields/textarea";
// import Button from "../../../../../button/_";
import {isChatbotInitiallyClosed} from "../../../../../../popups/container";
import SectionHeader from "../../../../../../sections/section-header";
import {getFormatedDate} from "../../../../../../../../helpers";
import Tooltip from "../../../../../../fields/tooltip";

export default function Drawer({
                                   lead,
                                   allColumns = [],
                                   isOpen,
                                   onClose,
                                   onSaveEdit,
                                   onDelete
                               }) {
    const [isEditMode, setIsEditMode] = useState(false);
    const [editedData, setEditedData] = useState({});
    const [newNote, setNewNote] = useState('');

    const initiallyClosedRef = useRef(isChatbotInitiallyClosed());

    useEffect(() => {
        if (isOpen) {
            initiallyClosedRef.current = isChatbotInitiallyClosed();
            LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', false);
        } else {
            if (!initiallyClosedRef.current) {
                LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', true);
            }
        }

        return () => {
            if (!initiallyClosedRef.current) {
                LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', true);
            }
        }
    }, [isOpen]);

    const handleClose = () => {
        setIsEditMode(false);
        setEditedData({});
        setNewNote('');
        onClose();
    };

    /*const handleEdit = () => {
        setIsEditMode(true);
        // Build editedData from lead_values
        const data = {};
        lead?.lead_values?.forEach(lv => {
            data[lv.lead_field.field_key] = lv.value;
        });
        setEditedData(data);
    };

    const handleCancelEdit = () => {
        setIsEditMode(false);
        setEditedData({});
    };

    const handleSave = () => {
        onSaveEdit(editedData);
        setIsEditMode(false);
    };

    const handleAddNote = () => {
        if (!newNote.trim()) return;
        const note = {
            id: Date.now(),
            content: newNote,
            timestamp: new Date().toISOString(),
            author: 'Current User' // TODO: Get actual user
        };
        // TODO: Implement add note API call
        setNewNote('');
    };*/

    if (!isOpen || !lead) {
        return null;
    }

    const domNode = document.getElementById('lbaic-settings-drawer-layout');
    if (!domNode) {
        return null;
    }

    // Get lead field value by field_key
    const getLeadValue = (fieldKey) => {
        const field = lead.lead_values?.find(lv => lv.lead_field.field_key === fieldKey);
        return field?.value || '';
    };

    // Filter columns to show only dynamic lead fields (exclude fixed columns)
    const leadFieldColumns = allColumns.filter(col => !col.fixed && !col.alwaysVisible);

    // Get name and email for header
    const nameField = lead.lead_values?.find(lv =>
        lv.lead_field.field_key === 'full_name' ||
        lv.lead_field.field_key === 'name' ||
        lv.lead_field.label?.toLowerCase().includes('name')
    );
    const emailField = lead.lead_values?.find(lv =>
        lv.lead_field.field_key === 'email' ||
        lv.lead_field.data_type === 'email'
    );

    return createPortal(
        <div className="lbaic-settings-leads-drawer">
            <div className="lbaic-settings-leads-drawer-overlay" onClick={handleClose}></div>
            <div className="lbaic-settings-leads-drawer-content">
                {/* Header */}
                <div className="lbaic-settings-leads-drawer-header">
                    <SectionHeader
                        title={nameField?.value || __("Lead", 'limb-chatbot')}
                        description={emailField?.value || ''}
                    />
                    <button
                        onClick={handleClose}
                        className="lbaic-settings-leads-drawer-header-close"
                    >
                        <svg className="lbaic-settings-leads-drawer-header-close-icon"
                             xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <use href="#lbaic-settings-close"/>
                        </svg>
                    </button>
                </div>

                {/* Content - Scrollable */}
                <div className="lbaic-settings-leads-drawer-body">
                    <div className="lbaic-settings-leads-drawer-body-in">
                        {/* Quick Actions */}
                        {/*<div className="lbaic-settings-leads-drawer-actions">
                            {!isEditMode ? (
                                <Button
                                    type="secondary"
                                    label={__("Edit", 'limb-chatbot')}
                                    icon="edit"
                                    onClick={handleEdit}
                                />
                            ) : (
                                <>
                                    <Button
                                        type="primary"
                                        label={__("Save", 'limb-chatbot')}
                                        onClick={handleSave}
                                    />
                                    <Button
                                        type="secondary"
                                        label={__("Cancel", 'limb-chatbot')}
                                        onClick={handleCancelEdit}
                                    />
                                </>
                            )}
                            <Button
                                type="danger"
                                label={__("Delete", 'limb-chatbot')}
                                icon="delete"
                                onClick={onDelete}
                                className="lbaic-settings-leads-drawer-actions-delete"
                            />
                        </div>*/}

                        {/* Lead Information Card */}
                        <div className="lbaic-settings-leads-drawer-card">
                            <h3 className="lbaic-settings-leads-drawer-card-title">
                                {__("Lead Information", 'limb-chatbot')}
                            </h3>

                            {leadFieldColumns.map((column) => {
                                const value = getLeadValue(column.id);

                                if (!value) {
                                    return null;
                                }

                                return (
                                    <div key={column.id} className="lbaic-settings-leads-drawer-card-row">
                                        <div className="lbaic-settings-leads-drawer-card-row-label">
                                            <span>{column.label}</span>
                                        </div>
                                        <div className="lbaic-settings-leads-drawer-card-row-value">
                                            {isEditMode ? (
                                                <Input
                                                    value={editedData[column.id] || ''}
                                                    setValue={(val) => setEditedData({...editedData, [column.id]: val})}
                                                />
                                            ) : (
                                                <Tooltip
                                                    contentClassName='lbaic-settings-leads-drawer-copy-tooltip-content'
                                                    copyText={value}
                                                >
                                                    <span>{value}</span>
                                                </Tooltip>
                                            )}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>

                        {/* Source Details */}
                        <div className="lbaic-settings-leads-drawer-card">
                            <h3 className="lbaic-settings-leads-drawer-card-title">
                                {__("Source", 'limb-chatbot')}
                            </h3>
                            <div className="lbaic-settings-leads-drawer-source">
                                <div className="lbaic-settings-leads-drawer-source-item">
                                    <svg className="lbaic-settings-leads-drawer-source-icon"
                                         xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                        <use href="#lbaic-settings-join-chat"/>
                                    </svg>
                                    <span className="lbaic-settings-leads-drawer-source-label">
                                        {__("Chatbot:", 'limb-chatbot')}
                                    </span>
                                    <span className="lbaic-settings-leads-drawer-source-value">
                                        {lead.chatbot_uuid || __("Default", 'limb-chatbot')}
                                    </span>
                                </div>
                                <div className="lbaic-settings-leads-drawer-source-item">
                                    <svg
                                        className="lbaic-settings-leads-drawer-source-icon"
                                        xmlns="http://www.w3.org/2000/svg"
                                        fill="none"
                                        viewBox="0 0 24 24"
                                    >
                                        <use
                                            href={`#lbaic-settings-${lead.source_type === 'widget' ? 'puzzle' : 'briefcase'}`}/>
                                    </svg>
                                    <span className="lbaic-settings-leads-drawer-source-label">
                                        {lead.source_type === 'action' ? __("Action", 'limb-chatbot') : __("Widget", 'limb-chatbot')}:
                                    </span>
                                    <span className="lbaic-settings-leads-drawer-source-value">
                                        {lead.source_title || __("N/A", 'limb-chatbot')}
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Conversation Transcript */}
                        {/*<div className="lbaic-settings-leads-drawer-section">
                            <h3 className="lbaic-settings-leads-drawer-section-title">
                                {__("Conversation History", 'limb-chatbot')}
                            </h3>
                            {lead.conversation && lead.conversation.length > 0 ? (
                                <div className="lbaic-settings-leads-drawer-conversation">
                                    {lead.conversation.map((message) => (
                                        <div
                                            key={message.id}
                                            className={`lbaic-settings-leads-drawer-conversation-message ${
                                                message.role === 'user' ? 'lbaic-settings-leads-drawer-conversation-message-user' : ''
                                            }`}
                                        >
                                            <div className={`lbaic-settings-leads-drawer-conversation-message-bubble ${
                                                message.role === 'user' ? 'lbaic-settings-leads-drawer-conversation-message-bubble-user' : ''
                                            }`}>
                                                <p className="lbaic-settings-leads-drawer-conversation-message-content">
                                                    {message.content}
                                                </p>
                                                <p className={`lbaic-settings-leads-drawer-conversation-message-time ${
                                                    message.role === 'user' ? 'lbaic-settings-leads-drawer-conversation-message-time-user' : ''
                                                }`}>
                                                    {getFormatedDate(message.timestamp)}
                                                </p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <p className="lbaic-settings-leads-drawer-notes-empty">
                                    {__("No conversation history", 'limb-chatbot')}
                                </p>
                            )}
                        </div>*/}

                        {/* Activity Timeline */}
                        <div className="lbaic-settings-leads-drawer-section">
                            <h3 className="lbaic-settings-leads-drawer-section-title">
                                {__("Activity Timeline", 'limb-chatbot')}
                            </h3>
                            <div className="lbaic-settings-leads-drawer-timeline">
                                <div className="lbaic-settings-leads-drawer-timeline-item">
                                    <div
                                        className="lbaic-settings-leads-drawer-timeline-icon lbaic-settings-leads-drawer-timeline-icon-active">
                                        <svg className="lbaic-settings-leads-drawer-timeline-icon-svg"
                                             xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                            <use href="#lbaic-settings-schedule"/>
                                        </svg>
                                    </div>
                                    <div className="lbaic-settings-leads-drawer-timeline-content">
                                        <p className="lbaic-settings-leads-drawer-timeline-description">
                                            {__("Lead captured", 'limb-chatbot')}
                                        </p>
                                        <p className="lbaic-settings-leads-drawer-timeline-time">
                                            {getFormatedDate(lead.created_at)}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Notes Section */}
                        {/*<div className="lbaic-settings-leads-drawer-section">
                            <h3 className="lbaic-settings-leads-drawer-section-title">
                                {__("Notes", 'limb-chatbot')}
                            </h3>

                             Add Note
                            <div className="lbaic-settings-leads-drawer-notes-add">
                                <Textarea
                                    value={newNote}
                                    setValue={setNewNote}
                                    staticPlaceholder={__("Add a note...", 'limb-chatbot')}
                                />
                                <Button
                                    type="primary"
                                    label={__("Add Note", 'limb-chatbot')}
                                    onClick={handleAddNote}
                                    disabled={!newNote.trim()}
                                />
                            </div>

                             Notes List
                            <div className="lbaic-settings-leads-drawer-notes-list">
                                {lead.notes.slice().reverse().map((note) => (
                                    <div key={note.id} className="lbaic-settings-leads-drawer-notes-item">
                                        <p className="lbaic-settings-leads-drawer-notes-item-content">
                                            {note.content}
                                        </p>
                                        <p className="lbaic-settings-leads-drawer-notes-item-meta">
                                            {formatTimestamp(note.timestamp)} • {note.author}
                                        </p>
                                    </div>
                                ))}
                                {lead.notes.length === 0 && (
                                    <p className="lbaic-settings-leads-drawer-notes-empty">
                                        {__("No notes yet", 'limb-chatbot')}
                                    </p>
                                )}
                            </div>
                        </div>*/}
                    </div>
                </div>
            </div>
        </div>,
        domNode
    );
}
