<?php

namespace App\Campaigns;

use Illuminate\Support\Collection;

class PerformanceChart
{
    /** @var list<int> */
    public const RANGE_DAYS = [3, 7, 15, 30];

    /** @var list<string> */
    public const METRICS = [
        'spend',
        'impressions',
        'clicks',
        'cpc',
        'ctr',
        'conversions',
        'conversion_value',
    ];

    /**
     * Single-metric line graph for a day window. Defaults to 7 days of spend.
     *
     * @param  Collection<int, PerformanceDay>  $days
     * @return array<string, mixed>
     */
    public static function fromDays(Collection $days, int $rangeDays = 7, string $metric = 'spend'): array
    {
        $sorted = $days
            ->sortBy(fn (PerformanceDay $row): int => $row->stat_date->timestamp)
            ->values();

        $rangeDays = in_array($rangeDays, self::RANGE_DAYS, true) ? $rangeDays : 7;
        $metric = in_array($metric, self::METRICS, true) ? $metric : 'spend';

        $slice = self::sliceDays($sorted, $rangeDays);
        $chart = self::buildSingleMetricChart($slice, $metric);
        $windowTotals = [];

        foreach (self::RANGE_DAYS as $length) {
            $windowTotals[$length] = self::totalsForDays($sorted, $length);
        }

        return array_merge($chart, [
            'range_days' => self::RANGE_DAYS,
            'metrics' => self::METRICS,
            'default_range' => $rangeDays,
            'default_metric' => $metric,
            'series' => self::seriesFromDays($sorted),
            'window_totals' => $windowTotals,
            'range_subtitle' => self::rangeSubtitle($slice, $rangeDays),
            'loaded_day_count' => $sorted->count(),
        ]);
    }

    /**
     * @param  Collection<int, PerformanceDay>  $days
     * @return Collection<int, PerformanceDay>
     */
    public static function sliceDays(Collection $days, int $rangeDays): Collection
    {
        $to = now()->copy()->startOfDay();
        $from = $to->copy()->subDays(max(1, $rangeDays) - 1);

        return $days
            ->filter(
                fn (PerformanceDay $row): bool => $row->stat_date->gte($from)
                    && $row->stat_date->lte($to),
            )
            ->sortBy(fn (PerformanceDay $row): int => $row->stat_date->timestamp)
            ->values();
    }

    /**
     * @param  Collection<int, PerformanceDay>  $days
     * @return array<string, float|int|null>
     */
    public static function totalsForDays(Collection $days, int $rangeDays): array
    {
        $slice = self::sliceDays($days, $rangeDays);
        $spend = round((float) $slice->sum('spend'), 2);
        $impressions = (int) $slice->sum('impressions');
        $clicks = (int) $slice->sum('clicks');
        $conversions = (int) $slice->sum(fn (PerformanceDay $row): int => (int) ($row->conversions ?? 0));
        $conversionValue = round((float) $slice->sum(fn (PerformanceDay $row): float => (float) ($row->conversion_value ?? 0)), 2);

        return [
            'days_on_file' => $slice->count(),
            'expected_days' => $rangeDays,
            'spend' => $spend,
            'impressions' => $impressions,
            'clicks' => $clicks,
            'cpc' => $clicks > 0 ? round($spend / $clicks, 4) : null,
            'ctr' => $impressions > 0 ? round($clicks / $impressions, 4) : null,
            'conversions' => $conversions,
            'conversion_value' => $conversionValue,
        ];
    }

    /**
     * @param  Collection<int, PerformanceDay>  $slice
     */
    public static function rangeSubtitle(Collection $slice, int $rangeDays): string
    {
        $onFile = $slice->count();

        if ($onFile === 0) {
            return 'No daily rows in this window yet.';
        }

        $first = $slice->first()?->stat_date->toDateString();
        $last = $slice->last()?->stat_date->toDateString();

        if ($onFile < $rangeDays) {
            return $onFile.' of '.$rangeDays.' days on file · '.$first.' – '.$last;
        }

        return $onFile.' days · '.$first.' – '.$last;
    }

    /**
     * @param  Collection<int, PerformanceDay>  $sorted
     * @return list<array<string, mixed>>
     */
    private static function seriesFromDays(Collection $sorted): array
    {
        return $sorted->map(function (PerformanceDay $day): array {
            $spend = round((float) $day->spend, 2);
            $clicks = (int) $day->clicks;
            $impressions = (int) $day->impressions;
            $conversions = (int) ($day->conversions ?? 0);
            $conversionValue = round((float) ($day->conversion_value ?? 0), 2);

            return [
                'date' => $day->stat_date->toDateString(),
                'label' => $day->stat_date->format('j M'),
                'spend' => $spend,
                'impressions' => $impressions,
                'clicks' => $clicks,
                'cpc' => $day->cpc !== null ? round((float) $day->cpc, 4) : ($clicks > 0 ? round($spend / $clicks, 4) : null),
                'ctr' => $day->ctr,
                'conversions' => $conversions,
                'conversion_value' => $conversionValue,
            ];
        })->values()->all();
    }

    /**
     * @param  Collection<int, PerformanceDay>  $slice
     * @return array<string, mixed>
     */
    private static function buildSingleMetricChart(Collection $slice, string $metric): array
    {
        $height = 260;
        $padL = 52;
        $padR = 16;
        $padT = 20;
        $padB = 48;
        $count = $slice->count();
        $width = (int) max(720, $padL + $padR + max(1, $count) * 42);
        $innerW = $width - $padL - $padR;
        $innerH = $height - $padT - $padB;
        $baseY = $padT + $innerH;

        if ($slice->isEmpty()) {
            return [
                'empty' => true,
                'metric' => $metric,
                'day_count' => 0,
                'width' => $width,
                'height' => $height,
                'pad_l' => $padL,
                'pad_r' => $padR,
                'pad_t' => $padT,
                'base_y' => $baseY,
                'days' => [],
                'points' => '',
                'area' => '',
                'dots' => [],
                'x_ticks' => [],
                'max_value' => 0.0,
                'y_labels' => ['0', '0', '0', '0'],
                'first_date' => null,
                'last_date' => null,
            ];
        }

        $values = $slice->map(fn (PerformanceDay $day): float => self::metricValue($day, $metric))->all();
        $maxValue = max(1.0, (float) max($values));
        $slot = $innerW / $count;

        $series = [];
        $points = [];
        $dots = [];
        $ticks = [];

        foreach ($slice->values() as $index => $day) {
            $center = round($padL + ($slot * $index) + ($slot / 2), 1);
            $value = self::metricValue($day, $metric);
            $y = round($padT + $innerH - ($value / $maxValue) * $innerH, 1);

            $series[] = [
                'center' => $center,
                'date' => $day->stat_date->toDateString(),
                'label' => $day->stat_date->format('j M'),
                'value' => $value,
                'metric' => $metric,
                'spend' => round((float) $day->spend, 2),
                'clicks' => (int) $day->clicks,
                'impressions' => (int) $day->impressions,
                'cpc' => $day->cpc,
                'ctr' => $day->ctr,
                'conversions' => (int) ($day->conversions ?? 0),
                'conversion_value' => round((float) ($day->conversion_value ?? 0), 2),
                'hit_x' => round($padL + ($slot * $index), 1),
                'hit_width' => round($slot, 1),
            ];
            $points[] = $center.','.$y;
            $dots[] = ['x' => $center, 'y' => $y];
            $ticks[] = [
                'x' => $center,
                'label' => $day->stat_date->format('j M'),
            ];
        }

        $firstX = $dots[0]['x'];
        $lastX = $dots[array_key_last($dots)]['x'];
        $area = 'M '.$firstX.' '.$baseY.' L '.str_replace(',', ' ', implode(' L ', $points)).' L '.$lastX.' '.$baseY.' Z';

        return [
            'empty' => false,
            'metric' => $metric,
            'day_count' => $count,
            'width' => $width,
            'height' => $height,
            'pad_l' => $padL,
            'pad_r' => $padR,
            'pad_t' => $padT,
            'base_y' => $baseY,
            'days' => $series,
            'points' => implode(' ', $points),
            'area' => $area,
            'dots' => $dots,
            'x_ticks' => $ticks,
            'max_value' => round($maxValue, 4),
            'y_labels' => self::yLabels($metric, $maxValue),
            'first_date' => $slice->first()?->stat_date->toDateString(),
            'last_date' => $slice->last()?->stat_date->toDateString(),
        ];
    }

    private static function metricValue(PerformanceDay $day, string $metric): float
    {
        return match ($metric) {
            'spend' => round((float) $day->spend, 2),
            'impressions' => (float) (int) $day->impressions,
            'clicks' => (float) (int) $day->clicks,
            'cpc' => (float) ($day->cpc ?? (($day->clicks > 0) ? round($day->spend / $day->clicks, 4) : 0)),
            'ctr' => (float) ($day->ctr ?? 0),
            'conversions' => (float) (int) ($day->conversions ?? 0),
            'conversion_value' => round((float) ($day->conversion_value ?? 0), 2),
            default => 0.0,
        };
    }

    /**
     * @return list<string>
     */
    private static function yLabels(string $metric, float $maxValue): array
    {
        $format = fn (float $value): string => match ($metric) {
            'spend', 'cpc', 'conversion_value' => '$'.number_format($value, $metric === 'cpc' ? 2 : 0),
            'ctr' => number_format($value * 100, 2).'%',
            default => number_format($value, 0),
        };

        return [
            $format($maxValue),
            $format($maxValue * 0.66),
            $format($maxValue * 0.33),
            $format(0),
        ];
    }
}
