@extends('layouts.app')

@section('title', 'Activities')

@section('content')
    @php
        $closedStatuses = ['completed', 'done', 'cancelled', 'sent', 'replied'];
        $completedStatuses = ['completed', 'done', 'sent', 'replied'];
        $entryStatus = fn ($entry) => strtolower((string) ($entry->status ?: 'planned'));
        $entryMoment = function ($entry) {
            try { return $entry->date ? \Carbon\Carbon::parse($entry->date) : null; }
            catch (\Throwable) { return null; }
        };
        $completedCount = $entries->filter(fn ($entry) => in_array($entryStatus($entry), $completedStatuses, true))->count();
        $overdueCount = $entries->filter(fn ($entry) => ($moment = $entryMoment($entry)) && $moment->lt(now()) && !in_array($entryStatus($entry), $closedStatuses, true))->count();
        $todayCount = $entries->filter(fn ($entry) => $entryMoment($entry)?->isToday())->count();
        $activeFilterCount = collect(['q', 'type', 'scope', 'owner_id', 'related_record', 'status', 'date_from', 'date_to'])->filter(fn ($key) => request()->filled($key))->count();
        $typeStyles = [
            'call' => ['Call', 'feather-phone', 'primary'],
            'meeting' => ['Meeting', 'feather-calendar', 'info'],
            'email' => ['Email', 'feather-mail', 'success'],
            'message' => ['Message', 'feather-message-circle', 'info'],
            'note' => ['Note', 'feather-file-text', 'secondary'],
            'follow_up' => ['Follow-up', 'feather-repeat', 'warning'],
            'todo' => ['To-do', 'feather-check-square', 'success'],
            'task' => ['Task', 'feather-clipboard', 'primary'],
            'event' => ['Event', 'feather-calendar', 'warning'],
            'activity' => ['Activity', 'feather-activity', 'secondary'],
        ];
    @endphp

    <style>
        .activity-workspace-page { padding-top: 20px; background: #f7f9fc; }
        .activity-workspace-card { border: 1px solid #e4e9f1 !important; border-radius: 15px; background: #fff; box-shadow: 0 9px 28px rgba(15,23,42,.05); overflow: hidden; }
        .activity-workspace-hero { padding: 22px; border: 1px solid #e4e9f1; border-radius: 16px; background: radial-gradient(circle at 90% 10%, rgba(52,84,209,.11), transparent 30%), linear-gradient(135deg,#fff,#f7f9ff); box-shadow: 0 10px 30px rgba(15,23,42,.05); }
        .activity-workspace-icon { display: inline-flex; width: 50px; height: 50px; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 15px; background: linear-gradient(145deg,#3454d1,#5875e5); color: #fff; font-size: 20px; box-shadow: 0 9px 20px rgba(52,84,209,.22); }
        .activity-kpi { position: relative; height: 100%; padding: 16px; border: 1px solid #e6ebf2; border-radius: 13px; background: #fff; overflow: hidden; }
        .activity-kpi:before { position: absolute; top: 0; right: 0; left: 0; height: 3px; background: var(--kpi-color,#3454d1); content: ''; }
        .activity-kpi.kpi-success { --kpi-color:#22a06b; } .activity-kpi.kpi-warning { --kpi-color:#f59e0b; } .activity-kpi.kpi-danger { --kpi-color:#dc3545; }
        .activity-kpi-icon { display: inline-flex; width: 36px; height: 36px; align-items: center; justify-content: center; border-radius: 10px; }
        .activity-kpi small { color: #8490a2; font-size: 10px; font-weight: 750; letter-spacing: .05em; text-transform: uppercase; }
        .activity-filter-card .card-header { padding: 17px 20px; border-bottom: 1px solid #edf0f4; background: #fbfcfe; }
        .activity-filter-card .card-body { padding: 20px; }
        .activity-filter-card .form-label { margin-bottom: 6px; color: #667085; font-size: 10px; font-weight: 750; letter-spacing: .04em; text-transform: uppercase; }
        .activity-filter-card .form-control, .activity-filter-card .form-select { min-height: 41px; border-color: #dce2eb; border-radius: 9px; }
        .activity-filter-search .input-group-text { border-color: #dce2eb; border-radius: 9px 0 0 9px; background: #fff; color: #8792a2; }
        .activity-filter-search .form-control { border-left: 0; }
        .activity-table-card .card-header { padding: 18px 20px; border-bottom: 1px solid #edf0f4; background: #fff; }
        .activity-workspace-table { min-width: 1220px; margin: 0; }
        .activity-workspace-table thead th { padding: 12px 16px; border-bottom: 1px solid #e8ecf2; background: #f8fafc; color: #788497; font-size: 10px; font-weight: 750; letter-spacing: .05em; text-transform: uppercase; white-space: nowrap; }
        .activity-workspace-table tbody td { padding: 14px 16px; border-color: #eef1f5; vertical-align: middle; }
        .activity-workspace-table tbody tr:hover { background: #fbfcff; }
        .activity-type-badge { display: inline-flex; align-items: center; gap: 7px; min-width: 105px; padding: 7px 9px; border-radius: 8px; font-size: 11px; font-weight: 700; }
        .activity-subject { display: block; max-width: 270px; overflow: hidden; color: #263247; font-weight: 700; text-overflow: ellipsis; white-space: nowrap; }
        .activity-source { display: block; margin-top: 3px; color: #98a2b3; font-size: 10px; }
        .activity-owner-avatar { display: inline-flex; width: 30px; height: 30px; align-items: center; justify-content: center; border-radius: 9px; background: #eef2ff; color: #3454d1; font-size: 10px; font-weight: 800; }
        .activity-assignee-list { display: flex; min-width: 150px; max-width: 230px; flex-wrap: wrap; gap: 5px; }
        .activity-assignee-chip { display: inline-flex; align-items: center; gap: 5px; padding: 5px 8px; border-radius: 8px; background: #f0f4ff; color: #3454d1; font-size: 10px; font-weight: 700; }
        .activity-related { display: block; max-width: 175px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .activity-evidence { display: inline-flex; align-items: center; gap: 6px; color: #526176; font-size: 11px; font-weight: 650; }
        .activity-empty-state { padding: 60px 20px !important; text-align: center; }
        .activity-empty-icon { display: inline-flex; width: 54px; height: 54px; align-items: center; justify-content: center; margin-bottom: 13px; border-radius: 16px; background: #eef2ff; color: #3454d1; font-size: 22px; }
        .activity-admin-card .card-header { padding: 16px 20px; background: #fffaf0; border-bottom: 1px solid #f4ead5; }
        .activity-requirement-chip { display: inline-flex; align-items: center; gap: 6px; margin: 5px 5px 0 0; padding: 6px 9px; border-radius: 8px; background: #f6f8fb; color: #667085; font-size: 11px; }
        @media (max-width:767.98px) { .activity-workspace-page { padding-top:12px; } .activity-workspace-hero { padding:17px; } .activity-workspace-actions .btn { flex:1 1 auto; } }
    </style>

    <div class="page-header">
        <div class="page-header-left d-flex align-items-center">
            <div class="page-header-title">
                <h5 class="mb-1">Activities</h5>
                <small class="text-muted d-none d-lg-block">Manage calls, meetings, emails and follow-up work</small>
            </div>
        </div>
        <div class="page-header-right ms-auto">
            <div class="page-header-right-items">
                <div class="d-flex d-md-none"><a href="javascript:void(0)" class="page-header-right-close-toggle"><i class="feather-arrow-left me-2"></i><span>Back</span></a></div>
                <div class="activity-workspace-actions d-flex flex-wrap align-items-center gap-2 page-header-right-items-wrapper">
                    <a class="btn btn-light-brand" href="{{ route('workflow.index', 'follow-ups') }}"><i class="feather-repeat me-1"></i><span>Follow-up</span></a>
                    <a class="btn btn-light-brand" href="{{ route('workflow.index', 'todos') }}"><i class="feather-check-square me-1"></i><span>To-do</span></a>
                    @can('create_activities')
                        <a class="btn btn-primary" href="{{ route('schedule-activity-create') }}"><i class="feather-plus me-1"></i><span>New Activity</span></a>
                    @endcan
                </div>
            </div>
            <div class="d-md-none d-flex align-items-center"><a href="javascript:void(0)" class="page-header-right-open-toggle"><i class="feather-align-right fs-20"></i></a></div>
        </div>
    </div>

    <div class="main-content activity-workspace-page">
        @if(session('success'))<div class="alert alert-success d-flex align-items-center gap-2"><i class="feather-check-circle"></i>{{ session('success') }}</div>@endif

        <section class="activity-workspace-hero mb-4">
            <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3">
                <div class="d-flex align-items-center gap-3"><span class="activity-workspace-icon"><i class="feather-activity"></i></span><div><h4 class="fw-bold mb-1">Activity Workspace</h4><p class="text-muted mb-0">One chronological view of customer engagement and operational follow-through.</p></div></div>
                @if($activeFilterCount)<span class="badge bg-soft-primary text-primary px-3 py-2"><i class="feather-filter me-1"></i>{{ $activeFilterCount }} active {{ Str::plural('filter', $activeFilterCount) }}</span>@endif
            </div>
        </section>

        <div class="row g-3 mb-4">
            <div class="col-6 col-xl-3"><div class="activity-kpi"><div class="d-flex align-items-center justify-content-between"><div><small>Total Records</small><strong class="d-block fs-4 mt-1">{{ $entries->count() }}</strong></div><span class="activity-kpi-icon bg-soft-primary text-primary"><i class="feather-layers"></i></span></div></div></div>
            <div class="col-6 col-xl-3"><div class="activity-kpi kpi-warning"><div class="d-flex align-items-center justify-content-between"><div><small>Scheduled Today</small><strong class="d-block fs-4 mt-1">{{ $todayCount }}</strong></div><span class="activity-kpi-icon bg-soft-warning text-warning"><i class="feather-calendar"></i></span></div></div></div>
            <div class="col-6 col-xl-3"><div class="activity-kpi kpi-success"><div class="d-flex align-items-center justify-content-between"><div><small>Completed</small><strong class="d-block fs-4 mt-1">{{ $completedCount }}</strong></div><span class="activity-kpi-icon bg-soft-success text-success"><i class="feather-check-circle"></i></span></div></div></div>
            <div class="col-6 col-xl-3"><div class="activity-kpi kpi-danger"><div class="d-flex align-items-center justify-content-between"><div><small>Overdue</small><strong class="d-block fs-4 mt-1">{{ $overdueCount }}</strong></div><span class="activity-kpi-icon bg-soft-danger text-danger"><i class="feather-alert-circle"></i></span></div></div></div>
        </div>

        <section class="card activity-workspace-card activity-filter-card mb-4">
            <div class="card-header d-flex align-items-center justify-content-between"><div><h6 class="fw-bold mb-1"><i class="feather-filter me-2 text-primary"></i>Filter Activities</h6><small class="text-muted">Narrow the workspace by type, owner, status or date.</small></div>@if($activeFilterCount)<a class="btn btn-sm btn-light" href="{{ route('schedule-activity') }}"><i class="feather-rotate-ccw me-1"></i>Reset</a>@endif</div>
            <div class="card-body">
                <form method="GET" class="row g-3 align-items-end">
                    <div class="col-lg-4"><label class="form-label">Search</label><div class="input-group activity-filter-search"><span class="input-group-text"><i class="feather-search"></i></span><input name="q" value="{{ request('q') }}" class="form-control" placeholder="Search subject, related record or source"></div></div>
                    <div class="col-sm-6 col-lg-2"><label class="form-label">Activity Type</label><select name="type" class="form-select"><option value="">All types</option>@foreach(['call'=>'Calls','meeting'=>'Meetings','task'=>'Tasks','email'=>'Emails','message'=>'Messages','note'=>'Notes','follow_up'=>'Follow-ups','todo'=>'To-do Items'] as $key=>$label)<option value="{{ $key }}" @selected(request('type')===$key)>{{ $label }}</option>@endforeach</select></div>
                    <div class="col-sm-6 col-lg-2"><label class="form-label">Activity View</label><select name="scope" class="form-select"><option value="">All Visible</option><option value="mine" @selected(request('scope')==='mine')>Owned by Me</option><option value="team" @selected(request('scope')==='team')>My Team</option><option value="assigned" @selected(request('scope')==='assigned')>Assigned to Me</option></select></div>
                    <div class="col-sm-6 col-lg-2"><label class="form-label">Owner</label><select name="owner_id" class="form-select"><option value="">All owners</option>@foreach($users as $user)<option value="{{ $user->id }}" @selected((string)request('owner_id')===(string)$user->id)>{{ $user->name }}</option>@endforeach</select></div>
                    <div class="col-sm-6 col-lg-2"><label class="form-label">Status</label><select name="status" class="form-select"><option value="">All statuses</option>@foreach(['planned'=>'Planned','open'=>'Open','in_progress'=>'In Progress','completed'=>'Completed','cancelled'=>'Cancelled','sent'=>'Sent','replied'=>'Replied'] as $key=>$label)<option value="{{ $key }}" @selected(request('status')===$key)>{{ $label }}</option>@endforeach</select></div>
                    <div class="col-sm-6 col-lg-2"><label class="form-label">Related Record ID</label><input name="related_record" type="number" min="1" value="{{ request('related_record') }}" class="form-control" placeholder="Record ID"></div>
                    <div class="col-sm-6 col-lg-3"><label class="form-label">Date From</label><input name="date_from" type="date" value="{{ request('date_from') }}" class="form-control"></div>
                    <div class="col-sm-6 col-lg-3"><label class="form-label">Date To</label><input name="date_to" type="date" value="{{ request('date_to') }}" class="form-control"></div>
                    <div class="col-lg-6 d-flex justify-content-lg-end gap-2"><a class="btn btn-light" href="{{ route('schedule-activity') }}">Clear</a><button class="btn btn-primary"><i class="feather-check me-1"></i>Apply Filters</button></div>
                </form>
            </div>
        </section>

        @if(auth()->user()->is_admin)
            <section class="card activity-workspace-card activity-admin-card mb-4">
                <div class="card-header d-flex align-items-center justify-content-between" role="button" data-bs-toggle="collapse" data-bs-target="#activityEvidenceRules" aria-expanded="false"><div><h6 class="fw-bold mb-1"><i class="feather-shield me-2 text-warning"></i>Attachment Evidence Rules</h6><small class="text-muted">Administrative controls for required activity evidence.</small></div><i class="feather-chevron-down"></i></div>
                <div class="collapse" id="activityEvidenceRules"><div class="card-body p-4"><form method="POST" action="{{ route('activities.attachment-requirements.store') }}" class="row g-3 align-items-end">@csrf<div class="col-md-3"><label class="form-label">Activity Type</label><select class="form-select" name="activity_type"><option value="call">Call</option><option value="meeting">Meeting</option><option value="email">Email</option></select></div><div class="col-md-3"><label class="form-label">Outcome</label><select class="form-select" name="outcome"><option value="">Any outcome</option><option value="interested">Interested</option><option value="follow_up_required">Follow-up required</option><option value="not_interested">Not interested</option></select></div><div class="col-md-3"><label class="form-check mb-2"><input class="form-check-input" type="checkbox" name="required" value="1" checked><span class="form-check-label">Require attachment</span></label></div><div class="col-md-3"><button class="btn btn-outline-primary w-100">Save Rule</button></div></form>@if($attachmentRequirements->isNotEmpty())<div class="mt-3">@foreach($attachmentRequirements as $requirement)<span class="activity-requirement-chip"><i class="feather-paperclip"></i>{{ ucfirst($requirement->activity_type) }} · {{ $requirement->outcome ? ucwords(str_replace('_',' ',$requirement->outcome)) : 'Any outcome' }} · {{ $requirement->required ? 'Required' : 'Optional' }}</span>@endforeach</div>@endif</div></div>
            </section>
        @endif

        <section class="card activity-workspace-card activity-table-card mb-4">
            <div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2"><div><h6 class="fw-bold mb-1">Activity Timeline</h6><small class="text-muted">{{ $entries->count() }} {{ Str::plural('record', $entries->count()) }} in the current view</small></div><span class="badge bg-soft-primary text-primary">Newest first</span></div>
            <div class="table-responsive">
                <table class="table activity-workspace-table align-middle">
                    <thead><tr><th>Type</th><th>Subject</th><th>Related Record</th><th>Owner / User</th><th>Assigned Employees</th><th>When</th><th>Status</th><th>Evidence</th><th class="text-end">Action</th></tr></thead>
                    <tbody>
                        @forelse($entries as $entry)
                            @php
                                [$typeLabel, $typeIcon, $typeColor] = $typeStyles[$entry->type] ?? [ucwords(str_replace('_',' ',$entry->type)), 'feather-activity', 'secondary'];
                                $status = $entryStatus($entry);
                                $moment = $entryMoment($entry);
                                $isOverdue = $moment?->lt(now()) && !in_array($status, $closedStatuses, true);
                                $statusLabel = $isOverdue ? 'Overdue' : ucwords(str_replace('_',' ',$status));
                                $statusColor = $isOverdue ? 'danger' : match($status) { 'completed','done','sent','replied' => 'success', 'cancelled' => 'secondary', 'open','in_progress' => 'warning', default => 'primary' };
                                $ownerName = $entry->ownerId ? ($users->firstWhere('id',$entry->ownerId)?->name ?? 'Former user') : 'Unassigned';
                            @endphp
                            <tr>
                                <td><span class="activity-type-badge bg-soft-{{ $typeColor }} text-{{ $typeColor }}"><i class="{{ $typeIcon }}"></i>{{ $typeLabel }}</span></td>
                                <td><a href="{{ $entry->editUrl }}" class="activity-subject">{{ $entry->title }}</a><small class="activity-source">{{ $entry->source }}</small></td>
                                <td><span class="activity-related" title="{{ $entry->related }}">{{ $entry->related }}</span></td>
                                <td><div class="d-flex align-items-center gap-2"><span class="activity-owner-avatar">{{ strtoupper(substr($ownerName,0,2)) }}</span><span class="text-nowrap">{{ $ownerName }}</span></div></td>
                                <td><div class="activity-assignee-list">@forelse($entry->assignedNames as $assignedName)<span class="activity-assignee-chip"><i class="feather-user-check"></i>{{ $assignedName }}</span>@empty<span class="text-muted">Unassigned</span>@endforelse</div></td>
                                <td><strong class="d-block text-dark text-nowrap">{{ $moment?->format('d M Y') ?: 'Not scheduled' }}</strong>@if($moment)<small class="text-muted">{{ $moment->format('h:i A') }}</small>@endif</td>
                                <td><span class="badge bg-soft-{{ $statusColor }} text-{{ $statusColor }}">{{ $statusLabel }}</span></td>
                                <td>@if($entry->filesUrl)<a href="{{ $entry->filesUrl }}" class="activity-evidence"><i class="feather-paperclip"></i>{{ $entry->filesCount }} {{ Str::plural('file',$entry->filesCount) }}</a>@else<span class="text-muted">—</span>@endif</td>
                                <td class="text-end"><a class="avatar-text avatar-md bg-soft-primary text-primary ms-auto" href="{{ $entry->editUrl }}" title="Open or edit" aria-label="Open or edit"><i class="feather-arrow-up-right"></i></a></td>
                            </tr>
                        @empty
                            <tr><td colspan="9" class="activity-empty-state"><span class="activity-empty-icon"><i class="feather-inbox"></i></span><h6 class="fw-bold mb-1">No activities found</h6><p class="text-muted mb-3">No records match the selected filters.</p><a class="btn btn-sm btn-light" href="{{ route('schedule-activity') }}">Clear Filters</a></td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </section>
    </div>
@endsection
