<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ReturnRequestResource\Pages\CreateReturnRequest;
use App\Filament\Resources\ReturnRequestResource\Pages\EditReturnRequest;
use App\Filament\Resources\ReturnRequestResource\Pages\ListReturnRequests;
use App\Models\ReturnRequest;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use BackedEnum;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\ToggleButtons;
use Filament\Forms\Components\Hidden;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Resources\Resource;
use Illuminate\Support\HtmlString;

class ReturnRequestResource extends Resource
{
    protected static ?string $model = ReturnRequest::class;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-arrow-path';

    protected static string|\UnitEnum|null $navigationGroup = 'Orders';

    protected static ?int $navigationSort = 2;

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::whereIn('status', ['pending', 'approved', 'processing'])->count() ?: null;
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return 'warning';
    }

    public static function form(Schema $schema): Schema
    {
        $fillOrderData = function ($state, callable $set) {
            if (!$state) return;
            $order = Order::find($state);
            if ($order) {
                $set('user_id', $order->user_id);
                $refund = $order->is_exchange 
                    ? max(0, (float) $order->discount - (float) $order->subtotal - (float) $order->shipping_cost)
                    : max(0, (float) $order->subtotal - (float) $order->discount);
                $set('refund_amount', $refund);
                
                // Auto-populate items repeater
                $items = [];
                foreach ($order->items as $item) {
                    $items[] = [
                        'order_item_id' => $item->id,
                        'quantity' => $item->quantity,
                        'price' => $item->price,
                    ];
                }
                $set('items', $items);
            }
        };

        return $schema
            ->components([
                Grid::make([
                    'default' => 1,
                    'lg' => 12,
                ])
                ->schema([
                    // Main left column (span 8)
                    Grid::make(1)
                        ->schema([
                            Section::make('Associated Order & Customer')
                                ->description('Select the order and view associated customer information.')
                                ->schema([
                                    Select::make('order_id')
                                        ->label('Order')
                                        ->default(fn () => request()->query('order_id'))
                                        ->options(fn (?ReturnRequest $record) => Order::query()
                                            ->where('status', 'delivered')
                                            ->when($record?->order_id, fn ($query, $id) => $query->orWhere('id', $id))
                                            ->get()
                                            ->mapWithKeys(fn ($order) => [$order->id => "Order #{$order->order_number} — {$order->customer_name}"])
                                        )
                                        ->required()
                                        ->searchable()
                                        ->live()
                                        ->afterStateUpdated(fn ($state, callable $set) => $fillOrderData($state, $set))
                                        ->columnSpan(2),

                                    Placeholder::make('customer_details')
                                        ->label('Customer Information')
                                        ->content(function ($get) {
                                            $orderId = $get('order_id');
                                            if (!$orderId) {
                                                return new HtmlString('<span class="text-gray-400 text-sm">Select an order to view customer details</span>');
                                            }
                                            $order = Order::find($orderId);
                                            if (!$order) {
                                                return new HtmlString('<span class="text-gray-400 text-sm">Select an order to view customer details</span>');
                                            }
                                            return new HtmlString("
                                                <div class='text-sm space-y-1 text-gray-700 bg-gray-50 p-2.5 rounded-lg border'>
                                                    <div><strong>Name:</strong> {$order->customer_name}</div>
                                                    <div><strong>Phone:</strong> {$order->customer_phone}</div>
                                                    <div><strong>Email:</strong> " . ($order->customer_email ?? 'N/A') . "</div>
                                                </div>
                                            ");
                                        })
                                        ->columnSpan(2),

                                    Placeholder::make('order_links')
                                        ->label('Related Orders & Summary')
                                        ->content(function (?ReturnRequest $record, $get) {
                                            $orderId = $get('order_id');
                                            $exchangeOrderId = $record?->exchange_order_id;
                                            
                                            $html = "<div class='text-sm space-y-2'>";
                                            
                                            if ($orderId) {
                                                $order = Order::find($orderId);
                                                if ($order) {
                                                    $url = \App\Filament\Resources\Orders\OrderResource::getUrl('edit', ['record' => $order->id]);
                                                    $html .= "<div>
                                                        <span class='text-gray-500 dark:text-gray-400'>Original Order:</span>
                                                        <a href='{$url}' class='text-primary-600 dark:text-primary-400 hover:underline font-semibold ml-1' style='display: inline-flex; align-items: center; gap: 0.25rem;'>
                                                            #{$order->order_number}
                                                            <svg class='w-4 h-4' fill='none' stroke='currentColor' viewBox='0 0 24 24' style='width: 1rem; height: 1rem;'>
                                                                <path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25'></path>
                                                            </svg>
                                                        </a>
                                                    </div>";
                                                }
                                            }
                                            
                                            if ($exchangeOrderId) {
                                                $exchangeOrder = Order::find($exchangeOrderId);
                                                if ($exchangeOrder) {
                                                    $url = \App\Filament\Resources\Orders\OrderResource::getUrl('edit', ['record' => $exchangeOrder->id]);
                                                    $html .= "<div>
                                                        <span class='text-gray-500 dark:text-gray-400'>Exchange Order (New):</span>
                                                        <a href='{$url}' class='text-primary-600 dark:text-primary-400 hover:underline font-semibold ml-1' style='display: inline-flex; align-items: center; gap: 0.25rem;'>
                                                            #{$exchangeOrder->order_number}
                                                            <svg class='w-4 h-4' fill='none' stroke='currentColor' viewBox='0 0 24 24' style='width: 1rem; height: 1rem;'>
                                                                <path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25'></path>
                                                            </svg>
                                                        </a>
                                                    </div>";
                                                    
                                                    // Eager load items for calculations
                                                    $exchangeOrder->loadMissing('items');
                                                    $record->loadMissing('items');
                                                    
                                                    $returnedValue = $record->items->sum(fn ($item) => (float) $item->price * (int) $item->quantity);
                                                    $exchangeValue = $exchangeOrder->items->sum(fn ($item) => (float) $item->price * (int) $item->quantity);
                                                    $shippingCost = (float) $exchangeOrder->shipping_cost;
                                                    $exchangeDiscount = max(0.00, (float) $exchangeOrder->discount - $returnedValue);
                                                    
                                                    $cod = (float) $exchangeOrder->grand_total;
                                                    $refund = (float) $record->refund_amount;

                                                    $refundRow = '';
                                                    if ($refund > 0) {
                                                        $refundRow = "
                                                            <span style='opacity: 0.7; color: #3b82f6;'>Refundable Amount:</span>
                                                            <span style='font-weight: 600; color: #3b82f6; text-align: right;'>৳" . number_format($refund, 2) . "</span>
                                                        ";
                                                    }

                                                    $html .= "
                                                        <div style='margin-top: 1rem; padding: 1.25rem; background: rgba(128, 128, 128, 0.05); border: 1px solid rgba(128, 128, 128, 0.15); border-radius: 0.75rem; font-family: inherit; color: inherit; width: 100%; box-sizing: border-box;'>
                                                            <h3 style='margin: 0 0 1rem 0; font-size: 0.95rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.8; border-bottom: 1px dashed rgba(128, 128, 128, 0.25); padding-bottom: 0.5rem;'>
                                                                Exchange Financial Summary
                                                            </h3>
                                                            <div style='display: grid; grid-template-columns: 1fr auto; gap: 0.75rem; font-size: 0.875rem; line-height: 1.25rem;'>
                                                                
                                                                <span style='opacity: 0.7;'>Total Returned Value (Credit):</span>
                                                                <span style='font-weight: 600; text-align: right;'>৳" . number_format($returnedValue, 2) . "</span>
                                                                
                                                                <span style='opacity: 0.7;'>Total Exchanged Value (New Items):</span>
                                                                <span style='font-weight: 600; text-align: right;'>৳" . number_format($exchangeValue, 2) . "</span>
                                                                
                                                                <span style='opacity: 0.7;'>Exchange Delivery Charge:</span>
                                                                <span style='font-weight: 600; text-align: right;'>+ ৳" . number_format($shippingCost, 2) . "</span>
                                                                
                                                                <span style='opacity: 0.7;'>Additional Discount:</span>
                                                                <span style='font-weight: 600; color: #ef4444; text-align: right;'>- ৳" . number_format($exchangeDiscount, 2) . "</span>
                                                                
                                                                {$refundRow}
                                                                
                                                                <div style='grid-column: span 2; border-top: 2px solid rgba(128, 128, 128, 0.15); margin: 0.5rem 0; padding-top: 0.75rem; display: grid; grid-template-columns: 1fr auto; align-items: center;'>
                                                                    <span style='font-size: 1rem; font-weight: 800;'>Total COD to Collect:</span>
                                                                    <span style='font-size: 1.25rem; font-weight: 800; color: #22c55e; text-align: right;'>৳" . number_format($cod, 2) . "</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    ";
                                                }
                                            }
                                            
                                            if (!$orderId && !$exchangeOrderId) {
                                                return new HtmlString('<span class="text-gray-400">No related orders linked</span>');
                                            }
                                            
                                            $html .= "</div>";
                                            return new HtmlString($html);
                                        })
                                        ->columnSpan(4),

                                    Hidden::make('user_id')
                                        ->default(fn () => Order::find(request()->query('order_id'))?->user_id)
                                        ->dehydrated(),
                                ])
                                ->columns(4),

                            Section::make('Returned Items')
                                ->description('Select the items from the order that are being returned.')
                                ->schema([
                                    Repeater::make('items')
                                        ->relationship('items')
                                        ->hiddenLabel()
                                        ->addActionLabel('Add Item')
                                        ->default(function () {
                                            $orderId = request()->query('order_id');
                                            if (!$orderId) return [];
                                            $order = Order::find($orderId);
                                            if (!$order) return [];
                                            $items = [];
                                            foreach ($order->items as $item) {
                                                $items[] = [
                                                    'order_item_id' => $item->id,
                                                    'quantity' => $item->quantity,
                                                    'price' => $item->price,
                                                ];
                                            }
                                            return $items;
                                        })
                                        ->schema([
                                            Grid::make(12)
                                                ->schema([
                                                    Select::make('order_item_id')
                                                        ->label('Product Item')
                                                        ->options(function (callable $get, $livewire) {
                                                            $orderId = $get('../../order_id') ?? $get('../order_id') ?? ($livewire->record?->order_id ?? null);
                                                            if (!$orderId) {
                                                                return [];
                                                            }
                                                            return OrderItem::where('order_id', $orderId)
                                                                ->get()
                                                                ->pluck('product_name', 'id');
                                                        })
                                                        ->required()
                                                        ->live()
                                                        ->afterStateUpdated(function ($state, callable $set) {
                                                            $item = OrderItem::find($state);
                                                            if ($item) {
                                                                $set('price', $item->price);
                                                            }
                                                        })
                                                        ->columnSpan(5),
                                                    
                                                    Placeholder::make('product_image')
                                                        ->label('Image')
                                                        ->content(function ($get) {
                                                            $orderItemId = $get('order_item_id');
                                                            if (!$orderItemId) {
                                                                return new HtmlString('<div class="w-12 h-12 bg-gray-50 rounded flex items-center justify-center text-xs text-gray-400 border border-dashed border-gray-200">No Image</div>');
                                                            }
                                                            $orderItem = OrderItem::find($orderItemId);
                                                            if (!$orderItem) {
                                                                return new HtmlString('<div class="w-12 h-12 bg-gray-50 rounded flex items-center justify-center text-xs text-gray-400 border border-dashed border-gray-200">No Image</div>');
                                                            }
                                                            $product = $orderItem->product;
                                                            if (!$product) {
                                                                return new HtmlString('<div class="w-12 h-12 bg-gray-50 rounded flex items-center justify-center text-xs text-gray-400 border border-dashed border-gray-200">No Image</div>');
                                                            }
                                                            $imageUrl = $product->getFirstMediaUrl('images', 'webp') ?: '/images/placeholder.jpg';
                                                            return new HtmlString('<img src="' . $imageUrl . '" class="w-12 h-12 object-cover rounded border shadow-sm" />');
                                                        })
                                                        ->columnSpan(2),

                                                    TextInput::make('quantity')
                                                        ->label('Qty')
                                                        ->numeric()
                                                        ->required()
                                                        ->default(1)
                                                        ->columnSpan(2),

                                                    TextInput::make('price')
                                                        ->label('Unit Price')
                                                        ->numeric()
                                                        ->required()
                                                        ->prefix('৳')
                                                        ->columnSpan(3),
                                                ])
                                        ])
                                        ->columnSpanFull()
                                ]),

                            Section::make('Refund Details')
                                ->schema([
                                    TextInput::make('refund_amount')
                                        ->label('Refund Amount')
                                        ->numeric()
                                        ->prefix('৳')
                                        ->default(function () {
                                            $order = Order::find(request()->query('order_id'));
                                            if (!$order) return 0.00;
                                            return $order->is_exchange 
                                                ? max(0, (float) $order->discount - (float) $order->subtotal - (float) $order->shipping_cost)
                                                : max(0, (float) $order->subtotal - (float) $order->discount);
                                        }),

                                    Select::make('refund_method')
                                        ->label('Refund Method')
                                        ->options([
                                            'bkash' => 'bKash',
                                            'nagad' => 'Nagad',
                                            'bank' => 'Bank Transfer',
                                            'cash' => 'Cash/Other',
                                        ])
                                        ->nullable(),

                                    TextInput::make('refund_details')
                                        ->label('Account/Txn Details')
                                        ->placeholder('e.g., Phone number or Txn ID')
                                        ->maxLength(255),
                                ])
                                ->columns(3),

                            Section::make('Notes & Explanations')
                                ->schema([
                                    Textarea::make('customer_notes')
                                        ->label('Customer Explanations')
                                        ->rows(3)
                                        ->placeholder('Notes submitted by the customer...'),
                                    Textarea::make('admin_notes')
                                        ->label('Internal Admin Notes')
                                        ->rows(3)
                                        ->placeholder('Internal notes visible to administrators only...'),
                                ])
                                ->columns(2),
                        ])
                        ->columnSpan(8),

                    // Sidebar right column (span 4)
                    Grid::make(1)
                        ->schema([
                            Section::make('Status & Type')
                                ->schema([
                                    ToggleButtons::make('status')
                                        ->label('Request Status')
                                        ->options([
                                            'pending' => 'Pending',
                                            'approved' => 'Approved',
                                            'rejected' => 'Rejected',
                                            'processing' => 'Processing',
                                            'completed' => 'Completed',
                                        ])
                                        ->colors([
                                            'pending' => 'warning',
                                            'approved' => 'info',
                                            'rejected' => 'danger',
                                            'processing' => 'warning',
                                            'completed' => 'success',
                                        ])
                                        ->icons([
                                            'pending' => 'heroicon-m-clock',
                                            'approved' => 'heroicon-m-check-circle',
                                            'rejected' => 'heroicon-m-x-circle',
                                            'processing' => 'heroicon-m-arrow-path',
                                            'completed' => 'heroicon-m-check-badge',
                                        ])
                                        ->default('pending')
                                        ->disabled()
                                        ->dehydrated()
                                        ->inline()
                                        ->columnSpanFull(),

                                    ToggleButtons::make('type')
                                        ->label('Request Type')
                                        ->options([
                                            'return' => 'Return/Exchange',
                                            'refund' => 'Refund/Return',
                                        ])
                                        ->colors([
                                            'return' => 'gray',
                                            'refund' => 'purple',
                                        ])
                                        ->icons([
                                            'return' => 'heroicon-m-arrow-uturn-left',
                                            'refund' => 'heroicon-m-currency-bangladeshi',
                                        ])
                                        ->required()
                                        ->disabled(fn (?ReturnRequest $record) => $record && $record->exchange_order_id !== null)
                                        ->dehydrated()
                                        ->inline()
                                        ->columnSpanFull(),

                                    Select::make('reason')
                                        ->label('Reason')
                                        ->options([
                                            'damaged' => 'Damaged Product',
                                            'wrong_item' => 'Wrong Item Delivered',
                                            'size_issue' => 'Size Issue',
                                            'other' => 'Other / Change of Mind',
                                        ])
                                        ->required(),
                                ]),

                            Section::make('Timeline & Metadata')
                                ->schema([
                                    Placeholder::make('created_at')
                                        ->label('Submitted At')
                                        ->content(fn (?ReturnRequest $record): string => $record?->created_at?->format('M j, Y \a\t H:i') ?? '—'),
                                    Placeholder::make('updated_at')
                                        ->label('Last Modified')
                                        ->content(fn (?ReturnRequest $record): string => $record?->updated_at?->diffForHumans() ?? '—'),
                                ])
                                ->collapsible()
                                ->collapsed()
                                ->hidden(fn (?ReturnRequest $record) => $record === null),
                        ])
                        ->columnSpan(4),
                ])
                ->columnSpanFull()
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // Request ID — compact, monospace, sortable
                TextColumn::make('id')
                    ->label('#')
                    ->sortable()
                    ->alignCenter()
                    ->formatStateUsing(fn ($state) => '#' . $state)
                    ->extraAttributes(['style' => 'font-family:monospace;font-weight:700;font-size:0.8rem;color:#6366f1;']),

                // Order Number
                TextColumn::make('order.order_number')
                    ->label('Order')
                    ->searchable()
                    ->sortable()
                    ->extraAttributes(['style' => 'font-family:monospace;font-size:0.8rem;']),

                // Customer
                TextColumn::make('user.name')
                    ->label('Customer')
                    ->searchable()
                    ->sortable()
                    ->default('Guest')
                    ->icon('heroicon-m-user-circle')
                    ->iconColor('gray'),

                // Returned Products — clean thumbnail + name layout
                TextColumn::make('items_summary')
                    ->label('Returned Products')
                    ->html()
                    ->state(function (ReturnRequest $record): string {
                        $output = [];
                        foreach ($record->items as $item) {
                            $orderItem = $item->orderItem;
                            if (!$orderItem) continue;
                            $product = $orderItem->product;
                            if (!$product) continue;
                            $imageUrl = $product->getFirstMediaUrl('images', 'webp') ?: '/images/placeholder.jpg';
                            $name = e($product->name);
                            $qty  = $item->quantity;
                            $output[] = "
                                <div style='display:flex;align-items:center;gap:8px;margin-bottom:6px;'>
                                    <img src='{$imageUrl}' style='width:32px;height:32px;object-fit:cover;border-radius:6px;border:1px solid #e5e7eb;flex-shrink:0;' />
                                    <span style='font-size:0.8125rem;color:#374151;line-height:1.3;'>
                                        {$name}
                                        <span style='color:#9ca3af;font-size:0.75rem;'>(x{$qty})</span>
                                    </span>
                                </div>";
                        }
                        return !empty($output)
                            ? '<div style="padding:2px 0;">' . implode('', $output) . '</div>'
                            : '<span style="color:#9ca3af;font-size:0.8125rem;font-style:italic;">No items</span>';
                    }),

                // Type badge
                TextColumn::make('type')
                    ->label('Type')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'return' => 'Return/Exchange',
                        'refund' => 'Refund/Return',
                        default  => ucfirst($state),
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'return' => 'gray',
                        'refund' => 'purple',
                        default  => 'gray',
                    }),

                // Status badge
                TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending'    => 'warning',
                        'approved'   => 'info',
                        'rejected'   => 'danger',
                        'processing' => 'warning',
                        'completed'  => 'success',
                        default      => 'gray',
                    }),

                // Reason — toggleable, shown by default
                TextColumn::make('reason')
                    ->label('Reason')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'damaged'    => 'Damaged',
                        'wrong_item' => 'Wrong Item',
                        'size_issue' => 'Size Issue',
                        default      => ucfirst(str_replace('_', ' ', $state)),
                    })
                    ->badge()
                    ->color('gray')
                    ->toggleable(isToggledHiddenByDefault: true),

                // Refund amount — toggleable
                TextColumn::make('refund_amount')
                    ->label('Refund')
                    ->money('BDT')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                // Submitted time — always visible, newest first
                TextColumn::make('created_at')
                    ->label('Submitted')
                    ->since()
                    ->sortable()
                    ->tooltip(fn ($record) => $record->created_at->format('M j, Y H:i'))
                    ->extraAttributes(['style' => 'font-size:0.8rem;color:#6b7280;white-space:nowrap;']),
            ])
            ->defaultSort('created_at', 'desc')
            ->recordUrl(fn (ReturnRequest $record): string => static::getUrl('edit', ['record' => $record]))
            ->filters([
                //
            ])
            ->actions([
                EditAction::make()->iconButton(),
                DeleteAction::make()->iconButton(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ])
            ->striped()
            ->paginated([10, 25, 50]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListReturnRequests::route('/'),
            'create' => CreateReturnRequest::route('/create'),
            'edit' => EditReturnRequest::route('/{record}/edit'),
        ];
    }
}