<?php

namespace App\Livewire\Admin\Pengaturan;

use App\Models\Setting;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;

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

    public string $activeTab = 'store'; // store | operational | order | notification | payment

    // ── Identitas Toko (group: store, contact) ─────────────────────────────
    public string  $store_name   = '';
    public $store_logo           = null; // file upload baru
    public ?string $existing_logo = null;
    public string  $wa_admin     = '';
    public string  $store_email  = '';
    public string  $store_address = '';

    // ── Operasional (group: store) ──────────────────────────────────────────
    public string $operating_hours       = '';
    public string $min_order             = '0';
    public string $default_delivery_cost = '0';
    public string $shipping_mode         = 'flat'; // flat | per_mitra | manual | free

    // ── Pesanan (group: order) ───────────────────────────────────────────────
    public string $auto_cancel_pending_minutes = '60';
    public string $checkout_duration_minutes   = '15';

    // ── Notifikasi (group: notification) ─────────────────────────────────────
    public bool $wa_notification_enabled = true;

    // ── Pembayaran (group: payment) ───────────────────────────────────────────
    public array   $bank_accounts         = [];
    public $qris_image_file               = null; // upload baru
    public ?string $existing_qris_image   = null;
    public string  $transfer_instruction  = '';
    public string  $qris_instruction      = '';

    public function mount(): void
    {
        $this->store_name     = Setting::get('store_name', '');
        $this->existing_logo  = Setting::get('store_logo');
        $this->wa_admin       = Setting::get('wa_admin', '');
        $this->store_email    = Setting::get('store_email', '');
        $this->store_address  = Setting::get('store_address', '');

        $this->operating_hours       = Setting::get('operating_hours', '');
        $this->min_order             = (string) Setting::get('min_order', '0');
        $this->default_delivery_cost = (string) Setting::get('default_delivery_cost', '0');
        $this->shipping_mode         = Setting::get('shipping_mode', 'flat');

        $this->auto_cancel_pending_minutes = (string) Setting::get('auto_cancel_pending_minutes', '60');
        $this->checkout_duration_minutes   = (string) Setting::get('checkout_duration_minutes', '15');

        $this->wa_notification_enabled = Setting::get('wa_notification_enabled', '1') !== '0';

        // Payment
        $this->bank_accounts        = json_decode(Setting::get('bank_accounts', '[]'), true) ?? [['bank_name'=>'','account_number'=>'','account_name'=>'']];
        $this->existing_qris_image  = Setting::get('qris_image');
        $this->transfer_instruction = Setting::get('transfer_instruction', '');
        $this->qris_instruction     = Setting::get('qris_instruction', '');
    }

    protected function rules(): array
    {
        return match ($this->activeTab) {
            'store' => [
                'store_name'    => ['required', 'string', 'max:150'],
                'store_logo'    => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
                'wa_admin'      => ['nullable', 'string', 'max:20'],
                'store_email'   => ['nullable', 'email', 'max:150'],
                'store_address' => ['nullable', 'string', 'max:500'],
            ],
            'operational' => [
                'operating_hours'       => ['nullable', 'string', 'max:100'],
                'min_order'             => ['required', 'numeric', 'min:0'],
                'default_delivery_cost' => ['required', 'numeric', 'min:0'],
                'shipping_mode'         => ['required', 'in:flat,per_mitra,manual,free'],
            ],
            'order' => [
                'auto_cancel_pending_minutes' => ['required', 'integer', 'min:0'],
                'checkout_duration_minutes'   => ['required', 'integer', 'min:1'],
            ],
            'notification' => [
                'wa_notification_enabled' => ['boolean'],
            ],
            default => [],
        };
    }

    protected $messages = [
        'store_name.required'    => 'Nama toko wajib diisi.',
        'store_logo.image'       => 'File harus berupa gambar.',
        'store_logo.mimes'       => 'Format logo harus JPG, PNG, atau WEBP.',
        'store_logo.max'         => 'Ukuran logo maksimal 2MB.',
        'store_email.email'      => 'Format email tidak valid.',
        'min_order.required'             => 'Minimal belanja wajib diisi.',
        'default_delivery_cost.required' => 'Ongkir default wajib diisi.',
        'auto_cancel_pending_minutes.required' => 'Durasi auto cancel wajib diisi.',
        'checkout_duration_minutes.required'   => 'Durasi checkout wajib diisi.',
        'checkout_duration_minutes.min'        => 'Durasi checkout minimal 1 menit.',
    ];

    public function setTab(string $tab): void
    {
        $this->activeTab = $tab;
    }

    public function removeLogo(): void
    {
        if ($this->existing_logo) {
            Storage::disk('public')->delete($this->existing_logo);
            Setting::set('store_logo', null, 'store');
            $this->existing_logo = null;
            $this->dispatch('notify', type: 'success', message: 'Logo berhasil dihapus.');
        }
    }

    public function saveStoreIdentity(): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        $this->activeTab = 'store';
        $this->validate();

        Setting::set('store_name', $this->store_name, 'store');
        Setting::set('wa_admin', $this->wa_admin ?: null, 'contact');
        Setting::set('store_email', $this->store_email ?: null, 'contact');
        Setting::set('store_address', $this->store_address ?: null, 'contact');

        if ($this->store_logo) {
            if ($this->existing_logo) {
                Storage::disk('public')->delete($this->existing_logo);
            }
            $path = $this->store_logo->store('settings', 'public');
            Setting::set('store_logo', $path, 'store');
            $this->existing_logo = $path;
            $this->store_logo    = null;
        }

        $this->dispatch('notify', type: 'success', message: 'Identitas toko berhasil disimpan.');
    }

    public function saveOperational(): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        $this->activeTab = 'operational';
        $this->validate();

        Setting::set('operating_hours', $this->operating_hours ?: null, 'store');
        Setting::set('min_order', $this->min_order, 'store');
        Setting::set('default_delivery_cost', $this->default_delivery_cost, 'store');
        Setting::set('shipping_mode', $this->shipping_mode, 'store');

        $this->dispatch('notify', type: 'success', message: 'Pengaturan operasional berhasil disimpan.');
    }

    public function saveOrder(): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        $this->activeTab = 'order';
        $this->validate();

        Setting::set('auto_cancel_pending_minutes', $this->auto_cancel_pending_minutes, 'order');
        Setting::set('checkout_duration_minutes', $this->checkout_duration_minutes, 'order');

        $this->dispatch('notify', type: 'success', message: 'Pengaturan pesanan berhasil disimpan.');
    }

    public function saveNotification(): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        Setting::set('wa_notification_enabled', $this->wa_notification_enabled ? '1' : '0', 'notification');

        $this->dispatch('notify', type: 'success', message: 'Pengaturan notifikasi berhasil disimpan.');
    }

    public function addBank(): void
    {
        $this->bank_accounts[] = ['bank_name' => '', 'account_number' => '', 'account_name' => ''];
    }

    public function removeBank(int $index): void
    {
        array_splice($this->bank_accounts, $index, 1);
    }

    public function removeQris(): void
    {
        if ($this->existing_qris_image) {
            Storage::disk('public')->delete($this->existing_qris_image);
            Setting::set('qris_image', null, 'payment');
            $this->existing_qris_image = null;
        }
    }

    public function savePayment(): void
    {
        abort_unless(auth()->user()->can('setting.manage'), 403);

        $this->activeTab = 'payment';

        // Validasi bank accounts
        $this->validate([
            'bank_accounts.*.bank_name'      => ['nullable', 'string', 'max:50'],
            'bank_accounts.*.account_number' => ['nullable', 'string', 'max:30'],
            'bank_accounts.*.account_name'   => ['nullable', 'string', 'max:100'],
            'qris_image_file'                => ['nullable', 'image', 'max:2048'],
            'transfer_instruction'           => ['nullable', 'string', 'max:1000'],
            'qris_instruction'               => ['nullable', 'string', 'max:1000'],
        ], [
            'qris_image_file.image' => 'File harus berupa gambar.',
            'qris_image_file.max'   => 'Ukuran gambar maksimal 2MB.',
        ]);

        // Simpan bank accounts sebagai JSON
        $cleanBanks = array_filter($this->bank_accounts, fn($b) => !empty($b['account_number']));
        Setting::set('bank_accounts', json_encode(array_values($cleanBanks)), 'payment');

        // Upload QRIS jika ada file baru
        if ($this->qris_image_file) {
            if ($this->existing_qris_image) {
                Storage::disk('public')->delete($this->existing_qris_image);
            }
            $path = $this->qris_image_file->store('settings/qris', 'public');
            Setting::set('qris_image', $path, 'payment');
            $this->existing_qris_image = $path;
            $this->qris_image_file     = null;
        }

        Setting::set('transfer_instruction', $this->transfer_instruction ?: null, 'payment');
        Setting::set('qris_instruction', $this->qris_instruction ?: null, 'payment');

        $this->dispatch('notify', type: 'success', message: 'Pengaturan pembayaran berhasil disimpan.');
    }

    public function render()
    {
        return view('livewire.admin.pengaturan.index', [
            'shippingModes' => \App\Services\ShippingCalculator::modes(),
        ]);
    }
}
