<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use App\Services\CourierService;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Filament\Notifications\Notification;

class RecentOrdersWidget extends BaseWidget
{
    protected static ?int $sort = 4;

    protected int|string|array $columnSpan = 'full';

    public function getHeading(): ?string
    {
        return null;
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(
                Order::query()->latest()->limit(5)
            )
            ->heading(new \Illuminate\Support\HtmlString('
                <span>Recent Orders</span>
                <style>
                    .recent-orders-table-widget .fi-ta-header-ctn,
                    [class*="RecentOrdersWidget"] .fi-ta-header-ctn,
                    .recent-orders-table-widget div:has(> .fi-ta-header):has(> .fi-ta-toolbar),
                    [class*="RecentOrdersWidget"] div:has(> .fi-ta-header):has(> .fi-ta-toolbar) {
                        display: flex !important;
                        flex-direction: row !important;
                        justify-content: space-between !important;
                        align-items: center !important;
                        gap: 1rem !important;
                        padding: 0.75rem 1.5rem !important;
                        border-bottom: 1px solid rgb(243 244 246) !important;
                    }
                    .recent-orders-table-widget .fi-ta-header,
                    [class*="RecentOrdersWidget"] .fi-ta-header {
                        border-bottom: none !important;
                        padding: 0 !important;
                        margin-bottom: 0 !important;
                    }
                    .recent-orders-table-widget .fi-ta-toolbar,
                    [class*="RecentOrdersWidget"] .fi-ta-toolbar {
                        border-bottom: none !important;
                        padding: 0 !important;
                        margin-top: 0 !important;
                    }
                    .recent-orders-table-widget .fi-ta-header-ctn div,
                    [class*="RecentOrdersWidget"] .fi-ta-header-ctn div,
                    .recent-orders-table-widget div:has(> .fi-ta-header):has(> .fi-ta-toolbar) div,
                    [class*="RecentOrdersWidget"] div:has(> .fi-ta-header):has(> .fi-ta-toolbar) div {
                        border-bottom: none !important;
                    }
                    .recent-orders-table-widget .fi-ta-toolbar .fi-ta-search-field,
                    [class*="RecentOrdersWidget"] .fi-ta-toolbar .fi-ta-search-field {
                        margin-top: 0 !important;
                    }
                </style>
            '))
            ->extraAttributes([
                'class' => 'recent-orders-table-widget',
            ])
            ->columns([
                TextColumn::make('order_number')
                    ->label('Number')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('customer_name')
                    ->label('Customer')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'info',
                        'processing' => 'warning',
                        'shipped' => 'info',
                        'delivered' => 'success',
                        'cancelled' => 'danger',
                        default => 'gray',
                    })
                    ->icon(fn (string $state): ?string => match ($state) {
                        'pending' => 'heroicon-m-sparkles',
                        'processing' => 'heroicon-m-arrow-path',
                        'shipped' => 'heroicon-m-truck',
                        'delivered' => 'heroicon-m-check-circle',
                        'cancelled' => 'heroicon-m-x-circle',
                        default => null,
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'pending' => 'New',
                        default => ucfirst($state),
                    })
                    ->sortable(),
                TextColumn::make('grand_total')
                    ->label('Total price')
                    ->money('BDT')
                    ->alignEnd()
                    ->sortable(),
                TextColumn::make('shipping_cost')
                    ->label('Shipping cost')
                    ->money('BDT')
                    ->alignEnd()
                    ->sortable(),
                TextColumn::make('created_at')
                    ->label('Order date')
                    ->date('M j, Y')
                    ->sortable(),
            ])
            ->recordActions([
                ActionGroup::make([
                    EditAction::make()
                        ->url(fn (Order $record): string => \App\Filament\Resources\Orders\OrderResource::getUrl('edit', ['record' => $record])),
                    Action::make('one_click_ship')
                        ->label('One-Click Ship')
                        ->icon('heroicon-o-truck')
                        ->color('success')
                        ->requiresConfirmation()
                        ->visible(fn (Order $record): bool => in_array($record->status, ['pending', 'processing']) && !$record->courierBooking()->exists())
                        ->action(function (Order $record) {
                            $result = CourierService::bookConsignment($record);
                            if ($result['success']) {
                                Notification::make()
                                    ->title('Shipment Booked')
                                    ->body($result['message'])
                                    ->success()
                                    ->send();
                            } else {
                                Notification::make()
                                    ->title('Booking Failed')
                                    ->body($result['message'])
                                    ->danger()
                                    ->send();
                            }
                        }),
                    Action::make('download_invoice')
                        ->label('Invoice')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->color('info')
                        ->url(fn (Order $record): string => route('orders.invoice', ['order' => $record->id]))
                        ->openUrlInNewTab(),
                ])
                ->color('info'),
            ]);
    }
}
