<?php

namespace App\Livewire\Reservation\Purchases;

use App\Models\Reservation\Order;
use App\Models\Ad;
use App\Models\CustomerReview;
use App\Models\Reservation\OrderStatusHistory;
use App\Models\Wallets\Wallet;
use Livewire\Component;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Filament\Tables\Actions\Action;
use Livewire\Attributes\Url;
use App\Settings\GeneralSettings;
use App\Settings\SEOSettings;
use Artesaos\SEOTools\Traits\SEOTools as SEOToolsTrait;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Builder;
use Mokhosh\FilamentRating\Components\Rating;
use Illuminate\Support\Str;

/**
 * MyAds Component.
 * Allows users to view and manage their ads with actions like preview, edit, and delete.
 */
class MyPurchases extends Component implements HasForms, HasTable
{
    use InteractsWithTable, InteractsWithForms, SEOToolsTrait;

    #[Url(as: 'ref', keep: true)]
    public $referrer = '/';
    public $activeTab = null;

    protected $listeners = ['tabChanged'];

    public $isDisplayTabs;
    public $tabs = [];
    /**
     * Mount lifecycle hook.
     */
    public function mount()
    {
        $this->setSeoData();

        if (is_ecommerce_active()) {
            $this->tabs[] = RESERVATION_TYPE_RETAIL;
            $this->activeTab = RESERVATION_TYPE_RETAIL;
        }

        if (isEnablePointSystem()) {
            $this->tabs[] = RESERVATION_TYPE_POINT_VAULT;
            $this->activeTab = $this->activeTab ?? RESERVATION_TYPE_POINT_VAULT;
        }

        $this->isDisplayTabs = false;
    }

    public function getQueryProperty()
    {
        return Order::query()->where('user_id', auth()->id())
            ->when($this->activeTab == RESERVATION_TYPE_RETAIL, fn($q) => $q->where('order_type', RESERVATION_TYPE_RETAIL))
            ->when($this->activeTab == RESERVATION_TYPE_POINT_VAULT, fn($q) => $q->where('order_type', RESERVATION_TYPE_POINT_VAULT));;
    }

    /**
     * Defines the table structure for displaying ads.
     */

    public function table(Table $table): Table
    {
        return $table
            ->query($this->query)
            ->poll('1s')
            ->emptyStateIcon('/images/not-found.svg')
            ->modifyQueryUsing(fn(Builder $query) => $query->latest())
            ->columns([
                TextColumn::make('order_number')
                    ->label(__('messages.t_my_purchase_order_number'))
                    ->sortable(),
                TextColumn::make('order_date')
                    ->label(__('messages.t_my_purchase_order_date'))
                    ->sortable(),
                TextColumn::make('points')
                    ->label(__('messages.t_my_purchase_points'))
                    ->visible(fn($livewire) => $this->activeTab == RESERVATION_TYPE_POINT_VAULT)
                    ->sortable(),
                TextColumn::make('total_amount')
                    ->label(__('messages.t_my_purchase_total_amount'))
                    ->hidden(fn($livewire) => $this->activeTab == RESERVATION_TYPE_POINT_VAULT)
                    ->sortable(),
                TextColumn::make('discount_amount')
                    ->label(__('messages.t_my_purchase_discount_amount'))
                    ->hidden(fn($livewire) => $this->activeTab == RESERVATION_TYPE_POINT_VAULT)
                    ->sortable(),
                TextColumn::make('subtotal_amount')
                    ->label(__('messages.t_my_purchase_subtotal_amount'))
                    ->hidden(fn($livewire) => $this->activeTab == RESERVATION_TYPE_POINT_VAULT)
                    ->sortable(),
                TextColumn::make('payment_method')
                    ->badge()
                    ->hidden(fn($livewire) => $this->activeTab == RESERVATION_TYPE_POINT_VAULT)
                    ->color('success')
                    ->formatStateUsing(fn(string $state): string => Str::title($state))
                    ->label(__('messages.t_my_purchase_payment_method'))
                    ->sortable(),
                TextColumn::make('payment_status')
                    ->badge()
                    ->label(fn($livewire) => ($this->activeTab == RESERVATION_TYPE_POINT_VAULT) ? __('messages.t_my_purchase_point_earned') : __('messages.t_my_purchase_payment_status'))
                    ->default('-')
                    ->color(fn(string $state): string => match ($state) {
                        'completed' => 'success',
                        'pending' => 'info',
                        default => 'warning'
                    })
                    ->formatStateUsing(fn(string $state): string => Str::title($state))
                    ->label(__('messages.t_my_purchase_payment_status'))
                    ->sortable(),
                TextColumn::make('status')
                    ->badge()
                    ->default(function ($record) {
                        return $record->histories()->whereNotNull('action_date')->orderBy('updated_at', 'desc')->first()?->action;
                    })
                    ->color(fn(string $state): string => match ($state) {
                        'order_request' => 'info',
                        'order_accepted' => 'info',
                        'order_processed' => 'warning',
                        'order_shipped' => 'warning',
                        'order_delivered' => 'success',
                        'order_received' => 'info',
                        'order_cancelled' => 'danger',
                        'order_rejected' => 'danger',
                        default => 'info'
                    })
                    ->formatStateUsing(fn(string $state): string => str_replace('_', ' ', Str::title($state)))
                    ->label(__('messages.t_my_purchase_status')),
                TextColumn::make('transaction_id')
                    ->label(__('messages.t_my_purchase_transaction_id'))
                    ->sortable()
                    ->hidden(fn($livewire) => $this->activeTab == RESERVATION_TYPE_POINT_VAULT),
            ])
            ->filters([
                // Add filters if needed
            ])
            ->headerActions([
                Action::make('Refresh')
                    ->icon('heroicon-o-arrow-path')
                    ->action(fn() => $this->dispatch('refreshTable'))
            ])
            ->actions([
                Action::make('confirm_order_received')->action(function ($record) {
                    $record->histories()->where('action', 'order_received')->first()?->update([
                        'action_date' => now()
                    ]);
                })->button()->visible(function ($record) {
                    return $record->histories()->whereNotNull('action_date')->where('action', 'order_delivered')->exists() && $record->histories()->whereNull('action_date')->where('action', 'order_received')->exists();
                }),
                Action::make('write_a_here')
                    ->icon('heroicon-o-pencil-square')
                    ->color('info')
                    ->label(__('messages.t_my_purchase_write_a_review'))
                    ->form([
                        Select::make('product')
                            ->required()
                            ->options(function ($record) {
                                return Ad::whereIn('id', $record->items->pluck('ad_id'))->pluck('title', 'id')->toArray();
                            })->disableOptionWhen(fn(string $value, $record): bool => in_array($value, CustomerReview::where('order_id', $record->id)->pluck('reviewable_id')->toArray())),
                        Rating::make('rate_your_self')
                            ->label(__('messages.t_my_purchase_rate_the_product'))
                            ->required()
                            ->size('lg')
                            ->helperText(__('messages.t_my_purchase_rate_the_product_helper')),
                        Textarea::make('write_your_feedback')->maxLength(300)
                            ->rows(10)
                            ->cols(20)
                            ->helperText(__('messages.t_my_purchase_write_your_feedback'))
                    ])->action(function ($data, $record) {
                        $record->customerReviews()->create([
                            'reviewable_id' => $data['product'],
                            'reviewable_type' => Ad::class,
                            'rating' => $data['rate_your_self'],
                            'feedback' => $data['write_your_feedback'],
                            'user_id' => auth()->user()->id
                        ]);

                        Notification::make()
                            ->title(__('messages.t_my_purchase_review_send_successfully'))
                            ->success()
                            ->send();
                    })
                    ->visible(function ($record) {
                        return $record->histories()->whereNotNull('action_date')->where('action', 'order_delivered')->exists();
                    }),
                Action::make('view')
                    ->icon('heroicon-o-eye')
                    ->label(__('messages.t_my_purchase_view_my_purchases'))
                    ->action(function ($record) {
                        return redirect()->route('reservation.view-purchases', $record->id);
                    })
                    ->openUrlInNewTab(),
            ])
            ->bulkActions([]);
    }


    public function setActiveTab($tab)
    {
        $this->activeTab = $tab;

        $this->getQueryProperty();
    }

    /**
     * Set SEO data
     */
    protected function setSeoData()
    {
        $generalSettings = app(GeneralSettings::class);
        $seoSettings = app(SEOSettings::class);

        $separator = $generalSettings->separator ?? '-';
        $siteName = $generalSettings->site_name ?? app_name();

        $title = __('messages.t_seo_my_purchases_title') . " $separator " . $siteName;
        $description = $seoSettings->meta_description;

        $this->seo()->setTitle($title);
        $this->seo()->setDescription($description);
    }

    /**
     * Renders the MyAds view.
     */
    public function render()
    {
        return view('livewire.reservation.purchases.my-purchases');
    }
}
