@extends('layouts.app')
@section('title', 'Manage Prompts')

@section('content')
    <style>
        div.dataTables_wrapper div.dataTables_paginate ul.pagination {
            white-space: nowrap;
            justify-content: flex-end;
        }

        /* Modal Styles */
        .modal-content {
            border-radius: 12px !important;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.25);
            border: none;
        }

        .modal-header {
            border-bottom: 1px solid #dee2e6;
            background: #f8f9fa;
            border-top-left-radius: 12px;
            border-top-right-radius: 12px;
        }

        .modal-body {
            padding: 20px 25px;
        }

        .modal-footer {
            border-top: 1px solid #dee2e6;
            background: #f8f9fa;
            border-bottom-left-radius: 12px;
            border-bottom-right-radius: 12px;
        }

        .table td {
            vertical-align: middle !important;
        }

        .function-card {
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 12px 15px;
            margin-bottom: 10px;
            background-color: #f8f9fa;
        }
    </style>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-12">
                <div class="box">
                    <div class="box-body">
                        <h4 class="box-title text-info mb-0">
                            <i class="fa fa-list fa-sx"></i> Manage Prompts
                        </h4>

                        <div class="d-flex justify-content-end gap-4">
                            <a href="{{ route('google.oauth') }}" target="_blank" type="button"
                                style="float:right;margin-top:-20px;"
                                class="waves-effect waves-light btn btn-rounded btn-danger btn-bitbucket btn-sm mb-5">
                                <i class="fa fa-plus"></i> Get Access Token
                            </a>
                            @if(Session::get('level') >= 9)
                                <form method="post">
                                    @csrf
                                    <a href="{{ route('prompts.create') }}" type="button" style="float:right;margin-top:-20px;"
                                        class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5">
                                        <i class="fa fa-plus"></i> Add Prompt
                                    </a>
                                </form>
                            @endif
                        </div>

                        <hr class="my-15">

                        <div class="table-responsive">
                            <table id="tickets" class="table mt-0 table-hover no-wrap">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Title</th>
                                        <th>Voice</th>
                                        <th>Description</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($prompts as $key => $prompt)
                                        <tr>
                                            <td>{{ $key + 1 }}</td>
                                            <td>{{ $prompt->title }}</td>
                                            <td>{{ ucfirst($prompt->voice_name) }}</td>
                                            <td style="max-width:400px;" class="text-truncate">{{ $prompt->description }}
                                            </td>
                                            <td>
                                                <a href="#" class="view-prompt" data-id="{{ $prompt->id }}" style="color:blue;">
                                                    <i class="fa fa-eye fa-lg"></i>
                                                </a>
                                                &nbsp;
                                                @if(Session::get('level') >= 9)
                                                    <a href="{{ route('prompts.edit', $prompt->id) }}" style="color:green;">
                                                        <i class="fa fa-edit fa-lg"></i>
                                                    </a>
                                                    &nbsp;
                                                    <form action="{{ route('prompts.destroy', $prompt->id) }}" method="POST"
                                                        class="delete-prompt-form d-inline">
                                                        @csrf
                                                        <a style="cursor:pointer;color:red;" class="delete-prompt-btn">
                                                            <i class="fa fa-trash fa-lg"></i>
                                                        </a>
                                                    </form>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div><!-- /.table-responsive -->
                    </div><!-- /.box-body -->
                </div><!-- /.box -->
            </div>
        </div>
    </section>

    <!-- Modal -->
    <div class="modal fade" id="promptModal" tabindex="-1" aria-labelledby="promptModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="promptModalLabel">Prompt Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="promptDetails">
                        <p class="text-muted">Loading details...</p>
                    </div>
                </div>
                <div class="modal-footer d-flex justify-content-between">
                    <a href="#" id="editPromptBtn" class="btn btn-success {{ Session::get('level') >= 9 ? '' : 'invisible'}}">Edit Prompt</a>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- SweetAlert + Bootstrap + jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        $(document).ready(function () {

            // Handle "View" button click
            $('.view-prompt').on('click', function (e) {
                e.preventDefault();
                const promptId = $(this).data('id');
                $('#promptModal').modal('show');
                $('#promptDetails').html('<p class="text-muted">Loading...</p>');
                $('#editPromptBtn').attr('href', '#');

                $.ajax({
                    url: `/prompts/show/${promptId}`,
                    method: 'GET',
                    success: function (res) {
                        if (res.success) {
                            const prompt = res.data.prompt;
                            const functions = res.data.functions || [];

                            // Prompt section
                            let html = `
                                    <h5 class="text-primary mb-3">${prompt.title}</h5>
                                    <p><strong>Voice:</strong> ${prompt.voice_name ? prompt.voice_name : 'N/A'}</p>
                                    <p><strong>Description:</strong></p>
                                    <div class="border p-3 rounded bg-light mb-4" style="max-height:400px; overflow-y:auto;">
                                        ${prompt.description || 'No description available'}
                                    </div>
                                `;

                            // Functions Section
                            if (functions.length > 0) {
                                html +=
                                    `<h6 class="text-info mb-3"><i class="fa fa-cogs"></i> Functions (${functions.length})</h6>`;

                                functions.forEach((fn, index) => {
                                    html += `
                                            <div class="function-card mb-3 p-3 border rounded bg-white shadow-sm">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <h6 class="mb-1 text-dark">
                                                        <i class="fa ${fn.type === 'call' ? 'fa-phone' : 'fa-comment'} text-secondary me-2"></i>
                                                        ${fn.name || 'Unnamed Function'}
                                                    </h6>
                                                    <span class="badge bg-${fn.type === 'call' ? 'success' : 'info'} text-uppercase">${fn.type}</span>
                                                </div>
                                                <div class="mt-2">
                                                    ${fn.phone ? `<p class="mb-1"><strong>Phone:</strong> ${fn.phone}</p>` : ''}
                                                    ${fn.message ? `<p class="mb-1"><strong>Message:</strong> ${fn.message}</p>` : ''}
                                                    <small class="text-muted">Created at: ${new Date(fn.created_at).toLocaleString()}</small>
                                                </div>
                                            </div>
                                        `;
                                });
                            } else {
                                html +=
                                    `<div class="alert alert-secondary mt-3">No functions added to this prompt.</div>`;
                            }

                            $('#promptDetails').html(html);
                            $('#editPromptBtn').attr('href', '/prompts/edit/' + prompt.id);

                        } else {
                            $('#promptDetails').html(
                                '<div class="alert alert-danger">Unable to load prompt details.</div>'
                            );
                        }
                    },
                    error: function () {
                        $('#promptDetails').html(
                            '<div class="alert alert-danger">An error occurred while loading the prompt.</div>'
                        );
                    }
                });
            });

            // Delete confirmation
            $('.delete-prompt-btn').on('click', function () {
                const form = $(this).closest('form');
                Swal.fire({
                    title: 'Are you sure?',
                    text: "This will permanently delete the prompt.",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                });
            });
        });
    </script>
@endsection
