@extends('layouts.app')

@section('content')

<div class="container-fluid py-4 complaint-list-page">

    <div class="card shadow-lg border-0 rounded-4 overflow-hidden">

        {{-- ===================== HEADER ===================== --}}
        <div class="card-header bg-success text-white">
            <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                <h4 class="mb-0 d-flex align-items-center gap-2">
                    <i class="bi bi-list-check"></i>
                    Complaint List
                </h4>

                <a href="{{ route('complaint.create') }}" class="btn btn-light btn-sm btn-md-normal fw-semibold">
                    <i class="bi bi-plus-circle"></i>
                    <span class="d-none d-sm-inline">New Complaint</span>
                </a>
            </div>
        </div>

        <div class="card-body">

            @if(session('success'))
                <div class="alert alert-success alert-dismissible fade show d-flex align-items-center gap-2" role="alert">
                    <i class="bi bi-check-circle-fill"></i>
                    <div>{{ session('success') }}</div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            @endif

            {{-- ===================== TOOLBAR: SEARCH + FILTER ===================== --}}
            <div class="row g-2 align-items-center mb-3 toolbar">
                <div class="col-12 col-md-6 col-lg-4">
                    <div class="input-group">
                        <span class="input-group-text bg-white"><i class="bi bi-search"></i></span>
                        <input type="text" id="tableSearch" class="form-control" placeholder="Search complainant, CNIC, contact...">
                    </div>
                </div>

                <div class="col-6 col-md-3 col-lg-2">
                    <select id="statusFilter" class="form-select">
                        <option value="">All Status</option>
                        <option value="Resolved">Resolved</option>
                        <option value="Rejected">Rejected</option>
                        <option value="In Progress">In Progress</option>
                        <option value="Pending">Pending</option>
                    </select>
                </div>

                <div class="col-6 col-md-3 col-lg-2 ms-md-auto text-md-end">
                    <span class="badge bg-secondary-subtle text-dark border" id="rowCount"></span>
                </div>
            </div>

            {{-- ===================== TABLE ===================== --}}
            <div class="table-responsive rounded-3 border">
                <table class="table table-hover align-middle mb-0 complaint-table" id="complaintTable">
                    <thead class="table-dark">
                        <tr>
                            <th width="50">#</th>
                            <th width="120" class="text-nowrap">Date</th>
                            <th>Complainant</th>
                            <th>CNIC</th>
                            <th>Contact</th>
                            <th>District</th>
                            <th>Against</th>
                            <th>Status</th>
                            <th>Complaint</th>
                            <th width="160" class="text-center">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        @forelse($complaints as $key=>$row)
                            <tr>
                                <td data-label="#">{{ $complaints->firstItem()+$key }}</td>

                                <td data-label="Date" class="date-cell">
                                    {{ $row->created_at->format('d-M-Y') }}
                                    <br>
                                    <small class="text-muted d-block d-md-inline">{{ $row->created_at->format('h:i A') }}</small>
                                </td>

                                <td data-label="Complainant"><strong>{{ $row->complainant_name }}</strong></td>

                                <td data-label="CNIC">{{ $row->cnic_number }}</td>

                                <td data-label="Contact">{{ $row->contact_number }}</td>

                                <td data-label="District">
                                    @if($row->district)
                                        <span class="badge bg-primary rounded-pill">{{ $row->district->district_name }}</span>
                                    @endif
                                </td>

                                <td data-label="Against">
                                    @if($row->complaintType)
                                        <strong>{{ $row->complaintType->type_name }}</strong>
                                    @endif
                                    <br>
                                    @if($row->complaintAgainst)
                                        <small class="text-muted">{{ $row->complaintAgainst->name }}</small>
                                    @endif
                                </td>

                                <td data-label="Status">
                                    @if($row->latestStatus)
                                        @if($row->latestStatus->status=="Resolved")
                                            <span class="badge bg-success rounded-pill">Resolved</span>
                                        @elseif($row->latestStatus->status=="Rejected")
                                            <span class="badge bg-danger rounded-pill">Rejected</span>
                                        @elseif($row->latestStatus->status=="In Progress")
                                            <span class="badge bg-warning text-dark rounded-pill">In Progress</span>
                                        @else
                                            <span class="badge bg-info rounded-pill">{{ $row->latestStatus->status }}</span>
                                        @endif
                                    @else
                                        <span class="badge bg-secondary rounded-pill">Pending</span>
                                    @endif
                                </td>

                                <td data-label="Complaint" class="complaint-cell">
                                    {{ Str::limit($row->complaint,100) }}
                                </td>

                                <td data-label="Action">
                                    <div class="d-flex flex-nowrap justify-content-center gap-1 action-buttons">

                                        @if(auth()->user()->role=='coordinator')
                                            <form method="POST" action="{{route('complaint.verify',$row->id)}}" class="d-flex gap-1">
                                                @csrf
                                                <button name="action" value="Genuine" class="btn btn-success btn-sm" title="Mark Genuine">
                                                    <i class="bi bi-check-circle"></i>
                                                </button>
                                                <button name="action" value="Irrelevant" class="btn btn-danger btn-sm" title="Mark Irrelevant">
                                                    <i class="bi bi-x-circle"></i>
                                                </button>
                                            </form>
                                        @endif

                                        <a href="{{ route('complaint.edit',$row->id) }}" class="btn btn-sm btn-success" title="Edit">
                                            <i class="bi bi-pencil-square"></i>
                                        </a>

                                        <button class="btn btn-sm btn-warning"
                                                data-bs-toggle="modal"
                                                data-bs-target="#statusModal"
                                                data-id="{{ $row->id }}"
                                                data-name="{{ $row->complainant_name }}"
                                                title="Update Status">
                                            <i class="bi bi-clipboard-check"></i>
                                        </button>

                                        <a href="{{ route('complaint.print',$row->id) }}" class="btn btn-sm btn-primary" title="Print">
                                            <i class="bi bi-printer"></i>
                                        </a>

                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="10" class="text-center text-danger py-4">
                                    <i class="bi bi-inbox display-6 d-block mb-2"></i>
                                    No Complaint Found
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <div class="mt-3 d-flex justify-content-center justify-content-md-end">
                {{ $complaints->links() }}
            </div>

        </div>
    </div>
</div>


<!-- ================= STATUS MODAL ================= -->
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content rounded-4 overflow-hidden">
            <form action="{{ route('complaint.status.store') }}" method="POST">
                @csrf

                <div class="modal-header bg-success text-white">
                    <h5 class="mb-0"><i class="bi bi-clipboard-check me-1"></i> Update Complaint Status</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <input type="hidden" name="complaint_id" id="complaint_id">

                    <div class="mb-3">
                        <label class="fw-bold form-label">Complainant</label>
                        <input type="text" id="complainant_name" class="form-control" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="fw-bold form-label">Status</label>
                        <select name="status" class="form-select" required>
                            <option value="">Select Status</option>
                            <option>Pending</option>
                            <option>Forwarded</option>
                            <option>In Progress</option>
                            <option>Resolved</option>
                            <option>Closed</option>
                            <option>Rejected</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="fw-bold form-label">Remarks</label>
                        <textarea name="remarks" class="form-control" rows="4"></textarea>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-success">
                        <i class="bi bi-save"></i> Save Status
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- ===================== PAGE-SPECIFIC STYLES ===================== --}}
<style>
    .complaint-list-page .card-header h4 { letter-spacing: .3px; }

    .complaint-table thead th {
        white-space: nowrap;
        font-weight: 600;
        font-size: .85rem;
        letter-spacing: .3px;
        position: sticky;
        top: 0;
        z-index: 1;
    }

    .complaint-table tbody tr {
        transition: background-color .15s ease;
    }

    .complaint-table td {
        padding-top: .55rem;
        padding-bottom: .55rem;
        vertical-align: middle;
        line-height: 1.3;
        font-size: .85rem;
    }

    .complaint-table .date-cell {
        white-space: nowrap;
    }

    .complaint-table .date-cell small {
        margin-left: .20rem;
    }

    .complaint-table .complaint-cell {
        max-width: 260px;
        white-space: normal;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .complaint-table .badge {
        font-weight: 500;
        padding: .45em .8em;
    }

    .action-buttons .btn {
        border-radius: 6px;
    }

    #rowCount {
        font-weight: 500;
    }

    /* ---------- Responsive card-style table for small screens ---------- */
    @media (max-width: 767.98px) {
        .complaint-table thead {
            display: none;
        }

        .complaint-table, .complaint-table tbody, .complaint-table tr, .complaint-table td {
            display: block;
            width: 100%;
        }

        .complaint-table tr {
            margin-bottom: 1rem;
            border: 1px solid #e2e2e2;
            border-radius: .75rem;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,.06);
        }

        .complaint-table td {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: .75rem;
            text-align: right;
            padding: .6rem .9rem;
            border: none;
            border-bottom: 1px solid #f1f1f1;
        }

        .complaint-table td:last-child { border-bottom: none; }

        .complaint-table td::before {
            content: attr(data-label);
            font-weight: 600;
            text-align: left;
            color: #6c757d;
            flex-shrink: 0;
        }

        .complaint-table .action-buttons {
            justify-content: flex-end !important;
            width: 100%;
        }

        .complaint-table .complaint-cell {
            max-width: 100%;
        }
    }

    @media (min-width: 576px) {
        .btn-md-normal { padding: .375rem .9rem; }
    }
</style>

{{-- ===================== PAGE-SPECIFIC SCRIPTS ===================== --}}
<script>
    // Status modal population
    const statusModal = document.getElementById('statusModal');
    statusModal.addEventListener('show.bs.modal', function (event) {
        let button = event.relatedTarget;
        document.getElementById('complaint_id').value = button.dataset.id;
        document.getElementById('complainant_name').value = button.dataset.name;
    });

    // Client-side search + status filter (no backend changes required)
    (function () {
        const searchInput = document.getElementById('tableSearch');
        const statusFilter = document.getElementById('statusFilter');
        const rows = Array.from(document.querySelectorAll('#complaintTable tbody tr'));
        const rowCount = document.getElementById('rowCount');

        function applyFilters() {
            const term = (searchInput.value || '').toLowerCase().trim();
            const status = statusFilter.value;
            let visible = 0;

            rows.forEach(row => {
                const text = row.innerText.toLowerCase();
                const matchesSearch = !term || text.includes(term);
                const matchesStatus = !status || text.includes(status.toLowerCase());
                const show = matchesSearch && matchesStatus;
                row.style.display = show ? '' : 'none';
                if (show) visible++;
            });

            rowCount.textContent = visible + ' shown';
        }

        if (rows.length && rows[0].children.length > 1) {
            searchInput.addEventListener('input', applyFilters);
            statusFilter.addEventListener('change', applyFilters);
            applyFilters();
        }
    })();
</script>

@endsection