<?php

namespace App\Http\Controllers;

use App\Models\ActivityLog;
use App\Models\Family;
use App\Models\FamilyWallPost;
use App\Models\Person;
use App\Models\Subscription;
use App\Models\SubscriptionInvoice;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function __invoke(Request $request)
    {
        $authUser = $request->user();
        $person = $authUser?->person;

        $user = [
            'name' => $authUser?->name ?? 'Guest User',
            'role' => $authUser?->roles->pluck('name')->implode(', ') ?: 'Observer',
            'following' => $authUser?->following_count ?? 0,
            'followers' => $authUser?->followers_count ?? 0,
            'avatar' => $person?->photo_url ?? 'https://ui-avatars.com/api/?name='.urlencode($authUser?->name ?? 'Guest User'),
            'person_id' => $person?->id,
            'completion' => $this->profileCompletion($person),
            'completion_breakdown' => $this->profileCompletionBreakdown($person),
        ];

        $families = Family::query()
            ->withCount('members')
            ->latest('created_at')
            ->take(3)
            ->get()
            ->map(fn (Family $family) => [
                'name' => $family->name,
                'members' => $family->members_count,
                'cover' => $family->settings['cover_photo'] ?? 'https://images.unsplash.com/photo-1524504388940-b1c1722653e1?auto=format&fit=crop&w=1200&q=80',
            ]);

        // Default family to post into: prefer one created by user, otherwise first membership
        $postFamilyId = null;
        if ($authUser) {
            $postFamilyId = Family::query()->where('created_by', $authUser->id)->value('id');
            if (!$postFamilyId && $authUser->person) {
                $postFamilyId = Family::query()
                    ->whereHas('members', fn ($q) => $q->where('person_id', $authUser->person->id))
                    ->value('id');
            }
        }

        $suggestions = Person::query()
            ->latest('created_at')
            ->take(6)
            ->get()
            ->map(fn (Person $person) => [
                'id' => $person->id,
                'name' => trim("{$person->first_name} {$person->last_name}"),
                'relationship' => $person->meta['relationship_hint'] ?? 'Extended Family',
                'avatar' => $person->photo_url ?? 'https://ui-avatars.com/api/?name='.urlencode("{$person->first_name} {$person->last_name}"),
            ]);

        $feed = FamilyWallPost::query()
            ->with(['author', 'family'])
            ->withCount(['comments', 'reactions'])
            ->latest('created_at')
            ->take(5)
            ->get()
            ->map(fn (FamilyWallPost $post) => [
                'id' => $post->id,
                'family_id' => $post->family_id,
                'author' => $post->author?->name ?? 'Unknown Member',
                'avatar' => $post->author?->person?->photo_url ?? 'https://ui-avatars.com/api/?name='.urlencode($post->author?->name ?? 'Member'),
                'time' => optional($post->created_at)->diffForHumans() ?? Carbon::now()->diffForHumans(),
                'privacy' => $post->family?->name ?? 'Family',
                'content' => $post->content,
                'media_list' => is_array($post->media) ? $post->media : [],
                'likes' => $post->reactions_count,
                'comments' => $post->comments_count,
                'reactions' => collect($post->reactions?->pluck('type'))->take(3)->map(function ($type) {
                    return match ($type) {
                        'love' => '❤️',
                        'celebrate' => '🎉',
                        'support' => '🤝',
                        'insightful' => '💡',
                        default => '👍',
                    };
                })->all(),
            ]);

        $timeline = ActivityLog::query()
            ->latest('created_at')
            ->take(5)
            ->get()
            ->map(fn (ActivityLog $log) => [
                'label' => ucwords(str_replace(['.', '_'], [' ', ' '], $log->event)),
                'time' => optional($log->created_at)->diffForHumans() ?? 'Recently',
                'icon' => $this->activityIcon($log->event),
            ]);

        $canSeeOps = $authUser && method_exists($authUser, 'hasRole') ? $authUser->hasRole('admin') : false;
        $metrics = $canSeeOps ? $this->metrics() : [];

        return view('dashboard', compact('user', 'families', 'suggestions', 'feed', 'timeline', 'metrics', 'postFamilyId', 'canSeeOps'));
    }

    private function profileCompletion(?Person $person): int
    {
        if (!$person) {
            return 20;
        }

        $checks = [
            filled($person->first_name),
            filled($person->last_name),
            filled($person->photo_url),
            filled($person->bio),
            filled($person->birth_date),
        ];

        return (int) round((collect($checks)->filter()->count() / count($checks)) * 100);
    }

    private function profileCompletionBreakdown(?Person $person): array
    {
        return [
            ['label' => 'Profile Basics', 'completed' => (int) collect([$person?->first_name, $person?->last_name])->filter()->count(), 'total' => 2],
            ['label' => 'Story & Bio', 'completed' => filled($person?->bio) ? 1 : 0, 'total' => 1],
            ['label' => 'Portrait Photo', 'completed' => filled($person?->photo_url) ? 1 : 0, 'total' => 1],
            ['label' => 'Life Events', 'completed' => filled($person?->birth_date) ? 1 : 0, 'total' => 1],
        ];
    }

    private function metrics(): array
    {
        $activeFamilies = Family::count();
        $activeSubscriptions = Subscription::whereIn('status', ['active', 'trialing', 'pending'])->count();
        $mrrCents = Subscription::query()
            ->whereIn('status', ['active', 'trialing'])
            ->with('plan')
            ->get()
            ->sum(fn (Subscription $subscription) => $subscription->plan?->price_cents ?? 0);

        $recentRevenueCents = SubscriptionInvoice::query()
            ->where('status', 'paid')
            ->where('created_at', '>=', Carbon::now()->subMonth())
            ->sum('amount_cents');

        return [
            ['label' => 'Active Families', 'value' => number_format($activeFamilies), 'change' => '+'.number_format($activeFamilies ?: 0).' this month'],
            ['label' => 'Active Subscriptions', 'value' => number_format($activeSubscriptions), 'change' => 'Across all plans'],
            ['label' => 'Monthly Recurring Revenue', 'value' => '$'.number_format($mrrCents / 100, 2), 'change' => '$'.number_format($recentRevenueCents / 100, 2).' collected last 30d'],
        ];
    }

    private function activityIcon(string $event): string
    {
        return match (true) {
            str_contains($event, 'subscription') => 'autorenew',
            str_contains($event, 'invitation') => 'person_add',
            str_contains($event, 'webhook') => 'sync',
            str_contains($event, 'relationship') => 'favorite',
            default => 'notifications',
        };
    }
}
