<?php

namespace App\Livewire\Admin\Kategori;

use App\Models\Category;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;

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

    // ── Filter ───────────────────────────────────────────────────────────
    public string $search     = '';
    public string $filterStatus = '';

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

    // ── Form fields ──────────────────────────────────────────────────────
    public string $name       = '';
    public string $slug       = '';
    public bool   $is_active  = true;
    public int    $sort_order = 0;
    public $image = null;  // file upload

    protected function rules(): array
    {
        return [
            'name'       => ['required', 'string', 'max:100'],
            'slug'       => ['nullable', 'string', 'max:120',
                             \Illuminate\Validation\Rule::unique('categories', 'slug')
                                 ->ignore($this->editingId)],
            'is_active'  => ['boolean'],
            'sort_order' => ['integer', 'min:0'],
            'image'      => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
        ];
    }

    public function updatedName(): void
    {
        // Auto-generate slug hanya saat tambah baru
        if (! $this->editingId) {
            $this->slug = Str::slug($this->name);
        }
    }

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

    // ── CRUD Actions ─────────────────────────────────────────────────────

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

    public function edit(int $id): void
    {
        $cat = Category::findOrFail($id);
        $this->editingId  = $cat->id;
        $this->name       = $cat->name;
        $this->slug       = $cat->slug;
        $this->is_active  = $cat->is_active;
        $this->sort_order = $cat->sort_order;
        $this->image      = null;
        $this->showModal  = true;
    }

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

        $data = [
            'name'       => $this->name,
            'slug'       => $this->slug ?: Str::slug($this->name),
            'is_active'  => $this->is_active,
            'sort_order' => $this->sort_order,
        ];

        // Handle upload gambar
        if ($this->image) {
            // Hapus gambar lama jika edit
            if ($this->editingId) {
                $old = Category::find($this->editingId)?->image;
                if ($old) Storage::disk('public')->delete($old);
            }
            $data['image'] = $this->image->store('categories', 'public');
        }

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

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

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

    public function delete(): void
    {
        $cat = Category::findOrFail($this->deleteId);
        if ($cat->image) {
            Storage::disk('public')->delete($cat->image);
        }
        $cat->delete();
        $this->showDelete = false;
        $this->deleteId   = null;
        $this->dispatch('notify', type: 'success', message: 'Kategori berhasil dihapus.');
    }

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

    private function resetForm(): void
    {
        $this->editingId  = null;
        $this->name       = '';
        $this->slug       = '';
        $this->is_active  = true;
        $this->sort_order = 0;
        $this->image      = null;
        $this->resetValidation();
    }

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

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