<?php
namespace EasyChat\View;

class QuickReplyFragments {

    public static function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }

    public function alert($type, $message, $hidden = false) {
        $id = $type === 'success' ? 'save-alert' : 'error-alert';
        $class = $type === 'success' ? 'alert-success' : 'alert-danger';
        $icon = $type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle';

        return '<div id="' . $id . '" class="alert quick-reply-alert ' . $class . ($hidden ? ' d-none' : '') . ' ' . HtmxFragmentRenderer::motionClass('alert') . '">'
            . '<i class="fa ' . $icon . ' me-2"></i> <span>' . self::e($message) . '</span>'
            . '</div>';
    }

    public function aiPanel($scope, $ai_knowledge_available, array $ai_state = []) {
        $knowledge_checked = $ai_knowledge_available ? ' checked' : '';
        $knowledge_disabled = $ai_knowledge_available ? '' : ' disabled';
        $panel_open = !empty($ai_state) ? '' : ' d-none';
        $error = (string)($ai_state['error'] ?? '');
        $result_title = (string)($ai_state['title'] ?? '');
        $result_text = (string)($ai_state['text'] ?? '');
        $source_count = (int)($ai_state['source_count'] ?? 0);
        $warning = (string)($ai_state['warning'] ?? '');
        $source = $source_count > 0 ? 'База знаний: ' . $source_count : ($warning === 'knowledge_not_used' ? 'База знаний: нет совпадений' : '');
        $has_result = $result_text !== '';
        $has_error = $error !== '';

        return '<div class="reply-ai-panel' . $panel_open . '">'
            . '  <input type="hidden" name="ai_scope" value="' . self::e($scope) . '">'
            . '  <div class="reply-ai-controls">'
            . '    <select name="task" class="form-select form-select-sm reply-ai-task" aria-label="Задача ИИ">'
            . '      <option value="improve">Улучшить</option>'
            . '      <option value="generate">Сгенерировать</option>'
            . '      <option value="shorten">Сократить</option>'
            . '      <option value="expand">Подробнее</option>'
            . '    </select>'
            . '    <select name="style" class="form-select form-select-sm reply-ai-style" aria-label="Стиль ответа">'
            . '      <option value="current">Как сейчас</option>'
            . '      <option value="friendly">Дружелюбно</option>'
            . '      <option value="business">Делово</option>'
            . '      <option value="sales">Продающе</option>'
            . '      <option value="support">Техподдержка</option>'
            . '    </select>'
            . '    <label class="reply-ai-knowledge"><input type="checkbox" name="use_knowledge" class="form-check-input reply-ai-use-knowledge" value="1"' . $knowledge_checked . $knowledge_disabled . '> База знаний</label>'
            . '    <input type="text" name="instruction" class="form-control form-control-sm reply-ai-instruction" maxlength="500" placeholder="Что учесть">'
            . '    <button type="button" class="btn btn-primary btn-sm reply-ai-suggest" hx-post="index.php?route=quickreply/aiSuggest" hx-target="closest .reply-row" hx-swap="' . self::e(HtmxFragmentRenderer::quickReplyRowSwap()) . '" hx-sync="closest .reply-row:replace" hx-include="closest .reply-row, closest form [name=&quot;csrf_token&quot;]" hx-indicator="closest .reply-row .reply-ai-suggest"><i class="fa fa-magic me-1"></i> Предложить</button>'
            . '  </div>'
            . '  <div class="reply-ai-error' . ($has_error ? '' : ' d-none') . '">' . self::e($error) . '</div>'
            . '  <div class="reply-ai-result' . ($has_result ? '' : ' d-none') . '">'
            . '    <div class="reply-ai-result-title">' . self::e($result_title !== '' ? $result_title : 'Новый ответ') . '</div>'
            . '    <div class="reply-ai-result-text">' . self::e($result_text) . '</div>'
            . '    <div class="reply-ai-result-footer">'
            . '      <span class="reply-ai-source">' . self::e($source) . '</span>'
            . '      <button type="button" class="btn btn-outline-primary btn-sm reply-ai-apply" data-title="' . self::e($result_title) . '" data-text="' . self::e($result_text) . '"><i class="fa fa-check me-1"></i> Применить</button>'
            . '    </div>'
            . '  </div>'
            . '</div>';
    }

    public function replyRow($scope, array $reply, $editable, $max_title_length, $max_text_length, $ai_available, $ai_reason, $ai_knowledge_available, array $ai_state = []) {
        $reply_id = (int)($reply['raw_id'] ?? $reply['id'] ?? 0);
        $title = self::e($reply['title'] ?? '');
        $text = self::e($reply['text'] ?? '');
        $readonly = $editable ? '' : ' readonly disabled';
        $ai_button = $ai_available
            ? '<button type="button" class="btn btn-light btn-sm text-primary btn-ai-row" title="Помочь с текстом через ИИ"><i class="fa fa-magic"></i></button>'
            : '<button type="button" class="btn btn-light btn-sm text-muted btn-ai-row" title="' . self::e($this->aiDisabledTitle($ai_reason)) . '" disabled><i class="fa fa-magic"></i></button>';
        $actions = $editable
            ? $ai_button . '<button type="button" class="btn btn-light btn-sm text-muted btn-duplicate-row" title="Дублировать"><i class="fa fa-copy"></i></button><button type="button" class="btn btn-light btn-sm text-danger btn-delete-row" title="Удалить"><i class="fa fa-trash"></i></button>'
            : '<span class="badge bg-light text-muted border">только чтение</span>';

        $html = '<div class="reply-row ' . HtmxFragmentRenderer::motionClass('row') . '" data-scope="' . self::e($scope) . '"' . ($reply_id > 0 ? ' data-reply-id="' . (int)$reply_id . '"' : '') . '>'
            . '  <input type="hidden" name="reply_ids[]" class="reply-id-input" value="' . ($reply_id > 0 ? (int)$reply_id : '') . '">'
            . '  <input type="hidden" name="ids[]" class="reply-order-id" value="' . ($reply_id > 0 ? (int)$reply_id : '') . '">'
            . '  <div class="reply-row-handle cursor-move" tabindex="0" role="button" aria-label="Переместить ответ" title="Перетащить"><i class="fa fa-bars"></i></div>'
            . '  <div class="reply-row-main">'
            . '    <div class="reply-row-top">'
            . '      <div class="reply-title-wrap">'
            . '        <label class="form-label">Название кнопки</label>'
            . '        <input type="text" name="titles[]" class="form-control reply-title-input" maxlength="' . (int)$max_title_length . '" placeholder="Например: Гарантия" value="' . $title . '"' . $readonly . '>'
            . '      </div>'
            . '      <div class="reply-actions">' . $actions . '</div>'
            . '    </div>'
            . '    <label class="form-label mt-3">Текст ответа</label>'
            . '    <textarea name="texts[]" class="form-control reply-text-input" maxlength="' . (int)$max_text_length . '" rows="4" placeholder="Введите полный текст, который будет вставлен в поле ответа..."' . $readonly . '>' . $text . '</textarea>'
            . '    <div class="reply-row-meta"><span class="reply-text-counter">0 / ' . (int)$max_text_length . '</span><span class="reply-row-status d-none" aria-live="polite"></span></div>';

        if ($editable) {
            $html .= $this->aiPanel($scope, $ai_knowledge_available, $ai_state);
        }

        return $html . '  </div></div>';
    }

    public function replyRows($scope, array $replies, $editable, $max_title_length, $max_text_length, $ai_available, $ai_reason, $ai_knowledge_available) {
        if (empty($replies) && $editable) {
            $replies = [['title' => '', 'text' => '', 'scope' => $scope]];
        }

        if (empty($replies)) {
            return '<div class="quick-reply-empty text-center text-muted py-4 ' . HtmxFragmentRenderer::motionClass('empty') . '">'
                . '<i class="fa fa-bolt mb-2" style="font-size: 24px; color: #f59e0b;"></i>'
                . '<div class="fw-semibold text-dark">Пока нет шаблонов</div>'
                . '</div>';
        }

        $html = '';
        foreach ($replies as $reply) {
            $html .= $this->replyRow($scope, $reply, $editable, $max_title_length, $max_text_length, $ai_available, $ai_reason, $ai_knowledge_available);
        }
        return $html;
    }

    private function aiDisabledTitle($reason) {
        if ($reason === 'ai_disabled') {
            return 'AI-помощник сейчас недоступен';
        }
        if ($reason === 'api_key_missing') {
            return 'Не настроен API key ИИ';
        }
        return 'ИИ сейчас недоступен';
    }

}
