<?php

namespace App\Livewire\Ad\PostAd;

use App\Foundation\AdBase\BaseAdDetail;
use App\Models\Ad;
use App\Models\AdType;
use App\Models\Category;
use App\Settings\AdSettings;
use Filament\Forms\Components\Fieldset;
use Filament\Forms\Components\Group;
use Livewire\Attributes\On;
use Filament\Forms\Components\Select;
use Filament\Forms\Form;
use Filament\Forms\Get;

class AdDetail extends BaseAdDetail
{
    public function detailForm(): Form
    {
        return $this->makeForm()
            ->schema([
                $this->getCategoryId(),
                $this->getForSaleByToggle(),
                $this->createSkuInput(),
                $this->getDescription(),
                $this->getConditionToggle(),
                Fieldset::make()->schema([
                    $this->getPriceTypeSelect(),
                    $this->getPriceInput(),
                    $this->getOfferPriceInput(),
                    $this->getPriceSuffixSelect(),
                ]),
                // $this->getGroupedPriceFields(),
                Fieldset::make('Contact Information')->schema([
                    $this->getDisplayPhoneToggle(),
                    $this->getPhoneNumberInput(),
                    $this->getSameNumberToggle(),
                    $this->getWhatsappNumberInput(),
                ]),
                $this->createReturnPolicySelect(),
                $this->createCashOnDeliveryToggle(),
                $this->getTagsInput(),
            ]);
    }

    /**
     * Get all form definitions.
     *
     * @return array
     */
    protected function getForms(): array
    {
        return [
            'titleInput',
            'detailForm',
        ];
    }

    /**
     * Handle updates to component properties.
     *
     * @param string $name
     * @param mixed $value
     */
    public function updated($name, $value)
    {
        $this->checkRequiredFieldsFilled();
        $userId = auth()->id();
        $this->validateOnly($name);

        if (!$this->id) {
            if (!$userId) {
                abort(403, 'Unauthorized action.');
            }
            $ad = Ad::create([$name => $value, 'user_id' => $userId]);
            if (AdType::get()->count() == 1) {
                $ad->ad_type_id = AdType::get()->first()->id;
                $ad->save();
            }
            $this->id = $ad->id;
            $this->updateAdSlug($ad, $value);
            $this->loadAdDetails($this->id);
        } else {
            $ad = Ad::find($this->id);

            if (!$ad || $ad->user_id != $userId) {
                abort(403, 'Unauthorized action.');
            }

            // Update the "tags" property if it's an array element update
            if (str_starts_with($name, 'tags.')) {
                $index = explode('.', $name)[1];
                $tags = $this->tags;
                $tags[$index] = $value;
                $this->tags = $tags;
                $ad->update(['tags' => json_encode($tags)]);
            } else {
                // Handle title updates with slug condition
                if ($name === 'title' && !$this->requiresAdminApproval($ad)) {
                    $ad->update(['title' => $value]);
                    $this->updateAdSlug($ad->fresh(), $value); // Update slug if no approval required
                } else {
                    $ad->update([$name => $value]);
                }
                if ($name == 'category_id') {
                    $this->disable_condition = $ad->adType?->disable_condition;
                    $this->disable_price_type = $ad->adType?->disable_price_type;

                    // If the sub category is updated, update the location if it has default location
                    $this->updateLocation($ad, $value);
                }
            }

            if ($name == 'sub_category_id') {
                if ($value) {
                    $this->category_id =  $value;
                    $this->ad->category_id = $value;
                    $this->ad->save();
                } else {
                    $this->category_id =  $this->parent_category;
                    $this->ad->category_id = $this->parent_category;
                    $this->ad->save();
                }
                
                $this->child_category_id = null;
            }
        }

        if ($name == 'category_id') {
            $this->enableECommerce = $this->ad->adType?->marketplace == ONLINE_SHOP_MARKETPLACE ?? false;
        }

        $this->dispatch('ad-created', id: $ad->id);
    }

    /**
     * Check if admin approval is required for this ad.
     *
     * @param Ad $ad
     * @return bool
     */
    protected function requiresAdminApproval($ad)
    {
        return app(AdSettings::class)->admin_approval_required && $ad->status && $ad->status->value !== 'draft';
    }

    public function getRequiredFieldsProperty()
    {
        $requiredFields = [];
        $rules = $this->getRules();

        foreach ($rules as $field => $rule) {
            if (is_array($rule) && in_array('required', $rule)) {
                $requiredFields[] = $field;
            } elseif ($rule == 'required') {
                $requiredFields[] = $field;
            }
        }

        return $requiredFields;
    }

    public function checkRequiredFieldsFilled()
    {
        $isFilled = false;
        foreach ($this->requiredFields as $field) {
            if (trim($this->$field) !== '' && (!empty(trim($this->$field))) && (!is_null(trim($this->$field)))) {
                $isFilled = true;
            } else {
                $isFilled = false;
                break;
            }
        }

        if (isset($this->display_phone) && $this->display_phone && (!empty($this->phone_number))) {
            $isFilled = $isFilled ? true : false;
        }
        if (isset($this->display_whatsapp) && $this->display_whatsapp && (!empty($this->whatsapp_number))) {
            $isFilled = $isFilled ? true : false;
        }
        $this->dispatch('required-fields-filled', isFilled: $isFilled);
    }
    /**
     * Handle the next button click.
     */
    #[On('next-clicked')]
    public function next()
    {
        $this->validate();

        if (!$this->parent_category) {
            $this->addError('parent_category', __('messages.t_select_main_category'));
            return;
        }

        $this->dispatch('validate-dynamic-fields');
    }

    public function getCurrentCategory()
    {
        if ($this->id) {
            return Category::whereHas('ads', fn($query) => $query->whereId($this->id))->first();
        }
    }

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

        $adData = $this->only([
            'title',
            'category_id',
            'description',
            'price',
            'price_type_id',
            'condition_id',
            'display_phone',
            'phone_number',
            'for_sale_by',
            'tags',
            'price_suffix',
            'offer_price',
            'whatsapp_number',
            'display_whatsapp',
        ]);

        if ($this->id) {
            $ad = Ad::find($this->id);
            $ad->update($adData);
        }
        // else {
        //      $ad = Ad::create(array_merge($adData, ['user_id' => auth()->id()]));
        // }

        $this->updateAdSlug($ad, $this->title);

        $this->dispatch('ad-saved', id: $ad->id);
        return $this->redirect('/ads');
    }

    /**
     * Render the component view.
     *
     * @return \Illuminate\View\View
     */
    public function render()
    {
        return view('livewire.ad.post-ad.ad-detail');
    }
}
