<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProductRequest;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminProductController extends Controller
{
    public function index(Request $request): View
    {
        $query = Product::with('category');

        if ($request->filled('search')) {
            $query->search($request->search);
        }

        if ($request->filled('category')) {
            $query->filterByCategory($request->category);
        }

        if ($request->filled('source')) {
            $query->where('source', $request->source);
        }

        if ($request->filled('min_price') || $request->filled('max_price')) {
            $query->filterByPriceRange($request->min_price, $request->max_price);
        }

        $products = $query->latest()->paginate(20);
        $categories = Category::orderBy('name_en')->get();

        return view('admin.products.index', compact('products', 'categories'));
    }

    public function create(): View
    {
        $categories = Category::orderBy('name_en')->get();

        return view('admin.products.create', compact('categories'));
    }

    public function store(ProductRequest $request): RedirectResponse
    {
        Product::create($request->validated());

        return redirect()->route('admin.products.index')
            ->with('success', 'Product created successfully.');
    }

    public function show(Product $product): View
    {
        $product->load('category');

        return view('admin.products.show', compact('product'));
    }

    public function edit(Product $product): View
    {
        $categories = Category::orderBy('name_en')->get();

        return view('admin.products.edit', compact('product', 'categories'));
    }

    public function update(ProductRequest $request, Product $product): RedirectResponse
    {
        $product->update($request->validated());

        return redirect()->route('admin.products.index')
            ->with('success', 'Product updated successfully.');
    }

    public function destroy(Product $product): RedirectResponse
    {
        $product->delete();

        return redirect()->route('admin.products.index')
            ->with('success', 'Product deleted successfully.');
    }

    public function import(): View
    {
        return view('admin.products.import');
    }

    public function storeImport(Request $request): RedirectResponse
    {
        $request->validate([
            'category_id' => ['required', 'exists:categories,id'],
            'source' => ['required', 'in:aliexpress,amazon,noon'],
            'products' => ['required', 'array'],
        ]);

        $categoryId = $request->category_id;
        $source = $request->source;

        $imported = 0;
        $failed = 0;

        foreach ($request->products as $rawProduct) {
            try {
                $productData = [
                    'category_id' => $categoryId,
                    'source' => $source,
                    'product_id' => $rawProduct['ProductId'] ?? null,
                    'image_url' => $rawProduct['Image Url'] ?? null,
                    'video_url' => $rawProduct['Video Url'] ?? null,
                    'name_ar' => $rawProduct['Product Desc'] ?? $rawProduct['name_ar'] ?? 'N/A',
                    'name_en' => $rawProduct['Product Desc'] ?? $rawProduct['name_en'] ?? 'N/A',
                    'description_ar' => $rawProduct['Product Desc'] ?? null,
                    'description_en' => $rawProduct['Product Desc'] ?? null,
                    'price' => $this->parsePrice($rawProduct['Origin Price'] ?? 0),
                    'discount_price' => $this->parsePrice($rawProduct['Discount Price'] ?? 0),
                    'discount' => $this->parsePrice($rawProduct['Discount'] ?? 0),
                    'currency' => $rawProduct['Currency'] ?? 'USD',
                    'clicks' => 0,
                    'direct_commission_rate' => $this->parsePrice($rawProduct['Direct linking commission rate (%)'] ?? 0),
                    'estimated_direct_commission' => $this->parsePrice($rawProduct['Estimated direct linking commission'] ?? 0),
                    'indirect_commission_rate' => $this->parsePrice($rawProduct['Indirect linking commission rate (%)'] ?? 0),
                    'estimated_indirect_commission' => $this->parsePrice($rawProduct['Estimated indirect linking commission'] ?? 0),
                    'sales_180day' => (int) ($rawProduct['Sales180Day'] ?? 0),
                    'positive_feedback' => $this->parsePrice($rawProduct['Positive Feedback'] ?? 0),
                    'promotion_url' => $rawProduct['Promotion Url'] ?? null,
                    'code_name' => $rawProduct['Code Name'] ?? null,
                    'code_start_time' => $this->parseDate($rawProduct['Code Start Time'] ?? null),
                    'code_end_time' => $this->parseDate($rawProduct['Code End Time'] ?? null),
                    'code_value' => $rawProduct['Code Value'] ?? null,
                    'code_quantity' => (int) ($rawProduct['Code Quantity'] ?? 0),
                    'code_minimum_spend' => $this->parsePrice($rawProduct['Code Minimum Spend'] ?? 0),
                ];

                Product::create($productData);
                $imported++;
            } catch (\Exception $e) {
                $failed++;
                logger()->error('Failed to import product', [
                    'product' => $rawProduct,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        $message = "Successfully imported {$imported} products.";
        if ($failed > 0) {
            $message .= " Failed to import {$failed} products. Check logs for details.";
        }

        return redirect()->route('admin.products.index')
            ->with('success', $message);
    }

    private function parsePrice(mixed $value): ?float
    {
        if (is_numeric($value)) {
            return (float) $value;
        }

        if (is_string($value)) {
            $cleaned = preg_replace('/[^0-9.]/', '', $value);

            return $cleaned !== '' ? (float) $cleaned : null;
        }

        return null;
    }

    private function parseDate(mixed $value): ?string
    {
        if (empty($value)) {
            return null;
        }

        if (is_numeric($value)) {
            return date('Y-m-d H:i:s', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)->getTimestamp());
        }

        try {
            return date('Y-m-d H:i:s', strtotime($value));
        } catch (\Exception $e) {
            return null;
        }
    }
}
