/**
 * Shois Chat Button — Agents Page
 *
 * List of agents with add/edit drawer, avatar, platforms, schedule.
 *
 * @package ShoisChatButton
 */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import ScheduleEditor from '../components/ScheduleEditor';
import CustomSelect from '../components/CustomSelect';

/**
 * Generate a unique ID.
 *
 * @return {string} Unique ID.
 */
function uid() {
    return 'agent_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8);
}

/**
 * Default agent template.
 *
 * @return {Object} New agent config.
 */
function newAgent() {
    return {
        id: uid(),
        enabled: true,
        name: '',
        title: '',
        avatar_type: 'initials',
        avatar_url: '',
        avatar_initials: '',
        avatar_bg_color: '#5170ff',
        status_message: '',
        platforms: [],
        schedule: { enabled: false, hours: {} },
    };
}

/**
 * Render a status badge with a dot.
 */
function StatusBadge({ status, message }) {
    const isOnline = status === 'online';
    const label = isOnline ? __('Online', 'shois-chat-button') : __('Offline', 'shois-chat-button');

    return (
        <div className={`shcb-status-badge shcb-status-${status}`}>
            <span className="shcb-status-dot"></span>
            <span className="shcb-status-label">{message || label}</span>
        </div>
    );
}

/**
 * Platform icon helper.
 */
function PlatformIcon({ platformId, platformDefs }) {
    const def = platformDefs[platformId] || {};
    const icons = {
        whatsapp: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>,
        messenger: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M.001 11.639C.001 4.949 5.241 0 12.001 0S24 4.95 24 11.639c0 6.689-5.24 11.638-12 11.638-1.21 0-2.38-.16-3.47-.46a.96.96 0 00-.64.05l-2.39 1.05a.96.96 0 01-1.35-.85l-.07-2.14a.97.97 0 00-.32-.68A11.39 11.389 0 01.002 11.64zm8.32-2.19l-3.52 5.6c-.35.53.32 1.139.82.75l3.79-2.87c.29-.21.69-.21.97 0l2.8 2.1c.86.64 2.09.4 2.65-.5l3.52-5.6c.35-.53-.32-1.13-.82-.75l-3.79 2.87c-.29.21-.69.21-.97 0l-2.8-2.1c-.86-.64-2.09-.4-2.65.5z"/></svg>,
        telegram: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M11.944 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0 12 12 0 0011.944 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 01.171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>,
        instagram: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678a6.162 6.162 0 100 12.324 6.162 6.162 0 100-12.324zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405a1.441 1.441 0 11-2.88 0 1.441 1.441 0 012.88 0z"/></svg>,
    };

    return (
        <div 
            className="shcb-agent-platform-icon" 
            style={{ backgroundColor: def.color || '#6366f1' }}
            title={def.name || platformId}
        >
            {icons[platformId] || <span className="shcb-platform-initial">{(def.name || platformId).charAt(0)}</span>}
        </div>
    );
}

/**
 * Agent row in the table.
 */
function AgentRow({ agent, onEdit, onToggle, onDelete, platformDefs }) {
    const initials = agent.avatar_initials || (agent.name ? agent.name.charAt(0).toUpperCase() : '?');
    const enabledPlatforms = (agent.platforms || []).filter(p => p.enabled);

    return (
        <tr className={`shcb-agent-row ${!agent.enabled ? 'shcb-agent-disabled' : ''}`}>
            {/* AVATAR */}
            <td className="shcb-td-avatar">
                <div className="shcb-agent-list-avatar">
                    {agent.avatar_type === 'image' && agent.avatar_url ? (
                        <img src={agent.avatar_url} alt={agent.name} />
                    ) : (
                        <div
                            className="shcb-agent-list-initials"
                            style={{ background: agent.avatar_bg_color || '#5170ff' }}
                        >
                            {initials}
                        </div>
                    )}
                </div>
            </td>

            {/* NAME */}
            <td className="shcb-td-name">
                <span className="shcb-agent-name">{agent.name || __('Unnamed Agent', 'shois-chat-button')}</span>
            </td>

            {/* TITLE */}
            <td className="shcb-td-title">
                <span className="shcb-agent-title">{agent.title || ''}</span>
            </td>

            {/* STATUS */}
            <td className="shcb-td-status">
                <StatusBadge status={agent.enabled ? 'online' : 'offline'} message={agent.status_message} />
            </td>

            {/* PLATFORMS */}
            <td className="shcb-td-platforms">
                <div className="shcb-agent-platforms-list">
                    {enabledPlatforms.map((p, idx) => (
                        <PlatformIcon key={idx} platformId={p.platform_id} platformDefs={platformDefs} />
                    ))}
                    {enabledPlatforms.length === 0 && <span className="shcb-no-platforms">—</span>}
                </div>
            </td>

            {/* ACTIVE */}
            <td className="shcb-td-active">
                <label className="shcb-master-toggle shcb-toggle-sm">
                    <input
                        type="checkbox"
                        checked={agent.enabled}
                        onChange={() => onToggle(agent.id)}
                    />
                    <span className="shcb-toggle-slider"></span>
                </label>
            </td>

            {/* ACTIONS */}
            <td className="shcb-td-actions">
                <div className="shcb-row-actions">
                    <button className="shcb-row-action-btn" onClick={() => onEdit(agent)} title={__('Edit', 'shois-chat-button')}>
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 113 3L12 15l-4 1 1-4 9.5-9.5z" /></svg>
                    </button>
                    <button className="shcb-row-action-btn shcb-action-delete" onClick={() => onDelete(agent.id)} title={__('Delete', 'shois-chat-button')}>
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6" /></svg>
                    </button>
                </div>
            </td>
        </tr>
    );
}

/**
 * Agent edit drawer.
 */
function AgentDrawer({ agent, onSave, onClose, platformDefs }) {
    const [data, setData] = useState({ ...agent });

    const update = useCallback((updates) => {
        setData((prev) => ({ ...prev, ...updates }));
    }, []);

    const updatePlatform = (index, updates) => {
        const platforms = [...(data.platforms || [])];
        platforms[index] = { ...platforms[index], ...updates };
        update({ platforms });
    };

    const isPro = window.shcbAdmin?.isPro || false;

    const addPlatform = () => {
        const platforms = [...(data.platforms || [])];
        if (!isPro && platforms.length >= 1) {
            return; // blocked — UI shows upsell instead
        }
        platforms.push({ 
            platform_id: 'whatsapp', 
            value: '', 
            label: '',
            pre_message: '', 
            enabled: true, 
            is_primary: false 
        });
        update({ platforms });
    };

    const removePlatform = (index) => {
        const platforms = [...(data.platforms || [])];
        platforms.splice(index, 1);
        update({ platforms });
    };

    const handleScheduleChange = (schedule) => {
        update({ schedule });
    };

    return (
        <div className="shcb-drawer-overlay" onClick={onClose}>
            <div className="shcb-drawer" onClick={(e) => e.stopPropagation()}>
                <div className="shcb-drawer-header">
                    <h3>{agent.id ? __('Edit Agent', 'shois-chat-button') : __('Add Agent', 'shois-chat-button')}</h3>
                    <button className="shcb-drawer-close" onClick={onClose} type="button">✕</button>
                </div>

                <div className="shcb-drawer-body">
                    { /* Basic Info */}
                    <h4 className="shcb-section-title">{__('Basic Info', 'shois-chat-button')}</h4>

                    <div className="shcb-field-group">
                        <label className="shcb-field-label">{__('Name', 'shois-chat-button')}</label>
                        <input className="shcb-input" value={data.name} onChange={(e) => update({ name: e.target.value })} placeholder="John" />
                    </div>

                    <div className="shcb-field-group">
                        <label className="shcb-field-label">{__('Title / Role', 'shois-chat-button')}</label>
                        <input className="shcb-input" value={data.title} onChange={(e) => update({ title: e.target.value })} placeholder="Sales Manager" />
                    </div>

                    <div className="shcb-field-group">
                        <label className="shcb-field-label">{__('Status Message', 'shois-chat-button')}</label>
                        <input className="shcb-input" value={data.status_message} onChange={(e) => update({ status_message: e.target.value })} placeholder="Available • Replies in 5 min" />
                    </div>

                    { /* Avatar */}
                    <h4 className="shcb-section-title">{__('Avatar', 'shois-chat-button')}</h4>

                    <div className="shcb-field-group">
                        <label className="shcb-field-label">{__('Avatar Type', 'shois-chat-button')}</label>
                        <CustomSelect
                            value={data.avatar_type}
                            onChange={(val) => update({ avatar_type: val })}
                            options={[
                                { value: 'initials', label: __('Initials', 'shois-chat-button') },
                                { value: 'image', label: __('Image URL', 'shois-chat-button') }
                            ]}
                        />
                    </div>

                    {data.avatar_type === 'initials' && (
                        <>
                            <div className="shcb-field-group">
                                <label className="shcb-field-label">{__('Initials', 'shois-chat-button')}</label>
                                <input className="shcb-input" value={data.avatar_initials} onChange={(e) => update({ avatar_initials: e.target.value.substring(0, 2).toUpperCase() })} maxLength={2} placeholder="JD" />
                            </div>
                            <div className="shcb-field-group shcb-field-color">
                                <label className="shcb-field-label">{__('Background', 'shois-chat-button')}</label>
                                <div className="shcb-color-input-wrap">
                                    <input type="color" className="shcb-color-input" value={data.avatar_bg_color || '#5170ff'} onChange={(e) => update({ avatar_bg_color: e.target.value })} />
                                    <input type="text" className="shcb-input shcb-color-hex" value={data.avatar_bg_color || '#5170ff'} onChange={(e) => update({ avatar_bg_color: e.target.value })} maxLength={7} />
                                </div>
                            </div>
                        </>
                    )}

                    {data.avatar_type === 'image' && (
                        <div className="shcb-field-group">
                            <label className="shcb-field-label">{__('Image URL', 'shois-chat-button')}</label>
                            <input className="shcb-input" value={data.avatar_url} onChange={(e) => update({ avatar_url: e.target.value })} placeholder="https://..." />
                        </div>
                    )}

                    { /* Platforms */}
                    <h4 className="shcb-section-title">{__('Platforms', 'shois-chat-button')}</h4>

                    {(data.platforms || []).map((plat, idx) => {
                        const platDef = platformDefs[plat.platform_id] || {};
                        const isPhone = platDef.input_type === 'phone';
                        const showPreMsg = platDef.supports_pre_message;
                        const placeholder = platDef.input_placeholder || __('Number / Username', 'shois-chat-button');
                        const inputLabel = platDef.input_label || __('Value', 'shois-chat-button');

                        return (
                            <div key={idx} className="shcb-platform-row">
                                <div className="shcb-platform-row-top">
                                    <CustomSelect
                                        className="shcb-platform-select"
                                        value={plat.platform_id}
                                        onChange={(val) => updatePlatform(idx, { platform_id: val, value: '', pre_message: '' })}
                                        options={Object.keys(platformDefs || {}).map((pkey) => ({
                                            value: pkey,
                                            label: platformDefs[pkey]?.name || pkey
                                        }))}
                                        style={{ flex: '1' }}
                                    />
                                    <label className="shcb-master-toggle shcb-toggle-sm">
                                        <input type="checkbox" checked={plat.enabled} onChange={(e) => updatePlatform(idx, { enabled: e.target.checked })} />
                                        <span className="shcb-toggle-slider"></span>
                                    </label>
                                    <button className="shcb-btn shcb-btn-danger shcb-btn-sm" onClick={() => removePlatform(idx)} type="button">✕</button>
                                </div>
                                <div className="shcb-platform-row-fields">
                                    <div className="shcb-field-group" style={{ marginBottom: 0 }}>
                                        <label className="shcb-field-label shcb-field-label-sm">{inputLabel}</label>
                                        <input
                                            className="shcb-input"
                                            value={plat.value}
                                            onChange={(e) => updatePlatform(idx, { value: e.target.value })}
                                            placeholder={placeholder}
                                            type={isPhone ? 'tel' : 'text'}
                                        />
                                        {isPhone && (
                                            <p className="shcb-field-help" style={{ marginTop: 4 }}>
                                                {__('Include country code (e.g., +880, +1, +44). Without it, the link will not work.', 'shois-chat-button')}
                                            </p>
                                        )}
                                    </div>
                                    {showPreMsg && (
                                        <div className="shcb-field-group" style={{ marginBottom: 0 }}>
                                            <label className="shcb-field-label shcb-field-label-sm">{__('Pre-filled Message', 'shois-chat-button')}</label>
                                            <input
                                                className="shcb-input"
                                                value={plat.pre_message || ''}
                                                onChange={(e) => updatePlatform(idx, { pre_message: e.target.value })}
                                                placeholder={__('Hi! I have a question about...', 'shois-chat-button')}
                                            />
                                        </div>
                                    )}
                                </div>
                            </div>
                        );
                    })}

                    {(!isPro && (data.platforms || []).length >= 1) ? (
                        <div className="shcb-pro-upsell-inline" onClick={() => window.dispatchEvent(new CustomEvent('shcb-pro-alert'))} style={{cursor: 'pointer'}}>
                            <span>🔒</span>
                            <span>{__('Multiple platforms per agent requires', 'shois-chat-button')} <strong>PRO</strong></span>
                        </div>
                    ) : (
                        <button className="shcb-btn shcb-btn-secondary" onClick={addPlatform} type="button">
                            + {__('Add Platform', 'shois-chat-button')}
                        </button>
                    )}

                    { /* Schedule */}
                    <h4 className="shcb-section-title">
                        {__('Schedule', 'shois-chat-button')}
                    </h4>

                    <ScheduleEditor
                        schedule={data.schedule || {}}
                        onChange={handleScheduleChange}
                    />
                </div>

                <div className="shcb-drawer-footer">
                    <button className="shcb-btn shcb-btn-secondary" onClick={onClose} type="button">
                        {__('Cancel', 'shois-chat-button')}
                    </button>
                    <button className="shcb-btn shcb-btn-primary" onClick={() => onSave(data)} type="button">
                        {__('Save Agent', 'shois-chat-button')}
                    </button>
                </div>
            </div>
        </div>
    );
}

/**
 * AgentsPage — list + drawer CRUD for agents.
 *
 * @return {JSX.Element} Agents page.
 */
export default function AgentsPage() {
    const [agents, setAgents] = useState([]);
    const [editing, setEditing] = useState(null);
    const [saving, setSaving] = useState(false);
    const [platformDefs, setPlatformDefs] = useState({});

    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/agents' })
            .then((data) => setAgents(Array.isArray(data) ? data : []))
            .catch(() => { });

        apiFetch({ path: '/shois-chat/v1/platforms' })
            .then((data) => setPlatformDefs(data || {}))
            .catch(() => { });
    }, []);

    const saveAgents = (updated) => {
        setSaving(true);
        apiFetch({
            path: '/shois-chat/v1/agents',
            method: 'POST',
            data: { agents: updated },
        })
            .then(() => setAgents(updated))
            .catch(() => { })
            .finally(() => setSaving(false));
    };

    const handleToggle = (id) => {
        const updated = agents.map((a) => a.id === id ? { ...a, enabled: !a.enabled } : a);
        saveAgents(updated);
    };

    const handleDelete = (id) => {
        const updated = agents.filter((a) => a.id !== id);
        saveAgents(updated);
    };

    const handleSave = (agentData) => {
        let updated;
        const existing = agents.find((a) => a.id === agentData.id);
        if (existing) {
            updated = agents.map((a) => a.id === agentData.id ? agentData : a);
        } else {
            updated = [...agents, agentData];
        }
        saveAgents(updated);
        setEditing(null);
    };

    const isProUser = window.shcbAdmin?.isPro || false;

    const handleAddAgent = () => {
        if (!isProUser && agents.length >= 1) {
            return; // blocked — UI shows upsell
        }
        setEditing(newAgent());
    };

    return (
        <div className="shcb-agents-page">
            <div className="shcb-modern-card">
                <div className="shcb-modern-card-header">
                    <span>👤</span>
                    <h3>{__('Agents', 'shois-chat-button')}</h3>
                    {(!isProUser && agents.length >= 1) ? (
                        <div className="shcb-pro-upsell-inline" onClick={() => window.dispatchEvent(new CustomEvent('shcb-pro-alert'))} style={{cursor: 'pointer'}}>
                            <span>🔒</span>
                            <span>{__('Multiple agents requires', 'shois-chat-button')} <strong>PRO</strong></span>
                        </div>
                    ) : (
                        <button
                            className="shcb-btn shcb-btn-primary shcb-btn-sm"
                            onClick={handleAddAgent}
                            type="button"
                        >
                            + {__('Add Agent', 'shois-chat-button')}
                        </button>
                    )}
                </div>
                <p className="shcb-tab-description">
                    {__('Add team members who are available to chat. Each agent can have their own platforms and schedule.', 'shois-chat-button')}
                </p>
            </div>

            <div className="shcb-agents-list-container">
                {agents.length > 0 && (
                    <table className="shcb-agents-table">
                        <thead>
                            <tr>
                                <th>{__('AVATAR', 'shois-chat-button')}</th>
                                <th>{__('NAME', 'shois-chat-button')}</th>
                                <th>{__('TITLE', 'shois-chat-button')}</th>
                                <th>{__('STATUS', 'shois-chat-button')}</th>
                                <th>{__('PLATFORMS', 'shois-chat-button')}</th>
                                <th>{__('ACTIVE', 'shois-chat-button')}</th>
                                <th>{__('ACTIONS', 'shois-chat-button')}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {agents.map((agent) => (
                                <AgentRow
                                    key={agent.id}
                                    agent={agent}
                                    onEdit={(a) => setEditing({ ...a })}
                                    onToggle={handleToggle}
                                    onDelete={handleDelete}
                                    platformDefs={platformDefs}
                                />
                            ))}
                        </tbody>
                    </table>
                )}
            </div>

            {editing && (
                <AgentDrawer
                    agent={editing}
                    onSave={handleSave}
                    onClose={() => setEditing(null)}
                    platformDefs={platformDefs}
                />
            )}

            {saving && <div className="shcb-saving-toast">{__('Saving...', 'shois-chat-button')}</div>}
        </div>
    );
}
