<?php

namespace App\Livewire\Admin\Mitra;

use App\Models\Partner;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.admin')]
#[Title('Mitra')]
class Index extends Component
{
    use WithPagination;

    public string $search       = '';
    public string $filterStatus = '';

    // Modal
    public bool $showModal  = false;
    public bool $showDelete = false;
    public ?int $editingId  = null;
    public ?int $deleteId   = null;

    // Form
    public string $name                     = '';
    public string $phone                    = '';
    public string $address                  = '';
    public string $notes                    = '';
    public string $default_commission_type  = 'percent';
    public        $default_commission_value = 10;
    public int    $is_active                = 1;
    public string $open_time                = '';
    public string $close_time               = '';
    public string $logo                     = '';

    protected function rules(): array
    {
        return [
            'name'                     => ['required', 'string', 'max:150'],
            'phone'                    => ['nullable', 'string', 'max:20'],
            'address'                  => ['nullable', 'string', 'max:500'],
            'notes'                    => ['nullable', 'string', 'max:1000'],
            'default_commission_type'  => ['required', 'in:percent,fixed'],
            'default_commission_value' => ['required', 'numeric', 'min:0'],
            'is_active'                => ['required', 'in:0,1'],
            'open_time'                => ['nullable', 'date_format:H:i'],
            'close_time'               => ['nullable', 'date_format:H:i'],
            'logo'                     => ['nullable', 'string', 'max:500'],
        ];
    }

    protected $messages = [
        'name.required'                     => 'Nama mitra wajib diisi.',
        'default_commission_type.required'  => 'Tipe komisi wajib dipilih.',
        'default_commission_value.required' => 'Nilai komisi wajib diisi.',
        'default_commission_value.min'      => 'Nilai komisi tidak boleh negatif.',
    ];

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

    public function create(): void
    {
        $this->resetForm();
        $this->showModal = true;
    }

    public function edit(int $id): void
    {
        $mitra = Partner::findOrFail($id);
        $this->editingId                = $mitra->id;
        $this->name                     = $mitra->name;
        $this->phone                    = $mitra->phone ?? '';
        $this->address                  = $mitra->address ?? '';
        $this->notes                    = $mitra->notes ?? '';
        $this->default_commission_type  = $mitra->default_commission_type->value;
        $this->default_commission_value = (string) $mitra->default_commission_value;
        $this->is_active                = (int) $mitra->is_active;
        $this->open_time                = $mitra->open_time ? substr($mitra->open_time, 0, 5) : '';
        $this->close_time               = $mitra->close_time ? substr($mitra->close_time, 0, 5) : '';
        $this->logo                     = $mitra->logo ?? '';
        $this->showModal = true;
    }

    public function save(): void
    {
        $data = $this->validate();

        if ($this->editingId) {
            Partner::findOrFail($this->editingId)->update($data);
            $this->dispatch('notify', type: 'success', message: 'Mitra berhasil diperbarui.');
        } else {
            Partner::create($data);
            $this->dispatch('notify', type: 'success', message: 'Mitra berhasil ditambahkan.');
        }

        $this->showModal = false;
        $this->resetForm();
    }

    public function confirmDelete(int $id): void
    {
        $count = Partner::withCount('products')->findOrFail($id)->products_count;
        if ($count > 0) {
            $this->dispatch('notify', type: 'error',
                message: "Tidak bisa hapus. Mitra ini memiliki {$count} produk.");
            return;
        }
        $this->deleteId   = $id;
        $this->showDelete = true;
    }

    public function delete(): void
    {
        Partner::findOrFail($this->deleteId)->delete();
        $this->showDelete = false;
        $this->deleteId   = null;
        $this->dispatch('notify', type: 'success', message: 'Mitra berhasil dihapus.');
    }

    public function toggleActive(int $id): void
    {
        $mitra = Partner::findOrFail($id);
        $mitra->update(['is_active' => ! $mitra->is_active]);
        $label = $mitra->fresh()->is_active ? 'diaktifkan' : 'dinonaktifkan';
        $this->dispatch('notify', type: 'success', message: "Mitra berhasil {$label}.");
    }

    private function resetForm(): void
    {
        $this->editingId                = null;
        $this->name                     = '';
        $this->phone                    = '';
        $this->address                  = '';
        $this->notes                    = '';
        $this->default_commission_type  = 'percent';
        $this->default_commission_value = 10;
        $this->is_active                = 1;
        $this->open_time                = '';
        $this->close_time               = '';
        $this->logo                     = '';
        $this->resetValidation();
    }

    public function render()
    {
        $mitras = Partner::withCount('products')
            ->when($this->search, fn ($q) =>
                $q->where('name', 'like', "%{$this->search}%")
                  ->orWhere('phone', 'like', "%{$this->search}%"))
            ->when($this->filterStatus !== '', fn ($q) =>
                $q->where('is_active', (bool) $this->filterStatus))
            ->orderBy('name')
            ->paginate(15);

        return view('livewire.admin.mitra.index', compact('mitras'));
    }
}
