<div>
    <x-title>
        Conversion Report
        <x-slot:buttons>
            <button type="button" wire:click="$refresh" class="btn btn-primary btn-sm">
                <i class="mdi mdi-sync me-1"></i> Refresh
            </button>
        </x-slot:buttons>
    </x-title>

    <div class="card mb-4">
        <div class="card-body">
            <div class="row align-items-center g-3">
                <div class="col-12 col-lg">
                    <h4 class="card-title mb-1">Converted Client Master List</h4>
                    <p class="text-muted mb-0">
                        Conversion, redress, APP number and identity-document milestones for every converted client.
                    </p>
                </div>
                <div class="col-12 col-lg-auto">
                    <div class="bg-primary text-white rounded px-4 py-3">
                        <div class="small text-uppercase">
                            {{ $search || $trancheId ? 'Matching Cases' : 'Converted Cases' }}
                        </div>
                        <div class="fs-2 fw-bold">{{ number_format($clients->total()) }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3 align-items-end">
                <div class="col-12 col-lg-6">
                    <label for="conversion-search" class="form-label">Find a Client</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="mdi mdi-magnify"></i></span>
                        <input id="conversion-search"
                               type="search"
                               class="form-control"
                               wire:model.live.debounce.300ms="search"
                               placeholder="Reference, client name or APP number">
                    </div>
                </div>
                <div class="col-12 col-md-7 col-lg-4">
                    <label for="conversion-tranche" class="form-label">Funding Tranche</label>
                    <select id="conversion-tranche" class="form-select" wire:model.live="trancheId">
                        <option value="">All tranches</option>
                        @foreach($tranches as $tranche)
                            <option value="{{ $tranche->id }}">{{ $tranche->tranche_name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12 col-md-5 col-lg-2">
                    <label for="conversion-per-page" class="form-label">Rows</label>
                    <select id="conversion-per-page" class="form-select" wire:model.live="perPage">
                        <option value="25">25</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <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>Reference Number</th>
                        <th>Client Name</th>
                        <th>Conversion Date</th>
                        <th>Date Sent to Redress</th>
                        <th>Initial Call Audit</th>
                        <th>14-Day Cancellation Rights Expiry</th>
                        <th>Estimated APP Number Received Date</th>
                        <th>APP Number Received</th>
                        <th>POA/POI Received</th>
                        <th>Assigned Tranche</th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($rows as $row)
                        @php
                            $estimatedAppOverdue = $row['estimated_app_date']
                                && $row['estimated_app_date']->isPast()
                                && !$row['app_number_received_at'];
                        @endphp
                        <tr wire:key="conversion-row-{{ $row['client']->id }}">
                            <td>
                                <a wire:navigate
                                   href="{{ route('clients.show', $row['client']) }}"
                                   class="fw-bold text-decoration-none">
                                    {{ $row['reference'] }}
                                </a>
                            </td>
                            <td>
                                <div class="fw-semibold">{{ $row['name'] }}</div>
                                @if($savedClientId === $row['client']->id)
                                    <div class="small text-success mt-1">
                                        <i class="mdi mdi-check-circle-outline"></i> Corrections saved
                                    </div>
                                @endif
                                @can('reports.conversions.edit')
                                    <button type="button"
                                            wire:click="edit({{ $row['client']->id }})"
                                            class="btn btn-link btn-sm p-0 mt-1 text-decoration-none">
                                        <i class="mdi mdi-pencil-outline me-1"></i>Edit corrections
                                    </button>
                                @endcan
                            </td>
                            <td>
                                <div class="fw-semibold text-nowrap">{{ $row['conversion_date']->format('d M Y') }}</div>
                                <span class="badge bg-success-subtle text-success mt-1">Converted</span>
                            </td>
                            <td>
                                @if($row['redress_date'])
                                    <div class="fw-semibold text-nowrap">{{ $row['redress_date']->format('d M Y') }}</div>
                                    <div class="small text-muted mt-1">Application emailed</div>
                                @else
                                    <span class="text-muted">Not sent</span>
                                @endif
                            </td>
                            <td>
                                @if($row['audit_passed'] === true)
                                    <span class="badge bg-success-subtle text-success">
                                        <i class="mdi mdi-check-circle-outline me-1"></i>Pass
                                    </span>
                                @elseif($row['audit_passed'] === false)
                                    <span class="badge bg-danger-subtle text-danger">
                                        <i class="mdi mdi-close-circle-outline me-1"></i>Fail
                                    </span>
                                @else
                                    <span class="badge bg-secondary-subtle text-secondary">
                                        <i class="mdi mdi-clock-outline me-1"></i>Pending
                                    </span>
                                @endif
                                @if($row['audit_is_manual'])
                                    <div class="small text-primary mt-1">Manual correction</div>
                                @endif
                            </td>
                            <td>
                                <div class="fw-semibold text-nowrap">{{ $row['cancellation_expiry']->format('d M Y') }}</div>
                                <div class="small text-muted mt-1">
                                    {{ $row['cancellation_expiry']->isFuture() ? $row['cancellation_expiry']->diffForHumans() : 'Expired' }}
                                </div>
                            </td>
                            <td>
                                @if($row['estimated_app_date'])
                                    <div class="fw-semibold text-nowrap {{ $estimatedAppOverdue ? 'text-danger' : '' }}">
                                        {{ $row['estimated_app_date']->format('d M Y') }}
                                    </div>
                                    <div class="small {{ $estimatedAppOverdue ? 'text-danger' : 'text-muted' }} mt-1">
                                        @if($estimatedAppOverdue)
                                            Overdue
                                        @else
                                            {{ $row['estimated_app_days'] }}-day cumulative average
                                        @endif
                                    </div>
                                @else
                                    <span class="text-muted">Awaiting send date</span>
                                @endif
                            </td>
                            <td>
                                @if($row['app_number_received_at'])
                                    <div class="fw-semibold text-nowrap">{{ $row['app_number_received_at']->format('d M Y') }}</div>
                                @elseif($row['app_number'])
                                    <span class="text-warning">Date unavailable</span>
                                @else
                                    <span class="text-muted">Not received</span>
                                @endif
                                @if($row['app_number'])
                                    <div class="small text-muted mt-1">APP: {{ $row['app_number'] }}</div>
                                @endif
                            </td>
                            <td>
                                @if($row['identity_received'])
                                    <span class="badge bg-success-subtle text-success">
                                        <i class="mdi mdi-file-check-outline me-1"></i>Yes
                                    </span>
                                    @if($row['identity_received_at'])
                                        <div class="small text-muted mt-1">{{ $row['identity_received_at']->format('d M Y') }}</div>
                                    @endif
                                @else
                                    <span class="badge bg-warning-subtle text-warning">
                                        <i class="mdi mdi-file-clock-outline me-1"></i>No
                                    </span>
                                @endif
                            </td>
                            <td>
                                @if($row['tranche'])
                                    <span class="badge bg-primary-subtle text-primary">{{ $row['tranche'] }}</span>
                                @else
                                    <span class="text-muted">Unassigned</span>
                                @endif
                            </td>
                        </tr>

                        @if($editingClientId === $row['client']->id)
                            <tr wire:key="conversion-edit-{{ $row['client']->id }}" class="table-light">
                                <td colspan="10">
                                    <form wire:submit="saveCorrections" class="p-3">
                                        <div class="d-flex justify-content-between align-items-start mb-3">
                                            <div>
                                                <h5 class="mb-1">Correct Report Values for {{ $row['name'] }}</h5>
                                                <p class="text-muted small mb-0">
                                                    Blank fields use the automatic system value. Corrections are recorded in client history.
                                                </p>
                                            </div>
                                            <button type="button" wire:click="cancelEdit" class="btn-close" aria-label="Close"></button>
                                        </div>
                                        <div class="row g-3 align-items-end">
                                            <div class="col-12 col-md-5">
                                                <label for="audit-{{ $row['client']->id }}" class="form-label">Initial Call Audit</label>
                                                <select id="audit-{{ $row['client']->id }}"
                                                        class="form-select @error('editInitialAudit') is-invalid @enderror"
                                                        wire:model="editInitialAudit">
                                                    <option value="">Use automatic result</option>
                                                    <option value="pass">Pass</option>
                                                    <option value="fail">Fail</option>
                                                </select>
                                                @error('editInitialAudit') <div class="invalid-feedback">{{ $message }}</div> @enderror
                                            </div>
                                            <div class="col-12 col-md-5">
                                                <label for="app-date-{{ $row['client']->id }}" class="form-label">APP Number Received Date</label>
                                                <input id="app-date-{{ $row['client']->id }}"
                                                       type="date"
                                                       class="form-control @error('editAppNumberReceivedDate') is-invalid @enderror"
                                                       wire:model="editAppNumberReceivedDate">
                                                @error('editAppNumberReceivedDate') <div class="invalid-feedback">{{ $message }}</div> @enderror
                                            </div>
                                            <div class="col-12 col-md-2 d-flex gap-2 justify-content-md-end">
                                                <button type="button" wire:click="cancelEdit" class="btn btn-light">Cancel</button>
                                                <button type="submit" class="btn btn-primary" wire:loading.attr="disabled">
                                                    <span wire:loading.remove wire:target="saveCorrections">Save</span>
                                                    <span wire:loading wire:target="saveCorrections">Saving…</span>
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </td>
                            </tr>
                        @endif
                    @empty
                        <tr>
                            <td colspan="10" class="text-center text-muted py-5">
                                <i class="mdi mdi-file-search-outline d-block fs-2 mb-2"></i>
                                No converted clients found.
                            </td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>

            @if($clients->hasPages())
                <div class="border-top px-4 py-3">
                    {{ $clients->links() }}
                </div>
            @endif
        </div>
    </div>
</div>
