@extends('layouts.admin', ['title' => ($pageTitle ?? 'All Leads') . ' - HIPL CRM'])

@php
    $statusClasses = [
        'new' => 'bg-primary-subtle text-primary',
        'contacted' => 'bg-info-subtle text-info-emphasis',
        'qualified' => 'bg-warning-subtle text-warning-emphasis',
        'closed_won' => 'bg-success-subtle text-success-emphasis',
        'closed_lost' => 'bg-danger-subtle text-danger-emphasis',
    ];
@endphp

@section('content')
<div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3 mb-4">
    <div>
        <h2 class="mb-0 fw-bold">{{ $pageTitle ?? 'All Leads' }}</h2>
        <div class="text-muted">Filter, review, and update lead progress</div>
    </div>

    <a class="btn btn-success rounded-pill px-4" href="{{ route('leads.export', request()->query()) }}">Export CSV</a>
</div>

<div id="lead-status-alert" class="alert d-none mb-3 rounded-4" role="alert"></div>

<div class="card shadow-sm border-0 rounded-4 mb-3">
    <div class="card-body">
        <form class="row g-3" method="GET" action="{{ route('leads.index') }}">
            <div class="col-12 col-md-3">
                <label class="form-label">Website</label>
                <select name="website" class="form-select rounded-4">
                    <option value="">All</option>
                    @foreach($websites as $site)
                        <option value="{{ $site->key }}" @selected(($filters['website'] ?? '') == $site->key)>
                            {{ $site->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-12 col-md-3">
                <label class="form-label">Status</label>
                <select name="status" class="form-select rounded-4">
                    <option value="">All</option>
                    @foreach($statuses as $value => $label)
                        <option value="{{ $value }}" @selected(($filters['status'] ?? '') == $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>

            <div class="col-12 col-md-2">
                <label class="form-label">Month (YYYY-MM)</label>
                <input name="month" value="{{ $filters['month'] ?? '' }}" class="form-control rounded-4" placeholder="2026-01">
            </div>

            <div class="col-12 col-md-2">
                <label class="form-label">Start Date</label>
                <input type="date" name="start_date" value="{{ $filters['start_date'] ?? '' }}" class="form-control rounded-4">
            </div>

            <div class="col-12 col-md-2">
                <label class="form-label">End Date</label>
                <input type="date" name="end_date" value="{{ $filters['end_date'] ?? '' }}" class="form-control rounded-4">
            </div>

            <div class="col-12 d-flex gap-2">
                <button class="btn btn-dark rounded-pill px-4">Apply</button>
                <a class="btn btn-light rounded-pill px-4" href="{{ route('leads.index') }}">Reset</a>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0 rounded-4">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                <tr>
                    <th class="ps-4">#</th>
                    <th>Website</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Details</th>
                    <th>Status</th>
                    <th>Form</th>
                    <th>Created</th>
                </tr>
                </thead>
                <tbody>
                @forelse($leads as $lead)
                    @php
                        $customFields = $lead->displayCustomFields();
                    @endphp
                    <tr>
                        <td class="ps-4 fw-semibold">{{ $lead->id }}</td>
                        <td>{{ $lead->website->name ?? '-' }}</td>
                        <td>{{ $lead->name ?? '-' }}</td>
                        <td>{{ $lead->email ?? '-' }}</td>
                        <td>{{ $lead->phone ?? '-' }}</td>
                        <td style="min-width: 170px;">
                            <button type="button"
                                    class="btn btn-sm btn-outline-primary rounded-pill px-3"
                                    data-bs-toggle="modal"
                                    data-bs-target="#leadDetailsModal{{ $lead->id }}">
                                View Details
                            </button>

                            <div class="modal fade" id="leadDetailsModal{{ $lead->id }}" tabindex="-1" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered modal-lg">
                                    <div class="modal-content border-0 rounded-5 shadow-lg">
                                        <div class="modal-header border-0 pb-0 px-4 pt-4">
                                            <div>
                                                <h5 class="modal-title fw-bold">{{ $lead->name ?: 'Lead #'.$lead->id }}</h5>
                                                <div class="text-muted small">{{ $lead->website->name ?? 'Website' }} • {{ $lead->created_at?->format('Y-m-d H:i') }}</div>
                                            </div>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>

                                        <div class="modal-body px-4 pb-4">
                                            <div class="row g-3 mb-4">
                                                <div class="col-md-4">
                                                    <div class="border rounded-4 p-3 h-100 bg-light-subtle">
                                                        <div class="small text-muted">Name</div>
                                                        <div class="fw-semibold">{{ $lead->name ?? '-' }}</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="border rounded-4 p-3 h-100 bg-light-subtle">
                                                        <div class="small text-muted">Email</div>
                                                        <div class="fw-semibold text-break">{{ $lead->email ?? '-' }}</div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="border rounded-4 p-3 h-100 bg-light-subtle">
                                                        <div class="small text-muted">Phone</div>
                                                        <div class="fw-semibold">{{ $lead->phone ?? '-' }}</div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="d-flex align-items-center justify-content-between mb-3">
                                                <h6 class="fw-semibold mb-0">Custom Fields</h6>
                                                <span class="badge rounded-pill {{ $statusClasses[$lead->status] ?? 'bg-secondary-subtle text-secondary-emphasis' }}">
                                                    {{ $statuses[$lead->status] ?? ucfirst(str_replace('_', ' ', $lead->status)) }}
                                                </span>
                                            </div>

                                            @if($customFields !== [])
                                                <div class="row g-3">
                                                    @foreach($customFields as $label => $value)
                                                        <div class="col-12 col-md-6">
                                                            <div class="border rounded-4 p-3 h-100">
                                                                <div class="small text-muted mb-1">{{ $label }}</div>
                                                                <div class="fw-medium text-break">{{ $value }}</div>
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            @else
                                                <div class="border rounded-4 p-4 text-center text-muted bg-light-subtle">
                                                    No custom fields for this lead.
                                                </div>
                                            @endif

                                            @if($lead->page_url)
                                                <div class="mt-4">
                                                    <div class="small text-muted mb-1">Page URL</div>
                                                    <div class="text-break">{{ $lead->page_url }}</div>
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td style="min-width: 260px;">
                            <div class="d-flex flex-column gap-2">
                                <span class="badge rounded-pill align-self-start lead-status-badge {{ $statusClasses[$lead->status] ?? 'bg-secondary-subtle text-secondary-emphasis' }}"
                                      data-lead-badge="{{ $lead->id }}">
                                    {{ $statuses[$lead->status] ?? ucfirst(str_replace('_', ' ', $lead->status)) }}
                                </span>

                                <form method="POST"
                                      action="{{ route('leads.status', $lead) }}"
                                      class="lead-status-form d-flex gap-2 align-items-center"
                                      data-lead-form
                                      data-lead-id="{{ $lead->id }}">
                                    @csrf
                                    @method('PATCH')
                                    <select name="status"
                                            class="form-select form-select-sm rounded-pill"
                                            data-status-select
                                            aria-label="Update lead status">
                                        @foreach($statuses as $value => $label)
                                            <option value="{{ $value }}"
                                                    data-badge-class="{{ $statusClasses[$value] ?? 'bg-secondary-subtle text-secondary-emphasis' }}"
                                                    data-status-label="{{ $label }}"
                                                    @selected($lead->status === $value)>{{ $label }}</option>
                                        @endforeach
                                    </select>
                                    <button class="btn btn-sm btn-outline-dark rounded-pill d-none d-md-inline-flex" type="submit">
                                        Save
                                    </button>
                                    <span class="small text-muted d-none" data-status-feedback>Saved</span>
                                </form>
                            </div>
                        </td>
                        <td>{{ $lead->source_form ?? '-' }}</td>
                        <td>{{ $lead->created_at?->format('Y-m-d H:i') }}</td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="9" class="text-center text-muted py-5">No leads found.</td>
                    </tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <div class="card-footer bg-white rounded-bottom-4">
        {{ $leads->links() }}
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const alertBox = document.getElementById('lead-status-alert');

        const showAlert = function (message, type) {
            if (!alertBox) {
                return;
            }

            alertBox.textContent = message;
            alertBox.className = 'alert mb-3 rounded-4 alert-' + type;
        };

        const hideAlert = function () {
            if (!alertBox) {
                return;
            }

            alertBox.className = 'alert d-none mb-3 rounded-4';
            alertBox.textContent = '';
        };

        document.querySelectorAll('[data-lead-form]').forEach(function (form) {
            const select = form.querySelector('[data-status-select]');
            const badge = document.querySelector('[data-lead-badge="' + form.dataset.leadId + '"]');
            const feedback = form.querySelector('[data-status-feedback]');
            const submitButton = form.querySelector('button[type="submit"]');

            const setFeedback = function (text, visible) {
                if (!feedback) {
                    return;
                }

                feedback.textContent = text;
                feedback.classList.toggle('d-none', !visible);
            };

            const submitStatus = async function () {
                if (!select) {
                    return;
                }

                hideAlert();

                const selectedOption = select.options[select.selectedIndex];
                const previousValue = select.dataset.previousValue || select.value;

                select.disabled = true;

                if (submitButton) {
                    submitButton.disabled = true;
                }

                setFeedback('Saving...', true);

                try {
                    const response = await window.axios.patch(form.action, {
                        status: select.value
                    }, {
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        }
                    });

                    const payload = response.data;
                    const badgeClass = selectedOption.dataset.badgeClass;
                    const statusLabel = payload.lead?.status_label || selectedOption.dataset.statusLabel || selectedOption.text;

                    if (badge) {
                        badge.className = 'badge rounded-pill align-self-start lead-status-badge ' + badgeClass;
                        badge.textContent = statusLabel;
                    }

                    select.dataset.previousValue = select.value;
                    setFeedback('Saved', true);
                    showAlert(payload.message || 'Lead status updated.', 'success');
                } catch (error) {
                    select.value = previousValue;
                    setFeedback('Failed', true);
                    showAlert(error.response?.data?.message || 'Could not update lead status.', 'danger');
                } finally {
                    select.disabled = false;

                    if (submitButton) {
                        submitButton.disabled = false;
                    }

                    window.setTimeout(function () {
                        setFeedback('', false);
                    }, 1500);
                }
            };

            if (select) {
                select.dataset.previousValue = select.value;

                select.addEventListener('change', function () {
                    submitStatus();
                });
            }

            form.addEventListener('submit', function (event) {
                event.preventDefault();
                submitStatus();
            });
        });
    });
</script>
@endsection
