@extends('layouts.app')

@section('title', __('vetAI::lang.clinical_assistant'))

@section('css')
<style>
.vai-wrap { display:flex; gap:16px; align-items:flex-start; }
.vai-col-form { flex:0 0 420px; }
.vai-col-out  { flex:1; min-width:0; }
@media(max-width:1100px){ .vai-wrap{ flex-direction:column; } .vai-col-form{ flex:1 1 auto; width:100%; } }
.vai-card { background:#fff; border:1px solid #e5e9f0; border-radius:10px; margin-bottom:14px; }
.vai-card-h { padding:9px 14px; border-bottom:1px solid #f0f2f5; font-weight:700; color:#1e293b; }
.vai-card-b { padding:13px 14px; }
.vai-disc { background:#fffbeb; border:1px solid #fde68a; color:#92400e; border-radius:8px;
    padding:9px 13px; font-size:12px; margin-bottom:14px; }
.vai-qtype { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
.vai-qtype label { display:block; border:1.5px solid #e2e8f0; border-radius:7px; padding:7px 9px;
    font-size:12px; font-weight:600; cursor:pointer; margin:0; color:#475569; }
.vai-qtype input { margin-right:5px; }
.vai-qtype input:checked + span { color:#2563eb; }
.vai-qtype label:has(input:checked) { border-color:#2563eb; background:#eff6ff; }
.vai-response { font-size:13px; line-height:1.6; color:#1e293b;
    min-height:260px; max-height:600px; overflow:auto; background:#f8fafc;
    border:1px solid #e8ecf0; border-radius:8px; padding:14px 16px; }
.vai-response p { margin:0 0 9px; }
.vai-response ul, .vai-response ol { padding-left:22px; margin:0 0 9px; }
.vai-response li { margin-bottom:3px; }
.vai-response h1, .vai-response h2, .vai-response h3, .vai-response h4 {
    font-size:14px; font-weight:700; color:#0f172a; margin:14px 0 6px; }
.vai-response h1:first-child, .vai-response h2:first-child, .vai-response h3:first-child { margin-top:0; }
.vai-response code { background:#eef2f7; padding:1px 5px; border-radius:4px; font-size:12px; }
.vai-response pre { background:#eef2f7; padding:10px; border-radius:6px; overflow:auto; }
.vai-response table { width:100%; border-collapse:collapse; margin:0 0 9px; }
.vai-response th, .vai-response td { border:1px solid #e2e8f0; padding:4px 8px; font-size:12px; }
.vai-response em { color:#b45309; }
.vai-recent a { display:block; padding:6px 0; border-bottom:1px solid #f1f5f9; font-size:12px;
    color:#475569; text-decoration:none; }
.vai-recent a:hover { color:#2563eb; }
</style>
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fas fa-robot"></i> @lang('vetAI::lang.clinical_assistant')
        <small>LLM-powered clinical decision support</small>
    </h1>
</section>

<section class="content">

    @unless($settings->isConfigured())
        <div class="callout callout-warning">
            <i class="fa fa-exclamation-triangle"></i> {{ __('vetAI::lang.not_configured') }}
            @can('vet_ai.manage_settings')
                <a href="{{ route('vai.settings.index') }}">Open AI Settings</a>.
            @endcan
        </div>
    @endunless

    <div class="vai-disc">
        <i class="fa fa-shield-alt"></i> <strong>Advisory only.</strong> {{ __('vetAI::lang.disclaimer') }}
    </div>

    <div class="vai-wrap">
        {{-- ── Query form ───────────────────────────────────────── --}}
        <div class="vai-col-form">
            <div class="vai-card">
                <div class="vai-card-h"><i class="fa fa-stethoscope"></i> Case Input</div>
                <div class="vai-card-b">
                    <form id="vai_form">
                        <input type="hidden" id="vai_appointment_id" value="{{ $prefill['appointment_id'] ?? '' }}">
                        <input type="hidden" id="vai_pet_id" value="{{ $prefill['pet_id'] ?? '' }}">

                        @if(!empty($prefill['appointment_ref']))
                            <div class="alert alert-info" style="padding:6px 10px;font-size:12px;">
                                <i class="fa fa-link"></i> Linked to appointment <strong>{{ $prefill['appointment_ref'] }}</strong>
                            </div>
                        @endif

                        {{-- Optional pet lookup --}}
                        <div class="form-group">
                            <label style="font-size:12px;">Load patient from a pet <small class="text-muted">(optional)</small></label>
                            <select id="vai_owner" class="form-control input-sm" style="width:100%"></select>
                            <select id="vai_pet_picker" class="form-control input-sm" style="width:100%;margin-top:5px;">
                                <option value="">— select owner first —</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label style="font-size:12px;">@lang('vetAI::lang.query_type')</label>
                            <div class="vai-qtype">
                                @foreach(['differential','dosage','interaction','education','general'] as $i => $qt)
                                    <label>
                                        <input type="radio" name="query_type" value="{{ $qt }}" {{ $i === 0 ? 'checked' : '' }}>
                                        <span>@lang('vetAI::lang.'.$qt)</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-xs-6 form-group">
                                <label style="font-size:12px;">@lang('vetAI::lang.species')</label>
                                <input type="text" id="vai_species" class="form-control input-sm" value="{{ $prefill['species'] ?? '' }}">
                            </div>
                            <div class="col-xs-6 form-group">
                                <label style="font-size:12px;">@lang('vetAI::lang.breed')</label>
                                <input type="text" id="vai_breed" class="form-control input-sm" value="{{ $prefill['breed'] ?? '' }}">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-4 form-group">
                                <label style="font-size:12px;">@lang('vetAI::lang.age')</label>
                                <input type="text" id="vai_age" class="form-control input-sm" value="{{ $prefill['age'] ?? '' }}">
                            </div>
                            <div class="col-xs-4 form-group">
                                <label style="font-size:12px;">@lang('vetAI::lang.weight')</label>
                                <input type="text" id="vai_weight" class="form-control input-sm" value="{{ $prefill['weight'] ?? '' }}">
                            </div>
                            <div class="col-xs-4 form-group">
                                <label style="font-size:12px;">Sex</label>
                                <input type="text" id="vai_gender" class="form-control input-sm" value="{{ $prefill['gender'] ?? '' }}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label style="font-size:12px;">@lang('vetAI::lang.known_conditions')</label>
                            <input type="text" id="vai_conditions" class="form-control input-sm" value="{{ $prefill['conditions'] ?? '' }}">
                        </div>
                        <div class="form-group">
                            <label style="font-size:12px;" id="vai_details_label">@lang('vetAI::lang.clinical_details')</label>
                            <textarea id="vai_details" class="form-control" rows="5"
                                      placeholder="Describe the presentation / question…">{{ $prefill['details'] ?? '' }}</textarea>
                        </div>

                        <button type="submit" class="btn btn-primary btn-block" id="vai_submit"
                                {{ $settings->isConfigured() ? '' : 'disabled' }}>
                            <i class="fa fa-robot"></i> @lang('vetAI::lang.get_advice')
                        </button>
                    </form>
                </div>
            </div>

            @if($recent->isNotEmpty())
            <div class="vai-card">
                <div class="vai-card-h"><i class="fa fa-history"></i> @lang('vetAI::lang.recent_queries')</div>
                <div class="vai-card-b vai-recent">
                    @foreach($recent as $rq)
                        <a href="#" class="vai-recent-item" data-response="{{ $rq->status === 'success' ? base64_encode(\Modules\VetAI\Entities\VaiQuery::renderMarkdown($rq->response)) : '' }}">
                            <strong>{{ ucfirst($rq->query_type) }}</strong>
                            <span class="text-muted">· {{ optional($rq->created_at)->format('d M H:i') }}</span>
                            @if($rq->status !== 'success')<span class="label label-danger" style="font-size:9px;">error</span>@endif
                        </a>
                    @endforeach
                </div>
            </div>
            @endif
        </div>

        {{-- ── Response ─────────────────────────────────────────── --}}
        <div class="vai-col-out">
            <div class="vai-card">
                <div class="vai-card-h">
                    <i class="fa fa-comment-medical"></i> @lang('vetAI::lang.ai_response')
                    <span class="pull-right text-muted" id="vai_meta" style="font-weight:400;font-size:11px;"></span>
                </div>
                <div class="vai-card-b">
                    <div class="vai-response" id="vai_output"><span class="text-muted">The AI response will appear here. Fill in the case details and click "@lang('vetAI::lang.get_advice')".</span></div>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
$(function () {
    var detailHints = {
        differential: 'List the presenting signs, history and exam findings…',
        dosage:       'Which drug? e.g. "Amoxicillin for this patient"…',
        interaction:  'List the medications / supplements to check…',
        education:    'Which topic should the owner-facing note cover?',
        general:      'Type your clinical question…'
    };
    function applyHint() {
        $('#vai_details').attr('placeholder', detailHints[$('input[name=query_type]:checked').val()] || '');
    }
    $('input[name=query_type]').on('change', applyHint);
    applyHint();

    // Owner -> pet lookup
    $('#vai_owner').select2({
        width: '100%', placeholder: '— search pet owner —', minimumInputLength: 1, allowClear: true,
        ajax: {
            url: '{{ route('vc.pet-owners.search') }}', dataType: 'json', delay: 250,
            data: function (p) { return { q: p.term }; },
            processResults: function (d) { return { results: d }; }
        }
    }).on('select2:select', function (e) {
        $('#vai_pet_picker').html('<option value="">— loading —</option>');
        $.getJSON('{{ url('vet-clinic/pets/by-owner') }}/' + e.params.data.id, function (pets) {
            var html = '<option value="">— select pet —</option>';
            pets.forEach(function (p) { html += '<option value="' + p.id + '">' + p.text + '</option>'; });
            $('#vai_pet_picker').html(html);
        });
    });

    $('#vai_pet_picker').on('change', function () {
        var id = $(this).val();
        if (!id) return;
        $.getJSON('{{ url('vet-ai/assistant/pet') }}/' + id, function (d) {
            $('#vai_pet_id').val(d.pet_id || '');
            $('#vai_species').val(d.species || '');
            $('#vai_breed').val(d.breed || '');
            $('#vai_age').val(d.age || '');
            $('#vai_weight').val(d.weight || '');
            $('#vai_gender').val(d.gender || '');
            $('#vai_conditions').val(d.conditions || '');
        });
    });

    // Recent query -> show its response
    $(document).on('click', '.vai-recent-item', function (e) {
        e.preventDefault();
        var b64 = $(this).data('response');
        if (!b64) { toastr.info('That query returned an error — nothing to show.'); return; }
        $('#vai_output').html(decodeURIComponent(escape(window.atob(b64))));
        $('#vai_meta').text('(from history)');
    });

    // Submit
    $('#vai_form').on('submit', function (e) {
        e.preventDefault();
        var details = $.trim($('#vai_details').val());
        if (!details) { toastr.warning('Enter the clinical details / question.'); return; }

        var $btn = $('#vai_submit').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Thinking…');
        $('#vai_output').html('<span class="text-muted"><i class="fa fa-spinner fa-spin"></i> Contacting the AI model…</span>');
        $('#vai_meta').text('');

        $.post('{{ route('vai.assistant.ask') }}', {
            _token:         '{{ csrf_token() }}',
            query_type:     $('input[name=query_type]:checked').val(),
            appointment_id: $('#vai_appointment_id').val(),
            pet_id:         $('#vai_pet_id').val(),
            species:        $('#vai_species').val(),
            breed:          $('#vai_breed').val(),
            age:            $('#vai_age').val(),
            weight:         $('#vai_weight').val(),
            gender:         $('#vai_gender').val(),
            conditions:     $('#vai_conditions').val(),
            details:        details
        }).done(function (res) {
            if (res.success) {
                $('#vai_output').html(res.response_html || $('<div>').text(res.response || '').html());
                $('#vai_meta').text('~' + res.tokens + ' tokens');
            } else {
                $('#vai_output').html('<span style="color:#dc2626;">' + $('<div>').text(res.msg || 'Failed').html() + '</span>');
            }
        }).fail(function (xhr) {
            var m = (xhr.responseJSON && xhr.responseJSON.msg) ? xhr.responseJSON.msg : 'AI request failed.';
            $('#vai_output').html('<span style="color:#dc2626;">' + $('<div>').text(m).html() + '</span>');
        }).always(function () {
            $btn.prop('disabled', false).html('<i class="fa fa-robot"></i> {{ __('vetAI::lang.get_advice') }}');
        });
    });
});
</script>
@endsection
