<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Enums\Status;
use App\Models\Category;
use App\Models\Faq;
use App\Models\Post;
use App\Models\Producer;
use App\Models\Product;
use App\Models\Setting;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

class HomeController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $settings = Setting::query()
            ->where('is_public', true)
            ->where('key', 'like', 'index.%')
            ->pluck('value', 'key');

        return ApiResponse::success([
            'index_setting' => [
                'top_small_text' => $settings->get('index.top_small_text', 'با ریوو با خیال راحت خرید و فروش کن'),
                'top_big_description' => $settings->get('index.top_big_description', ''),
                'more_information_title' => $settings->get('index.more_information_title', 'با ریوو دامداری مجازی خودتو داشته باش!'),
                'more_information_text' => $settings->get('index.more_information_text', ''),
            ],
            'stats' => [
                'active_ranchers' => $settings->get('index.stats.active_ranchers', '۰'),
                'success_payments' => $settings->get('index.stats.success_payments', '۰'),
            ],
            'features' => $this->features($settings->get('index.features')),
            'categories' => $this->categories(),
            'slider_products' => $this->sliderProducts(),
            'livestock_products' => $this->livestockProducts(),
            'top_ranchers' => $this->topRanchers(),
            'blog_preview' => $this->blogPreview(),
            'faqs' => $this->faqs(),
        ]);
    }

    /**
     * @return array<int, array{title: string, desc: string, icon: string}>
     */
    private function features(?string $raw): array
    {
        if (filled($raw)) {
            $decoded = json_decode($raw, true);

            if (is_array($decoded) && $decoded !== []) {
                return array_values(array_map(fn (array $item): array => [
                    'title' => (string) ($item['title'] ?? ''),
                    'desc' => (string) ($item['desc'] ?? ''),
                    'icon' => (string) ($item['icon'] ?? 'i-lucide-check'),
                ], $decoded));
            }
        }

        return [
            [
                'title' => 'ضمانت کیفیت دام',
                'desc' => 'دام خریداری شده دقیقا مطابق توضیحات فروشگاه خواهد بود.',
                'icon' => 'i-lucide-home',
            ],
            [
                'title' => 'ضمانت خرید و فروش امن',
                'desc' => 'خرید و فروش به صورت کاملا امن و آنلاین انجام می‌شود.',
                'icon' => 'i-lucide-check',
            ],
            [
                'title' => 'ضمانت بازگشت پول',
                'desc' => 'مبلغ در صورت عدم رضایت برگردانده خواهد شد.',
                'icon' => 'i-lucide-shield',
            ],
            [
                'title' => 'پنل دامداری',
                'desc' => 'مدیریت آسان دام‌های خریداری و فروخته شده.',
                'icon' => 'i-lucide-award',
            ],
            [
                'title' => 'پشتیبانی ۲۴ ساعته',
                'desc' => 'در هر ساعت از شبانه‌روز پاسخگوی شما هستیم.',
                'icon' => 'i-lucide-headphones',
            ],
        ];
    }

    /**
     * @return array<int, array{name: string, slug: string, dam_count: int, bgImage: string|null}>
     */
    private function categories(): array
    {
        return Category::query()
            ->whereHas('products')
            ->where('model_type', Product::class)
            ->withCount(['products' => fn ($query) => $query->where('status', 'active')->where('is_active', true)])
            ->orderBy('order')
            ->orderBy('id')
            ->take(12)
            ->get()
            ->map(fn (Category $category): array => [
                'name' => $category->title,
                'slug' => $category->slug,
                'dam_count' => (int) $category->products_count,
                'bgImage' => $category->icon ? url($category->icon) : null,
            ])
            ->values()
            ->all();
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    private function sliderProducts(): array
    {
        $products = Product::query()
            ->with(['breed', 'category'])
            ->where('status', 'active')
            ->where('is_active', true)
            ->where('is_featured', true)
            ->take(6)
            ->get();

        if ($products->isEmpty()) {
            $products = Product::query()
                ->with(['breed', 'category'])
                ->where('status', 'active')
                ->where('is_active', true)
                ->take(6)
                ->get();
        }

        return $products
            ->map(fn (Product $product): array => [
                'id' => $product->id,
                'slug' => $product->slug,
                'image' => $product->image ? url($product->image) : null,
                'title' => $product->name,
                'price' => $this->formatPrice($product->total_price ?? $product->price),
                'countdown' => null,
                'specs' => $this->productSpecs($product),
            ])
            ->values()
            ->all();
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    private function livestockProducts(): array
    {
        return Product::query()
            ->with('breed')
            ->where('status', 'active')
            ->where('is_active', true)
            ->take(8)
            ->get()
            ->map(fn (Product $product): array => [
                'id' => $product->id,
                'slug' => $product->slug,
                'image' => $product->image ? url($product->image) : null,
                'title' => $product->name,
                'price' => $this->formatPrice($product->total_price ?? $product->price),
                'breed' => $product->breed?->name,
                'age' => $this->formatAge($product->age),
                'gender' => $this->formatGender($product->gender),
            ])
            ->values()
            ->all();
    }

    /**
     * @return array<int, array{id: int, username: string|null, fullname: string|null, dam_count: int, image: string|null}>
     */
    private function topRanchers(): array
    {
        return Producer::query()
            ->with('user')
            ->withCount(['products' => fn ($query) => $query->where('status', 'active')->where('is_active', true)])
            ->orderByDesc('products_count')
            ->take(8)
            ->get()
            ->map(fn (Producer $producer): array => [
                'id' => $producer->id,
                'username' => $producer->user?->name ?? $producer->brand_name,
                'fullname' => $producer->brand_name ?? $producer->user?->name,
                'dam_count' => (int) $producer->products_count,
                'image' => $producer->user?->avatar ? url($producer->user->avatar) : null,
            ])
            ->values()
            ->all();
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    private function blogPreview(): array
    {
        return Post::query()
            ->with('categories')
            ->where('status', Status::PUBLISHED->value)
            ->take(3)
            ->get()
            ->map(fn (Post $post): array => [
                'id' => $post->id,
                'slug' => $post->slug,
                'title' => $post->title,
                'excerpt' => $post->excerpt ?? '',
                'image' => $post->image ? url($post->image) : null,
                'views' => (int) ($post->views ?? 0),
                'rate' => 0,
                'comments' => 0,
                'category' => $post->categories->first()?->title ?? '',
            ])
            ->values()
            ->all();
    }

    /**
     * @return array<int, array{question: string, response: string}>
     */
    private function faqs(): array
    {
        return Faq::query()
            ->reorder()
            ->where('status', Faq::STATUS_APPROVED)
            ->orderBy('order')
            ->orderBy('id')
            ->take(10)
            ->get(['question', 'response'])
            ->map(fn (Faq $faq): array => [
                'question' => $faq->question,
                'response' => $faq->response,
            ])
            ->values()
            ->all();
    }

    /**
     * @return array<int, array{label: string, value: string, badge?: string, badgeClass?: string}>
     */
    private function productSpecs(Product $product): array
    {
        $specs = [];

        if ($product->breed?->name) {
            $specs[] = [
                'label' => 'نژاد',
                'value' => $product->breed->name,
                'badge' => mb_strtoupper($product->breed->name),
                'badgeClass' => 'bg-rievo-orange-red',
            ];
        }

        if ($product->weight !== null) {
            $unit = $product->weight_unit ?: 'کیلوگرم';
            $specs[] = [
                'label' => 'وزن',
                'value' => rtrim(rtrim(number_format((float) $product->weight, 2, '.', ''), '0'), '.') . ' ' . $unit,
                'badge' => mb_strtoupper($unit === 'کیلوگرم' ? 'KG' : $unit),
                'badgeClass' => 'bg-rievo-orange-red',
            ];
        }

        if (filled($product->color)) {
            $specs[] = [
                'label' => 'رنگ پوست',
                'value' => (string) $product->color,
                'badge' => mb_strtoupper((string) $product->color),
                'badgeClass' => 'bg-rievo-orange-red',
            ];
        }

        if ($product->age !== null) {
            $specs[] = [
                'label' => 'سن',
                'value' => $this->formatAge($product->age) ?? (string) $product->age,
            ];
        }

        if (filled($product->gender)) {
            $specs[] = [
                'label' => 'جنسیت',
                'value' => $this->formatGender($product->gender) ?? (string) $product->gender,
            ];
        }

        if ($product->category?->title) {
            $specs[] = [
                'label' => 'نوع',
                'value' => $product->category->title,
            ];
        }

        return $specs;
    }

    private function formatPrice(mixed $price): string
    {
        if ($price === null || $price === '') {
            return '۰';
        }

        return number_format((float) $price, 0, '', ',');
    }

    private function formatAge(mixed $age): ?string
    {
        if ($age === null || $age === '') {
            return null;
        }

        if (is_numeric($age)) {
            return ((int) $age) . ' سال';
        }

        return (string) $age;
    }

    private function formatGender(?string $gender): ?string
    {
        return match ($gender) {
            'male' => 'نر',
            'female' => 'ماده',
            'both' => 'هر دو',
            'unknown' => 'نامشخص',
            default => $gender,
        };
    }
}
