<?php

namespace App\Filament\Pages;

use App\Models\ShippingSetting;
use App\Models\UserAddress;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;

class ShippingSettings extends Page
{
    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-truck';

    protected static string | \UnitEnum | null $navigationGroup = 'الإعدادات';

    protected static ?string $navigationLabel = 'إعدادات الشحن';

    protected static ?string $title = 'إعدادات الشحن والتوصيل';

    protected static ?int $navigationSort = 11;

    public static function canAccess(): bool
    {
        return auth()->user()?->hasRole('admin') ?? false;
    }

    protected string $view = 'filament.pages.shipping-settings';

    public ?array $data = [];

    public function mount(): void
    {
        $settings = ShippingSetting::current();

        $fillData = [
            'shipping_type' => $settings->shipping_type,
            'flat_rate' => $settings->flat_rate,
        ];

        $rates = $settings->governorate_rates ?? [];
        foreach (UserAddress::getEgyptGovernorates() as $key => $label) {
            $fillData["gov_{$key}"] = $rates[$key] ?? 0;
        }

        $this->form->fill($fillData);
    }

    public function form(Schema $form): Schema
    {
        return $form
            ->schema([
                Section::make('نوع الشحن')
                    ->description('اختر طريقة حساب تكلفة الشحن')
                    ->schema([
                        Forms\Components\Radio::make('shipping_type')
                            ->label('')
                            ->options([
                                'free' => '🟢 شحن مجاني — تكلفة الشحن = 0 ج.م',
                                'flat' => '🔵 شحن بسعر ثابت — مبلغ موحد لكل الطلبات',
                                'per_governorate' => '🟡 شحن حسب المحافظة — سعر مختلف لكل محافظة',
                            ])
                            ->required()
                            ->reactive()
                            ->default('flat'),
                    ]),

                Section::make('سعر الشحن الثابت')
                    ->schema([
                        Forms\Components\TextInput::make('flat_rate')
                            ->label('تكلفة الشحن الثابتة')
                            ->numeric()
                            ->required()
                            ->minValue(0)
                            ->suffix('ج.م')
                            ->default(50),
                    ])
                    ->visible(fn (Get $get) => $get('shipping_type') === 'flat'),

                Section::make('أسعار الشحن حسب المحافظة')
                    ->description('أدخل سعر الشحن لكل محافظة بالجنيه المصري')
                    ->schema(
                        collect(UserAddress::getEgyptGovernorates())->map(fn ($label, $key) =>
                            Forms\Components\TextInput::make("gov_{$key}")
                                ->label($label)
                                ->numeric()
                                ->minValue(0)
                                ->suffix('ج.م')
                                ->default(0)
                        )->values()->toArray()
                    )
                    ->columns(3)
                    ->visible(fn (Get $get) => $get('shipping_type') === 'per_governorate'),
            ])
            ->statePath('data');
    }

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

        $governorateRates = [];
        foreach (UserAddress::getEgyptGovernorates() as $key => $label) {
            $fieldKey = "gov_{$key}";
            if (isset($data[$fieldKey])) {
                $governorateRates[$key] = (float) $data[$fieldKey];
            }
        }

        $settings = ShippingSetting::first();
        $saveData = [
            'shipping_type' => $data['shipping_type'],
            'flat_rate' => $data['flat_rate'] ?? 0,
            'governorate_rates' => $governorateRates,
        ];

        if ($settings) {
            $settings->update($saveData);
        } else {
            ShippingSetting::create($saveData);
        }

        Notification::make()
            ->title('تم حفظ إعدادات الشحن بنجاح')
            ->success()
            ->send();
    }
}
