@push('styles')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .bold-label {
            font-weight: 900 !important;
            font-family: Roboto, sans-serif !important;
            color: black !important;
        }
    </style>
@endpush

<div id="aiMessageGenerator" tabindex="-1" role="dialog" aria-labelledby="aiMessageGeneratorLabel" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" id="aiModalCloseBtn" class="close" data-dismiss="modal">&times;</button>
                <h4 id="aiMessageGeneratorLabel" class="modal-title">
                    <img style="width: 30px" src="{{ asset('img/ai_wand.png') }}">
                    <span class="bold-label">Compose My SMS Message with AI</span>&nbsp;
                </h4>
                <hr>
            </div>

            <div class="modal-body">
                <div id="chat_form">
                    <div class="col-md-12">
                        {{-- <div style="margin: 1em 0.0em;" class="row">
                            <div class="col-md-6">
                                <label class="control-label bold-label" for="tone">Tone</label>
                            </div>
                            <div class="col-md-6">
                                <select class="" id="tone" class="form-control d-inline">
                                    <option selected disabled>--Select SMS Tone --</option>
                                    <option>Formal</option>
                                    <option>Informal</option>
                                    <option>Concise</option>
                                    <option>Exciting</option>
                                    <option>Normal</option>
                                    @foreach (auth()->user()->ai_tones as $tone)
                                        <option value="{{ $tone->instruction }}">{{ $tone->name }}</option>
                                    @endforeach
                                    <option>Custom</option>
                                </select>
                            </div>
                        </div> --}}
                        <label style="padding: 0;" class="control-label col-md-12" for="chat_question">
                            <span style="font-size: 15px !important" class="bold-label">Focus of your Message</span>
                            <select style="float: right; margin-left: 10px;" class="toneSelect" id="tone"
                                class="form-control d-inline">
                                <option selected disabled value="">--Select SMS Tone --</option>
                                <option>Formal</option>
                                <option>Informal</option>
                                <option>Concise</option>
                                <option>Exciting</option>
                                <option>Normal</option>
                                @foreach (auth()->user()->ai_tones as $tone)
                                    <option value="{{ $tone->instruction }}">{{ $tone->name }}</option>
                                @endforeach
                                <option>Custom</option>
                            </select>
                            <button class="btn btn-sm" id="generateBtn"
                                style="background-color: #0b0c0f; color: #FFCB05; float: right;">Generate</button>
                            <button class="btn btn-sm font-weight-900" id="resetBtn"
                                style="background-color: #f8f9fa; color: #0b0c0f; float: right; margin-right: 5px;">
                                <i class="fas fa-undo"></i> Reset
                            </button>
                        </label>
                        <textarea name="chat_question" id="chat_question" class="form-control col-md-12" rows="5" cols="60"
                            maxlength="1528"></textarea>
                    </div>

                    <button class="hidden" id="triggerAiToneModal" data-toggle="modal" data-target="#aiToneModal"
                        hidden>Show AI Tone Modal</button>

                    <div class="form-group col-md-12" style="margin-top: 10px;">
                        <label style="padding: 0;" class="control-label col-md-12 bold-label" for="chat_answer">
                            <span style="font-size: 15px !important">Response</span>
                            <button class="btn btn-sm" id="copyBtn"
                                style="background-color: #0b0c0f; color: #FFCB05; float: right;">Use this
                                message</button></label>
                        <textarea name="chat_answer" id="chat_answer" class="form-control col-md-12" rows="10" cols="60"
                            maxlength="1528" readonly></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<div id="aiToneModal" tabindex="-1" role="dialog" aria-labelledby="aiToneModalLabel" class="modal fade">
    <div class="modal-dialog modal-md">
        <form id="aiToneForm">
            @csrf
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" id="aiToneCloseBtn" class="close tone-modal-close-btn"
                        data-dismiss="modal">&times;</button>
                    <h4 id="aiToneModalLabel" class="modal-title bold-label">Create your Tone</h4>
                    <hr>
                </div>

                <div class="modal-body">
                    <div class="form-group">
                        <label class="bold-label" for="name">Tone name</label>
                        <input id="toneName" class="form-control" placeholder="e.g. Professional" type="text"
                            name="name">
                        <small class="text-danger" id="nameError"></small> <!-- Error message -->
                    </div>

                    <div class="form-group">
                        <label class="bold-label" for="instruction">Tone instruction</label>
                        <textarea id="toneInstruction" name="instruction" rows="5" class="form-control"
                            placeholder="Instruction for how the AI should respond"></textarea>
                        <small class="text-danger" id="instructionError"></small> <!-- Error message -->
                    </div>
                    <small>Provide clear instructions for how the AI should format and style its responses.</small>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default tone-modal-close-btn"
                        data-dismiss="modal">Cancel</button>
                    <button id="toneSubmitBtn" type="submit" class="btn btn-success">Save Style</button>
                </div>
            </div>
        </form>
    </div>
</div>


@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>


    <script>
        // $('#tone')
        //     .select2({
        //         placeholder: 'Search',
        //         dropdownParent: $('#aiMessageGenerator'),
        //         tags: true,
        //         width: '100%',
        //     }).on('select2:select', function(e) {
        //         const selectedTone = e.params.data.id.toLowerCase();

        //         console.log('Selected tone: ', selectedTone);

        //         if (selectedTone === 'custom') {

        //             $('#triggerAiToneModal').trigger('click');
        //         }
        //     });


        $(document).ready(function() {
            $('#tone').change(function(e) {
                const selectedTone = e.target.value.toLowerCase();

                console.log('Selected tone: ', selectedTone);

                if (selectedTone === 'custom') {

                    $('#triggerAiToneModal').trigger('click');
                }
            });
            // let currentChatId = null;

            $('#aiToneForm').on('submit', function(e) {
                e.preventDefault(); // Prevent default form submission

                let formData = {
                    name: $('#toneName').val(),
                    instruction: $('#toneInstruction').val(),
                    _token: $('meta[name="csrf-token"]').attr('content') // CSRF token
                };

                $.ajax({
                    url: "{{ route('aitone.store') }}", // Laravel route for storing AI tone
                    method: "POST",
                    data: formData,
                    dataType: "json",
                    beforeSend: function() {
                        // Clear previous errors
                        $('#nameError').text('');
                        $('#instructionError').text('');
                        $('#toneSubmitBtn').prop('disabled', true).text('Saving...');
                    },
                    success: function(response) {
                        console.log("Success:", response);

                        // Close the modal
                        $('#aiToneModal').modal('hide');

                        // Show success message
                        alert('AI Tone added successfully!');

                        // Append new tone to the dropdown
                        let newOption =
                            `<option value="${formData.instruction}">${formData.name}</option>`;
                        $('.toneSelect').find('option:last').before(
                            newOption); // Add before "Custom" option

                        // Optionally, select the newly added tone
                        $('.toneSelect').val(formData.instruction);
                    },
                    error: function(xhr) {
                        console.log("Error:", xhr);
                        if (xhr.status === 422) {
                            // Validation errors
                            let errors = xhr.responseJSON.errors;
                            if (errors.name) {
                                $('#nameError').text(errors.name[0]);
                            }
                            if (errors.instruction) {
                                $('#instructionError').text(errors.instruction[0]);
                            }
                        } else if (
                            xhr.status === 409 &&
                            xhr.responseJSON?.status === 'error' &&
                            xhr.responseJSON?.message
                        ) {
                            alert(xhr.responseJSON?.message);
                        } else {
                            alert('Something went wrong! Please try again.');
                        }
                    },
                    complete: function() {
                        $('#toneSubmitBtn').prop('disabled', false).text('Save Style');
                        $('#toneName').val('')
                        $('#toneInstruction').val('')
                    },
                });
            });

            $('#generateBtn').on('click', function(e) {
                e.preventDefault();
                let question = $('#chat_question').val();
                let tone = $('#tone').val();

                if (!tone) {
                    alert("Please select SMS tone.");
                    return;
                }

                if (!question) {
                    alert("Please provide the focus of your message.");
                    return;
                }

                if (question) {
                    $.ajax({
                        url: "{{ route('ai.sms_generator') }}",
                        type: 'GET',
                        data: {
                            _token: "{{ csrf_token() }}",
                            'prompt': question,
                            'tone': tone
                        },
                        beforeSend: function() {
                            $('#generateBtn').prop('disabled', true).text('Generating...');
                        }
                    }).done((response) => {
                        if (response.code === 200) {
                            $('#chat_answer').val(response.results.data);
                            // $('#chat_answer').val(response.results.data.replace(/\n/g, ''));
                            // currentChatId = response.results.chat_id;
                        }
                    }).fail((xhr, status, error) => {
                        console.log("An error occurred: " + error);
                        alert('Generating message wasn\'t successful, kindly Try Again...');
                    }).always(() => {
                        $('#generateBtn').prop('disabled', false).text('Generate');
                    });
                }
            });

            $('#copyBtn').click(function(e) {
                e.preventDefault();
                let chat_answer = $('#chat_answer').val();
                if (!chat_answer) {
                    return;
                }
                $('textarea[name="message_content"]').val(chat_answer);

                // console.log('selected tone: ', $('#tone').val());

                $('#toneSelect option').each(function() {
                    if ($(this).text().toLowerCase() === $('#tone').val()
                        .toLowerCase()) {
                        $('#toneSelect').val($(this)
                            .val()); // Select the matching option
                        return false; // Break the loop
                    }
                });

                $('#aiModalCloseBtn').trigger('click');

            });

            // reset button
            $('#resetBtn').click(function(e) {
                e.preventDefault();
                $('#chat_question').val('');
                $('#tone').val('');
            });

            // Handle closing of Custom tone modal
            $('.tone-modal-close-btn').click(function(e) {
                $('#tone').val('');
            });
        });
    </script>
@endpush
