<?php

namespace App\Livewire\Partners;

use App\Models\PartnerType;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\GenericExport;
use App\Imports\PartnerTypeImport;

class PartnerTypesIndex extends Component
{
    use WithPagination, WithFileUploads;

    protected $paginationTheme = 'bootstrap';

    public $name = '';
    public $code = '';
    public $description = '';
    public $is_customer_group = false;
    public $is_supplier_group = false;
    
    public ?PartnerType $editingType = null;
    public bool $showModal = false;

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

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selectedRows = PartnerType::pluck('id')->map(fn($id) => (string)$id)->toArray();
        } else {
            $this->selectedRows = [];
        }
    }

    public function downloadTemplate()
    {
        $headers = ['name', 'code', 'description', 'is_customer_group', 'is_supplier_group'];
        $data = [
            ['Gold Customer', 'GOLD', 'High value customers', '1', '0'],
            ['Wholesale Supplier', 'WHOL', 'Bulk purchase suppliers', '0', '1'],
        ];

        return Excel::download(new GenericExport(
            collect($data),
            $headers,
            fn($row) => $row,
            'Partner_Types_Import_Template'
        ), 'partner_types_template.xlsx');
    }

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

        try {
            Excel::import(new PartnerTypeImport, $this->importFile);
            $this->showImportModal = false;
            $this->importFile = null;
            session()->flash('success', __('Partner types imported successfully.'));
        } catch (\Exception $e) {
            session()->flash('error', __('Error importing partner types: ') . $e->getMessage());
        }
    }

    public function export()
    {
        $query = PartnerType::query()
            ->when(!empty($this->selectedRows), fn($q) => $q->whereIn('id', $this->selectedRows));

        $types = $query->orderBy('name')->get();

        return Excel::download(new GenericExport(
            $types,
            ['Name', 'Code', 'Description', 'Customer Group', 'Supplier Group'],
            function ($row) {
                return [
                    $row->name,
                    $row->code,
                    $row->description,
                    $row->is_customer_group ? 'Yes' : 'No',
                    $row->is_supplier_group ? 'Yes' : 'No',
                ];
            },
            'Partner_Types_Export_' . now()->format('Y-m-d')
        ), 'partner_types_' . now()->format('YmdHis') . '.xlsx');
    }

    protected $rules = [
        'name' => 'required|string|max:255',
        'code' => 'nullable|string|max:50',
        'description' => 'nullable|string',
        'is_customer_group' => 'boolean',
        'is_supplier_group' => 'boolean',
    ];

    public function create()
    {
        $this->reset(['name', 'description', 'is_customer_group', 'is_supplier_group', 'editingType']);
        $this->showModal = true;
    }

    public function edit(PartnerType $type)
    {
        $this->editingType = $type;
        $this->name = $type->name;
        $this->description = $type->description;
        $this->is_customer_group = $type->is_customer_group;
        $this->is_supplier_group = $type->is_supplier_group;
        $this->showModal = true;
    }

    public function save()
    {
        $validated = $this->validate();

        if ($this->editingType) {
            $this->editingType->update($validated);
            session()->flash('success', __('Partner type updated successfully.'));
        } else {
            PartnerType::create($validated);
            session()->flash('success', __('Partner type created successfully.'));
        }

        $this->showModal = false;
        $this->reset(['name', 'description', 'is_customer_group', 'is_supplier_group', 'editingType']);
    }

    public function delete(PartnerType $type)
    {
        if ($type->partners()->exists()) {
            session()->flash('error', __('Cannot delete type assigned to partners.'));
            return;
        }

        $type->delete();
        session()->flash('success', __('Partner type deleted.'));
    }

    public function render()
    {
        return view('livewire.partners.partner-types-index', [
            'types' => PartnerType::orderBy('name')->paginate(10)
        ]);
    }
}
