<?php

namespace App\Http\Controllers;

use App\Models\Campaign;
use App\Models\CampaignEvent;
use App\Models\Contact;
use App\Models\ContactList;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Inertia\Inertia;
use Inertia\Response;

class AudienceController extends Controller
{
    public function index(Request $request): Response
    {
        $totalContacts = Contact::count();
        $subscribed = Contact::where('status', 'subscribed')->count();
        $unsubscribed = Contact::where('status', 'unsubscribed')->count();
        $bounced = Contact::where('status', 'bounced')->count();

        // Plan limit note (assuming 100k limit)
        $limit = 100000;
        $pctLimit = $limit > 0 ? min(100, round(($totalContacts / $limit) * 100)) : 0;
        $pctSubscribed = $totalContacts > 0 ? min(100, round(($subscribed / $totalContacts) * 100)) : 0;
        $pctUnsubscribed = $totalContacts > 0 ? min(100, round(($unsubscribed / $totalContacts) * 100)) : 0;
        $pctBounced = $totalContacts > 0 ? min(100, round(($bounced / $totalContacts) * 100)) : 0;

        // Health meters data
        $spamCount = CampaignEvent::where('event_type', 'spam')->count();
        $pctSpam = $totalContacts > 0 ? min(100, round(($spamCount / $totalContacts) * 100)) : 0;

        $healthMeters = [
            ['label' => 'Subscribed', 'value' => $pctSubscribed, 'color' => '#16a34a', 'count' => number_format($subscribed)],
            ['label' => 'Unsubscribed', 'value' => $pctUnsubscribed, 'color' => '#d97706', 'count' => number_format($unsubscribed)],
            ['label' => 'Bounced', 'value' => $pctBounced, 'color' => '#ef4444', 'count' => number_format($bounced)],
            ['label' => 'Spam complaints', 'value' => $pctSpam, 'color' => '#7c3aed', 'count' => number_format($spamCount)],
        ];

        // Top lists
        $topListsRaw = ContactList::withCount('contacts')
            ->orderByDesc('contacts_count')
            ->take(5)
            ->get();

        $topLists = $topListsRaw->map(function ($list) use ($totalContacts) {
            $growth = $totalContacts > 0 ? round(($list->contacts_count / $totalContacts) * 100) : 0;
            return [
                'name' => $list->title,
                'count' => number_format($list->contacts_count),
                'growth' => "+{$growth}%",
                'growthUp' => true,
                'color' => $list->color || '#4285F4',
            ];
        });

        // Stats card layout data
        $stats = [
            [
                'label' => 'Total Contacts',
                'value' => number_format($totalContacts),
                'icon' => 'pi pi-users',
                'color' => '#4285F4',
                'bg' => '#eff6ff',
                'pct' => $pctLimit,
                'note' => "{$pctLimit}% of " . number_format($limit) . " plan limit",
                'trend' => '+0.0%',
                'trendUp' => true
            ],
            [
                'label' => 'Active Subscribers',
                'value' => number_format($subscribed),
                'icon' => 'pi pi-check-circle',
                'color' => '#16a34a',
                'bg' => '#f0fdf4',
                'pct' => $pctSubscribed,
                'note' => "{$pctSubscribed}% of total contacts",
                'trend' => '+0.0%',
                'trendUp' => true
            ],
            [
                'label' => 'Unsubscribed',
                'value' => number_format($unsubscribed),
                'icon' => 'pi pi-sign-out',
                'color' => '#d97706',
                'bg' => '#fffbeb',
                'pct' => $pctUnsubscribed,
                'note' => "{$pctUnsubscribed}% unsubscribe rate",
                'trend' => '+0.0%',
                'trendUp' => false
            ],
            [
                'label' => 'Hard Bounced',
                'value' => number_format($bounced),
                'icon' => 'pi pi-exclamation-triangle',
                'color' => '#ef4444',
                'bg' => '#fef2f2',
                'pct' => $pctBounced,
                'note' => "{$pctBounced}% hard bounce rate",
                'trend' => '+0.0%',
                'trendUp' => false
            ],
        ];

        // Campaign metrics
        $emailsSent = (int) Campaign::sum('emails_sent');
        $uniqueOpens = (int) Campaign::sum('unique_opens');
        $uniqueClicks = (int) Campaign::sum('unique_clicks');
        $unsubscribes = (int) Campaign::sum('unsubscribes_count');

        $openRate = $emailsSent > 0 ? round(($uniqueOpens / $emailsSent) * 100, 1) : 0.0;
        $clickRate = $emailsSent > 0 ? round(($uniqueClicks / $emailsSent) * 100, 1) : 0.0;
        $unsubscribeRate = $emailsSent > 0 ? round(($unsubscribes / $emailsSent) * 100, 1) : 0.0;

        $engagementMetrics = [
            ['label' => 'Emails Sent', 'value' => number_format($emailsSent), 'color' => '#4285F4', 'bg' => '#eff6ff', 'icon' => 'pi pi-send', 'change' => '+0.0%', 'up' => true],
            ['label' => 'Open Rate', 'value' => "{$openRate}%", 'color' => '#16a34a', 'bg' => '#f0fdf4', 'icon' => 'pi pi-envelope-open', 'change' => '+0.0%', 'up' => true],
            ['label' => 'Click Rate', 'value' => "{$clickRate}%", 'color' => '#2563eb', 'bg' => '#eff6ff', 'icon' => 'pi pi-arrow-up-right', 'change' => '+0.0%', 'up' => true],
            ['label' => 'Unsubscribe Rate', 'value' => "{$unsubscribeRate}%", 'color' => '#d97706', 'bg' => '#fffbeb', 'icon' => 'pi pi-sign-out', 'change' => '0.0%', 'up' => false],
            ['label' => 'Spam Rate', 'value' => '0.0%', 'color' => '#16a34a', 'bg' => '#f0fdf4', 'icon' => 'pi pi-shield', 'change' => '0.0%', 'up' => true],
        ];

        // Growth Chart over last 12 months
        $months = [];
        $netGrowth = [];
        $newAdds = [];
        $churned = [];

        for ($i = 11; $i >= 0; $i--) {
            $monthStart = now()->subMonths($i)->startOfMonth();
            $monthEnd = now()->subMonths($i)->endOfMonth();

            $months[] = $monthStart->format('M');

            $added = Contact::whereBetween('created_at', [$monthStart, $monthEnd])->count();
            $removed = Contact::whereBetween('updated_at', [$monthStart, $monthEnd])
                ->where('status', 'unsubscribed')
                ->count();

            $newAdds[] = $added;
            $churned[] = $removed;
            $netGrowth[] = $added - $removed;
        }

        $growthChartData = [
            'labels' => $months,
            'datasets' => [
                [
                    'label' => 'Net growth',
                    'data' => $netGrowth,
                    'borderColor' => '#4285F4',
                    'backgroundColor' => 'rgba(66,133,244,0.08)',
                    'borderWidth' => 2.5,
                    'tension' => 0.4,
                    'fill' => true,
                    'pointBackgroundColor' => '#4285F4',
                    'pointBorderColor' => '#fff',
                    'pointBorderWidth' => 2,
                    'pointRadius' => 4,
                    'pointHoverRadius' => 7,
                ],
                [
                    'label' => 'New adds',
                    'data' => $newAdds,
                    'borderColor' => '#16a34a',
                    'backgroundColor' => 'rgba(22,163,74,0.06)',
                    'borderWidth' => 2,
                    'tension: 0.4',
                    'fill' => true,
                    'pointBackgroundColor' => '#16a34a',
                    'pointBorderColor' => '#fff',
                    'pointBorderWidth' => 2,
                    'pointRadius' => 3,
                    'pointHoverRadius' => 6,
                ],
                [
                    'label' => 'Churned',
                    'data' => $churned,
                    'borderColor' => '#ef4444',
                    'backgroundColor' => 'rgba(239,68,68,0.06)',
                    'borderWidth' => 2,
                    'tension: 0.4',
                    'fill' => true,
                    'pointBackgroundColor' => '#ef4444',
                    'pointBorderColor' => '#fff',
                    'pointBorderWidth' => 2,
                    'pointRadius' => 3,
                    'pointHoverRadius' => 6,
                    'borderDash' => [5, 4],
                ],
            ]
        ];

        return Inertia::render('Audience/Overview', [
            'stats' => $stats,
            'healthMeters' => $healthMeters,
            'topLists' => $topLists,
            'engagementMetrics' => $engagementMetrics,
            'growthChartData' => $growthChartData,
        ]);
    }
}
