<?php

namespace App\Livewire\Products;

use App\Models\Category;
use App\Models\Product;
use Livewire\Component;
use Livewire\WithPagination;

class ProductsIndex extends Component
{
    use WithPagination;
    use \Livewire\WithFileUploads;

    public string $search = '';
    public string $categoryFilter = '';
    public string $statusFilter = '';
    public string $sortField = 'created_at';
    public string $sortDirection = 'desc';
    public int $perPage = 15;

    public bool $showDeleteModal = false;
    public ?int $deleteId = null;

    // Import
    public bool $showImportModal = false;
    public $importFile;

    public array $selectedRows = [];
    public bool $selectAll = false;

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selectedRows = Product::query()
                ->when($this->search, function ($query) {
                    $query->where(function ($q) {
                        $q->where('name', 'like', '%' . $this->search . '%')
                          ->orWhere('name_ar', 'like', '%' . $this->search . '%')
                          ->orWhere('sku', 'like', '%' . $this->search . '%')
                          ->orWhere('barcode', 'like', '%' . $this->search . '%');
                    });
                })
                ->when($this->categoryFilter, function ($query) {
                    $query->where('category_id', $this->categoryFilter);
                })
                ->when($this->statusFilter !== '', function ($query) {
                    $query->where('is_active', $this->statusFilter === 'active');
                })
                ->pluck('id')->map(fn($id) => (string)$id)->toArray();
        } else {
            $this->selectedRows = [];
        }
    }

    public function export()
    {
        $query = !empty($this->selectedRows)
            ? Product::query()->whereIn('id', $this->selectedRows)
            : Product::query()
                ->when($this->search, function ($query) {
                    $query->where(function ($q) {
                        $q->where('name', 'like', '%' . $this->search . '%')
                          ->orWhere('name_ar', 'like', '%' . $this->search . '%')
                          ->orWhere('sku', 'like', '%' . $this->search . '%')
                          ->orWhere('barcode', 'like', '%' . $this->search . '%');
                    });
                })
                ->when($this->categoryFilter, function ($query) {
                    $query->where('category_id', $this->categoryFilter);
                })
                ->when($this->statusFilter !== '', function ($query) {
                    $query->where('is_active', $this->statusFilter === 'active');
                });

        $products = $query->with('category')->orderBy($this->sortField, $this->sortDirection)->get();

        return \Maatwebsite\Excel\Facades\Excel::download(new \App\Exports\GenericExport(
            $products,
            ['SKU', 'Name', 'Category', 'Price', 'Cost', 'Stock'],
            function ($row) {
                return [
                    $row->sku,
                    $row->localized_name,
                    $row->category->name ?? 'N/A',
                    number_format($row->selling_price, 2),
                    number_format($row->cost_price, 2),
                    $row->total_stock,
                ];
            },
            'Products_Export_' . now()->format('Y-m-d')
        ), 'products_' . now()->format('YmdHis') . '.xlsx');
    }

    protected $queryString = [
        'search' => ['except' => ''],
        'categoryFilter' => ['except' => ''],
        'statusFilter' => ['except' => ''],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingCategoryFilter()
    {
        $this->resetPage();
    }

    public function updatingStatusFilter()
    {
        $this->resetPage();
    }

    public function sortBy(string $field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortField = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function confirmDelete(int $id)
    {
        $this->deleteId = $id;
        $this->showDeleteModal = true;
    }

    public function delete()
    {
        if ($this->deleteId) {
            Product::find($this->deleteId)?->delete();
            session()->flash('success', __('Product deleted successfully.'));
        }
        $this->showDeleteModal = false;
        $this->deleteId = null;
    }

    public function cancelDelete()
    {
        $this->showDeleteModal = false;
        $this->deleteId = null;
    }

    public function openImportModal()
    {
        $this->reset(['importFile']);
        $this->showImportModal = true;
    }

    public function downloadTemplate()
    {
        $rows = [
            [
                'sku' => 'PROD-001',
                'name' => 'Sample Product',
                'name_ar' => 'منتج تجريبي',
                'category' => 'Electronics',
                'unit' => 'Piece',
                'cost_price' => 100,
                'selling_price' => 150,
                'alert_quantity' => 10,
                'description' => 'Product Description',
                'barcode' => '123456789',
            ]
        ];

        return \Maatwebsite\Excel\Facades\Excel::download(new \App\Exports\GenericExport(
            collect($rows),
            ['SKU', 'Name', 'Name AR', 'Category', 'Unit', 'Cost Price', 'Selling Price', 'Alert Quantity', 'Description', 'Barcode'],
            function ($row) {
                return [
                    $row['sku'],
                    $row['name'],
                    $row['name_ar'],
                    $row['category'],
                    $row['unit'],
                    $row['cost_price'],
                    $row['selling_price'],
                    $row['alert_quantity'],
                    $row['description'],
                    $row['barcode'],
                ];
            },
            'Products_Template'
        ), 'products_template.xlsx');
    }

    public function import()
    {
        $this->validate([
            'importFile' => 'required|file|mimes:xlsx,xls,csv|max:10240',
        ]);

        try {
            \Maatwebsite\Excel\Facades\Excel::import(new \App\Imports\ProductImport, $this->importFile);
            
            $this->showImportModal = false;
            $this->reset('importFile');
            session()->flash('success', __('Products imported successfully.'));
        } catch (\Exception $e) {
            $this->addError('importFile', __('Error importing file: ') . $e->getMessage());
        }
    }

    public function render()
    {
        $products = Product::query()
            ->with(['category', 'inventory'])
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('name', 'like', '%' . $this->search . '%')
                      ->orWhere('name_ar', 'like', '%' . $this->search . '%')
                      ->orWhere('sku', 'like', '%' . $this->search . '%')
                      ->orWhere('barcode', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->categoryFilter, function ($query) {
                $query->where('category_id', $this->categoryFilter);
            })
            ->when($this->statusFilter !== '', function ($query) {
                $query->where('is_active', $this->statusFilter === 'active');
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate($this->perPage);

        $categories = Category::active()->orderBy('sort_order')->get();

        return view('livewire.products.index', [
            'products' => $products,
            'categories' => $categories,
        ]);
    }
}
