<?php

namespace App\Livewire\Admin\Produk;

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

#[Layout('layouts.admin')]
class Form extends Component
{
    use WithFileUploads;

    public ?int $productId = null;  // null = tambah baru

    // Form fields
    public string $name             = '';
    public string $slug             = '';
    public int    $category_id      = 0;
    public int    $partner_id       = 0;
    public string $description      = '';
    public string $buy_price        = '';
    public string $sell_price       = '';
    public string $unit             = 'pcs';
    public string $commission_type  = '';   // kosong = pakai default mitra
    public string $commission_value = '';
    public bool   $is_active        = true;
    public bool   $is_featured      = false;
    public int    $sort_order       = 0;
    public string $stock            = '';   // kosong = tidak dikelola (null di DB)
    public $image = null;
    public ?string $existing_image  = null;

    protected function rules(): array
    {
        return [
            'category_id'      => ['required', 'integer', 'exists:categories,id'],
            'partner_id'       => ['required', 'integer', 'exists:partners,id'],
            'name'             => ['required', 'string', 'max:200'],
            'slug'             => ['nullable', 'string', 'max:220',
                                   \Illuminate\Validation\Rule::unique('products', 'slug')
                                       ->ignore($this->productId)
                                       ->whereNull('deleted_at')],
            'description'      => ['nullable', 'string', 'max:5000'],
            'buy_price'        => ['required', 'numeric', 'min:0'],
            'sell_price'       => ['required', 'numeric', 'min:0'],
            'unit'             => ['required', 'string', 'max:50'],
            'commission_type'  => ['nullable', 'in:percent,fixed'],
            'commission_value' => ['nullable', 'numeric', 'min:0'],
            'is_active'        => ['boolean'],
            'is_featured'      => ['boolean'],
            'sort_order'       => ['integer', 'min:0'],
            'stock'            => ['nullable', 'integer', 'min:0'],
            'image'            => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:3072'],
        ];
    }

    protected $messages = [
        'category_id.required' => 'Kategori wajib dipilih.',
        'category_id.exists'   => 'Kategori tidak valid.',
        'partner_id.required'  => 'Mitra wajib dipilih.',
        'partner_id.exists'    => 'Mitra tidak valid.',
        'name.required'        => 'Nama produk wajib diisi.',
        'buy_price.required'   => 'Harga beli wajib diisi.',
        'sell_price.required'  => 'Harga jual wajib diisi.',
        'unit.required'        => 'Satuan wajib diisi.',
        'image.max'            => 'Ukuran gambar maksimal 3MB.',
    ];

    public function mount(?int $id = null): void
    {
        $this->productId = $id;

        if ($id) {
            $product = Product::findOrFail($id);
            $this->name             = $product->name;
            $this->slug             = $product->slug;
            $this->category_id      = $product->category_id;
            $this->partner_id       = $product->partner_id;
            $this->description      = $product->description ?? '';
            $this->buy_price        = (string) $product->buy_price;
            $this->sell_price       = (string) $product->sell_price;
            $this->unit             = $product->unit;
            $this->commission_type  = $product->commission_type?->value ?? '';
            $this->commission_value = $product->commission_value ? (string) $product->commission_value : '';
            $this->is_active        = $product->is_active;
            $this->is_featured      = $product->is_featured;
            $this->sort_order       = $product->sort_order;
            $this->stock            = $product->stock !== null ? (string) $product->stock : '';
            $this->existing_image   = $product->image;
        }
    }

    public function updatedName(): void
    {
        if (! $this->productId) {
            $this->slug = Str::slug($this->name);
        }
    }

    public function removeImage(): void
    {
        if ($this->existing_image) {
            Storage::disk('public')->delete($this->existing_image);
            Product::findOrFail($this->productId)->update(['image' => null]);
            $this->existing_image = null;
        }
    }

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

        $data = [
            'category_id'      => $this->category_id,
            'partner_id'       => $this->partner_id,
            'name'             => $this->name,
            'slug'             => $this->slug ?: Str::slug($this->name),
            'description'      => $this->description ?: null,
            'buy_price'        => $this->buy_price,
            'sell_price'       => $this->sell_price,
            'unit'             => $this->unit,
            'commission_type'  => $this->commission_type ?: null,
            'commission_value' => ($this->commission_type && $this->commission_value !== '')
                                    ? $this->commission_value : null,
            'is_active'        => $this->is_active,
            'is_featured'      => $this->is_featured,
            'sort_order'       => $this->sort_order,
            'stock'            => $this->stock !== '' ? (int) $this->stock : null,
        ];

        // Handle upload gambar
        if ($this->image) {
            if ($this->existing_image) {
                Storage::disk('public')->delete($this->existing_image);
            }
            $data['image'] = $this->image->store('products', 'public');
        }

        if ($this->productId) {
            Product::findOrFail($this->productId)->update($data);
            session()->flash('success', 'Produk berhasil diperbarui.');
        } else {
            Product::create($data);
            session()->flash('success', 'Produk berhasil ditambahkan.');
        }

        $this->redirect(route('admin.produk'), navigate: true);
    }

    public function getTitle(): string
    {
        return $this->productId ? 'Edit Produk' : 'Tambah Produk';
    }

    public function render()
    {
        $categories     = Category::where('is_active', true)->orderBy('name')->get();
        $partners       = Partner::where('is_active', true)->orderBy('name')->get();
        $selectedPartner = $this->partner_id
            ? Partner::find($this->partner_id)
            : null;

        return view('livewire.admin.produk.form',
            compact('categories', 'partners', 'selectedPartner'))
            ->title($this->getTitle());
    }
}
