@extends('admin.layouts.app')

@section('title', 'FMP CORE - Edit Mapping')

@section('breadcrumbs')
    <i class="fa-solid fa-chevron-right mx-3 text-[8px]"></i>
    <span class="text-slate-900">Account Lawyer Mapping</span>
    <i class="fa-solid fa-chevron-right mx-3 text-[8px]"></i>
    <span class="text-slate-900">Edit Mapping</span>
@endsection

@push('styles')
<style>
    .page {
        width: 100%; max-width: 100%; background: #ffffff; border-radius: 24px;
        box-shadow: 0 22px 60px rgba(15, 23, 42, 0.16); padding: 28px 32px 32px; border: 1px solid #e2e8f0;
    }
    .page-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 24px; }
    .page-title { font-size: 18px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase; color: #0f172a; }
    .page-subtitle { font-size: 13px; color: #64748b; }
    .layout { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(0, 1.85fr); gap: 28px; align-items: flex-start; }
    .form-scroll { max-height: calc(100vh - 260px); overflow-y: auto; padding-right: 6px; }
    .field-group { margin-bottom: 14px; }
    .field-label { display: block; font-size: 13px; font-weight: 600; color: #475569; margin-bottom: 6px; }
    .field-label span { color: #d63031; }
    .input-text {
        width: 100%; border-radius: 14px; border: 1px solid #cbd5e1; padding: 10px 14px;
        font-size: 14px; outline: none; background: #ffffff; transition: border-color 0.15s ease, box-shadow 0.15s ease;
    }
    .input-text:focus { border-color: #00ada8; box-shadow: 0 0 0 3px rgba(0, 173, 168, 0.16); background: #f8fafc; }
    .input-text::placeholder { color: #94a3b8; }
    .btn {
        border: none; border-radius: 999px; padding: 10px 30px; font-size: 14px; font-weight: 500;
        cursor: pointer; transition: all 0.15s ease; white-space: nowrap;
    }
    .btn-primary {
        background: radial-gradient(circle at top left, #00ada8 0%, #007d79 100%);
        color: #ffffff; box-shadow: 0 10px 25px rgba(0, 173, 168, 0.35);
    }
    .btn-primary:hover { transform: translateY(-1px); }
    .btn-primary:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
    .btn-secondary { background: #ffffff; color: #64748b; border: 2px solid #e2e8f0; }
    .btn-secondary:hover { background: #f8fafc; }
    .result-panel {
        background: linear-gradient(135deg, #ffffff 0%, #f0fdfa 100%); border-radius: 18px;
        border: 1px solid #e2e8f0; padding: 22px; min-height: 260px; display: flex; flex-direction: column; gap: 14px;
        max-height: calc(100vh - 260px); overflow-y: auto;
    }
    .summary-card {
        background: #ffffff; border-radius: 16px; padding: 20px 24px; border: 2px solid #e2e8f0;
        box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08); transition: all 0.3s ease;
    }
    .summary-card:hover { border-color: #00ada8; transform: translateY(-2px); }
    .summary-header { display: flex; justify-content: space-between; align-items: flex-start; }
    .summary-title { font-size: 14px; font-weight: 800; color: #0f172a; margin-bottom: 6px; }
    .summary-title span { color: #00ada8; font-weight: 900; }
    .summary-meta { font-size: 13px; color: #64748b; font-weight: 500; }
    .summary-meta span { color: #1e293b; font-weight: 700; }
    .detail-btn {
        display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px;
        background: linear-gradient(135deg, #00ada8 0%, #007d79 100%); color: white; border-radius: 20px;
        font-size: 11px; font-weight: 700; text-transform: uppercase; border: none; cursor: pointer;
    }
    .lawyer-chip {
        background: #f0fdfb; border: 1.5px solid #99f6e4; border-radius: 14px; padding: 14px 16px;
        display: flex; align-items: flex-start; gap: 12px; position: relative; margin-bottom: 10px;
    }
    .lawyer-chip .remove-btn {
        position: absolute; top: 8px; right: 8px; width: 22px; height: 22px; border-radius: 50%;
        background: #fee2e2; color: #b91c1c; border: none; cursor: pointer; font-size: 10px;
        display: flex; align-items: center; justify-content: center;
    }
    .lawyer-chip .remove-btn:hover { background: #fecaca; }
    .lawyer-avatar {
        width: 44px; height: 44px; border-radius: 12px; background: #00ada8;
        color: #fff; font-size: 14px; font-weight: 800; display: flex; align-items: center;
        justify-content: center; flex-shrink: 0;
    }
    .actions-row {
        display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;
        padding-top: 20px; border-top: 1px solid #e2e8f0;
    }
    /* Lawyer search in edit */
    .add-lawyer-section { margin-top: 8px; }
    .search-row { display: flex; gap: 8px; }
    .search-input {
        flex: 1; border-radius: 999px; border: 1px solid #cbd5e1; padding: 8px 14px;
        font-size: 13px; outline: none;
    }
    .search-input:focus { border-color: #00ada8; box-shadow: 0 0 0 3px rgba(0,173,168,0.16); }
    .btn-sm { padding: 8px 20px; font-size: 12px; }
    .suggestions-box {
        margin-top: 6px; border-radius: 12px; border: 1.5px solid #e2e8f0; background: #fff;
        box-shadow: 0 8px 24px rgba(15,23,42,0.10); max-height: 200px; overflow-y: auto; display: none;
    }
    .sug-item { padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #f8fafc; font-size: 12px; }
    .sug-item:hover { background: #f0fdfb; }
    .alert-error {
        background: #fef2f2; border: 1px solid #fecaca; border-radius: 10px; padding: 10px 14px;
        color: #b91c1c; font-size: 11px; font-weight: 500; display: none; margin-top: 8px;
    }
    @media (max-width: 900px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
@endpush

@section('content')
    <div class="page">
        <header class="page-header">
            <div>
                <h1 class="page-title">Edit Account – Lawyer Mapping</h1>
                <p class="page-subtitle">Update case details and manage lawyer assignments.</p>
            </div>
        </header>

        <section class="layout">
            <!-- Left: Case details form -->
            <form id="editForm" class="form-scroll">
                <div class="field-group">
                    <label class="field-label" for="assignDate">Assign Date <span>*</span></label>
                    <input type="date" id="assignDate" class="input-text" value="{{ $mapping->assign_date?->format('Y-m-d') }}" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="submittedDate">Case Submitted Date <span>*</span></label>
                    <input type="date" id="submittedDate" class="input-text" value="{{ $mapping->case_submitted_date?->format('Y-m-d') }}" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="registrationVia">Case Registration Via <span>*</span></label>
                    <input type="text" id="registrationVia" class="input-text" value="{{ $mapping->case_registration_via }}" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="courtFee">Court Fee <span>*</span></label>
                    <input type="number" step="0.001" id="courtFee" class="input-text" value="{{ $mapping->court_fee }}" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="caseFiledDate">Case Filed Date <span>*</span></label>
                    <input type="date" id="caseFiledDate" class="input-text" value="{{ $mapping->case_filed_date?->format('Y-m-d') }}" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="remarks">Internal Remarks</label>
                    <textarea id="remarks" rows="3" class="input-text" style="border-radius:16px;resize:none;">{{ $mapping->internal_remarks }}</textarea>
                </div>
            </form>

            <!-- Right: Summary & lawyers -->
            <aside class="result-panel">
                <!-- Account summary (read-only in edit) -->
                <section class="summary-card">
                    <header class="summary-header">
                        <div class="flex-1">
                            <div class="summary-title">Account No (Loan ID): <span>{{ $mapping->loan_id }}</span></div>
                            <div class="summary-meta mt-1">Account Name: <span>{{ $mapping->customer_name }}</span></div>
                        </div>
                        <button class="detail-btn" type="button">
                            <i class="fa-solid fa-circle-check text-[10px]"></i> Account Details
                        </button>
                    </header>
                </section>

                <!-- Lawyers -->
                <div id="lawyersContainer"></div>

                <!-- Add lawyer -->
                <div class="add-lawyer-section">
                    <label class="field-label">Add Lawyer</label>
                    <div class="search-row">
                        <input type="text" id="lawyerSearchInput" class="search-input" placeholder="Search by code or name..." autocomplete="off" />
                        <button type="button" id="btnAddSearch" class="btn btn-primary btn-sm">Search</button>
                    </div>
                    <div id="suggestions" class="suggestions-box"></div>
                    <div id="alertError" class="alert-error"><i class="fa-solid fa-circle-exclamation mr-1"></i> <span id="alertErrorMsg"></span></div>
                </div>

                <div class="actions-row">
                    <button type="button" class="btn btn-secondary" onclick="window.location.href='{{ route('admin.account-lawyer.index') }}'">Cancel</button>
                    <button type="button" class="btn btn-primary" id="btnSave">Save Changes</button>
                </div>
            </aside>
        </section>
    </div>
@endsection

@push('scripts')
<script>
    const CSRF_TOKEN     = '{{ csrf_token() }}';
    const UPDATE_URL     = '{{ route("admin.account-lawyer.update", $mapping->id) }}';
    const INDEX_URL      = '{{ route("admin.account-lawyer.index") }}';
    const LAW_FIRM_URL   = '{{ route("admin.oracle.law-firms") }}';
    const CHECK_USER_URL = '{{ route("admin.oracle.check-lawyer-user") }}';

    let lawyers = @json($mapping->lawyers->map(fn($l) => [
        'id' => $l->law_firm_id,
        'name' => $l->law_firm_name,
        'address' => $l->address,
        'email' => $l->email,
        'mobile' => $l->mobile,
        'user_id' => $l->user_id,
    ]));

    function escapeJs(str) { return (str||'').replace(/\\/g,'\\\\').replace(/'/g,"\\'"); }

    function renderLawyers() {
        const container = document.getElementById('lawyersContainer');
        container.innerHTML = lawyers.map(l => {
            const initials = (l.name || 'L').split(' ').map(w => w[0]).join('').substring(0,2).toUpperCase();
            return `<div class="lawyer-chip">
                <button class="remove-btn" onclick="removeLawyer('${escapeJs(l.id)}')" title="Remove"><i class="fa-solid fa-xmark"></i></button>
                <div class="lawyer-avatar">${initials}</div>
                <div style="flex:1;min-width:0;">
                    <div style="font-size:13px;font-weight:800;color:#0f766e;">${l.name || ''}</div>
                    <div style="font-size:11px;color:#475569;margin-top:2px;"><strong>Code:</strong> ${l.id || ''}</div>
                    ${l.address ? `<div style="font-size:11px;color:#64748b;margin-top:1px;"><strong>Address:</strong> ${l.address}</div>` : ''}
                </div>
            </div>`;
        }).join('');
    }
    renderLawyers();

    function removeLawyer(id) {
        lawyers = lawyers.filter(l => l.id !== id);
        renderLawyers();
    }

    // Search & add lawyer
    const searchInput = document.getElementById('lawyerSearchInput');
    const sugBox      = document.getElementById('suggestions');
    const alertError  = document.getElementById('alertError');

    document.getElementById('btnAddSearch').addEventListener('click', doSearch);
    searchInput.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); doSearch(); } });

    async function doSearch() {
        const q = searchInput.value.trim();
        if (!q) return;
        alertError.style.display = 'none';
        sugBox.innerHTML = '<div style="padding:10px;font-size:11px;color:#94a3b8;text-align:center;"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Searching...</div>';
        sugBox.style.display = 'block';

        try {
            const res  = await fetch(LAW_FIRM_URL + '?q=' + encodeURIComponent(q), { headers: { 'Accept': 'application/json' } });
            const json = await res.json();
            if (!json.success || !json.data?.length) {
                sugBox.innerHTML = '<div style="padding:10px;font-size:11px;color:#94a3b8;text-align:center;">No results</div>';
                return;
            }
            const selectedIds = lawyers.map(l => l.id);
            sugBox.innerHTML = json.data.map(f => {
                const already = selectedIds.includes(f.id);
                return `<div class="sug-item ${already ? 'opacity-50' : ''}" ${already ? '' : `onclick="addLawyer('${escapeJs(f.id)}','${escapeJs(f.name)}','${escapeJs(f.address)}','${escapeJs(f.email)}','${escapeJs(f.mobile)}')"`}>
                    <strong style="color:#0f766e;">${f.id}</strong> — ${f.name}
                    ${already ? '<span style="color:#00ada8;font-size:10px;margin-left:6px;">Selected</span>' : ''}
                </div>`;
            }).join('');
        } catch (e) {
            sugBox.innerHTML = '<div style="padding:10px;font-size:11px;color:#ef4444;text-align:center;">Connection error</div>';
        }
    }

    async function addLawyer(id, name, address, email, mobile) {
        if (lawyers.find(l => l.id === id)) return;
        sugBox.style.display = 'none';
        searchInput.value = '';
        alertError.style.display = 'none';

        try {
            const res  = await fetch(CHECK_USER_URL + '?law_firm_id=' + encodeURIComponent(id), { headers: { 'Accept': 'application/json' } });
            const json = await res.json();
            if (!json.exists) {
                alertError.style.display = 'block';
                document.getElementById('alertErrorMsg').textContent = json.message || 'Lawyer not registered as portal user.';
                return;
            }
            lawyers.push({ id, name, address, email, mobile, user_id: json.user?.id || null });
            renderLawyers();
        } catch (e) {
            alertError.style.display = 'block';
            document.getElementById('alertErrorMsg').textContent = 'Error verifying lawyer.';
        }
    }

    document.addEventListener('click', e => { if (!e.target.closest('.add-lawyer-section')) sugBox.style.display = 'none'; });

    // Save
    document.getElementById('btnSave').addEventListener('click', async () => {
        const form = document.getElementById('editForm');
        if (!form.reportValidity()) return;
        if (lawyers.length === 0) { alert('At least one lawyer is required.'); return; }

        const btn = document.getElementById('btnSave');
        btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i> Saving...';

        const payload = new FormData();
        payload.append('_token', CSRF_TOKEN);
        payload.append('_method', 'PUT');
        payload.append('assign_date',           document.getElementById('assignDate').value);
        payload.append('case_submitted_date',   document.getElementById('submittedDate').value);
        payload.append('case_registration_via', document.getElementById('registrationVia').value);
        payload.append('court_fee',             document.getElementById('courtFee').value);
        payload.append('case_filed_date',       document.getElementById('caseFiledDate').value);
        payload.append('internal_remarks',      document.getElementById('remarks').value);
        payload.append('lawyers',               JSON.stringify(lawyers));

        try {
            const res  = await fetch(UPDATE_URL, { method: 'POST', body: payload, headers: { 'Accept': 'application/json' } });
            const data = await res.json();
            if (data.success) {
                window.location.href = INDEX_URL;
            } else {
                const err = data.errors ? Object.values(data.errors)[0]?.[0] : (data.message || 'Something went wrong.');
                alert(err);
            }
        } catch (e) { alert('Request failed.'); }
        finally { btn.disabled = false; btn.innerHTML = 'Save Changes'; }
    });
</script>
@endpush
