<?php

namespace App\Livewire\Pricing;

use App\Domain\Pricing\Enums\AdjustmentType;
use App\Domain\Pricing\Enums\PricingRuleType;
use App\Domain\Pricing\Models\PricingRule;
use App\Domain\Shared\Exceptions\DomainException;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إنشاء قاعدة تسعير')]
class CreatePricingRuleWizard extends Component
{
    public int $currentStep = 1;
    public int $totalSteps = 5;
    public bool $completed = false;

    // Step 1: Rule Type
    public string $ruleType = '';

    // Step 2: Conditions (dynamic based on rule_type)
    public ?int $minAge = null;
    public ?int $maxAge = null;
    public ?int $minMonths = null;
    public ?int $minChildren = null;
    public ?int $orderNumber = null;
    public string $targetGender = '';
    public ?int $targetBranchId = null;
    public string $targetClassification = '';
    public string $genericConditions = '';

    // Step 3: Adjustment
    public string $adjustmentType = '';
    public ?int $adjustmentValue = null;
    public ?int $maxDiscountPercent = null;

    // Step 4: Scope & Priority
    public string $nameAr = '';
    public string $name = '';
    public ?string $targetType = null;
    public ?int $targetId = null;
    public ?int $branchId = null;
    public int $priority = 10;
    public bool $isStackable = true;
    public string $effectiveFrom = '';
    public ?string $effectiveTo = null;
    public bool $isActive = true;
    public ?int $usageLimit = null;

    public function mount(): void
    {
        $this->authorize('pricing.create');
        $this->effectiveFrom = now()->toDateString();
    }

    public function getStepLabels(): array
    {
        return [
            1 => 'نوع القاعدة',
            2 => 'الشروط',
            3 => 'التعديل',
            4 => 'النطاق والأولوية',
            5 => 'مراجعة',
        ];
    }

    public function updatedRuleType(): void
    {
        $this->minAge = null;
        $this->maxAge = null;
        $this->minMonths = null;
        $this->minChildren = null;
        $this->orderNumber = null;
        $this->targetGender = '';
        $this->targetBranchId = null;
        $this->targetClassification = '';
        $this->genericConditions = '';
    }

    public function nextStep(): void
    {
        $this->validate($this->rulesForStep($this->currentStep));

        if ($this->currentStep < $this->totalSteps) {
            $this->currentStep++;
        }
    }

    public function previousStep(): void
    {
        if ($this->currentStep > 1) {
            $this->currentStep--;
        }
    }

    public function goToStep(int $step): void
    {
        if ($step < $this->currentStep) {
            $this->currentStep = $step;
        }
    }

    public function confirm(): void
    {
        try {
            DB::transaction(function () {
                PricingRule::create([
                    'academy_id' => app('current_academy')->id,
                    'name_ar' => $this->nameAr,
                    'name' => $this->name ?: null,
                    'rule_type' => $this->ruleType,
                    'adjustment_type' => $this->adjustmentType,
                    'adjustment_value' => $this->adjustmentValue,
                    'conditions' => $this->buildConditions(),
                    'target_type' => $this->targetType ?: null,
                    'target_id' => $this->targetId ?: null,
                    'branch_id' => $this->branchId ?: null,
                    'priority' => $this->priority,
                    'is_stackable' => $this->isStackable,
                    'max_discount_percent' => $this->maxDiscountPercent,
                    'effective_from' => $this->effectiveFrom,
                    'effective_to' => $this->effectiveTo ?: null,
                    'is_active' => $this->isActive,
                    'usage_limit' => $this->usageLimit,
                    'usage_count' => 0,
                    'created_by' => auth()->id(),
                ]);
            });

            $this->completed = true;
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    private function buildConditions(): array
    {
        return match ($this->ruleType) {
            'age' => ['min_age' => $this->minAge, 'max_age' => $this->maxAge],
            'membership_duration' => ['min_months' => $this->minMonths],
            'family_size' => ['min_children' => $this->minChildren],
            'sibling_order' => ['order_number' => $this->orderNumber],
            'gender' => ['target_gender' => $this->targetGender],
            'branch' => ['target_branch_id' => $this->targetBranchId],
            'classification' => ['target_classification' => $this->targetClassification],
            default => json_decode($this->genericConditions ?: '{}', true) ?: [],
        };
    }

    private function rulesForStep(int $step): array
    {
        return match ($step) {
            1 => [
                'ruleType' => 'required|in:' . implode(',', array_column(PricingRuleType::cases(), 'value')),
            ],
            2 => $this->conditionRulesForType(),
            3 => [
                'adjustmentType' => 'required|in:' . implode(',', array_column(AdjustmentType::cases(), 'value')),
                'adjustmentValue' => 'required|integer|min:1',
                'maxDiscountPercent' => 'nullable|integer|min:1|max:100',
            ],
            4 => [
                'nameAr' => 'required|string|min:3|max:255',
                'name' => 'nullable|string|max:255',
                'priority' => 'required|integer|min:1|max:100',
                'effectiveFrom' => 'required|date',
                'effectiveTo' => 'nullable|date|after:effectiveFrom',
                'usageLimit' => 'nullable|integer|min:1',
            ],
            default => [],
        };
    }

    private function conditionRulesForType(): array
    {
        return match ($this->ruleType) {
            'age' => [
                'minAge' => 'nullable|integer|min:1|max:100',
                'maxAge' => 'nullable|integer|min:1|max:100',
            ],
            'membership_duration' => [
                'minMonths' => 'required|integer|min:1',
            ],
            'family_size' => [
                'minChildren' => 'required|integer|min:2',
            ],
            'sibling_order' => [
                'orderNumber' => 'required|integer|min:1',
            ],
            'gender' => [
                'targetGender' => 'required|in:male,female',
            ],
            'branch' => [
                'targetBranchId' => 'required|integer|exists:branches,id',
            ],
            'classification' => [
                'targetClassification' => 'required|in:regular,vip,scholarship,staff_child,trial',
            ],
            default => [],
        };
    }

    public function getRuleTypeLabelProperty(): string
    {
        if (!$this->ruleType) {
            return '';
        }
        return PricingRuleType::from($this->ruleType)->label();
    }

    public function getAdjustmentTypeLabelProperty(): string
    {
        if (!$this->adjustmentType) {
            return '';
        }
        return AdjustmentType::from($this->adjustmentType)->label();
    }

    public function render()
    {
        return view('livewire.pricing.create-pricing-rule-wizard', [
            'ruleTypes' => PricingRuleType::cases(),
            'adjustmentTypes' => AdjustmentType::cases(),
            'branches' => \App\Domain\Identity\Models\Branch::orderBy('name_ar')->get(['id', 'name_ar', 'name']),
        ]);
    }
}
