<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ActivityLogResource\Pages\ListActivityLogs;
use App\Models\ActivityLog;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Placeholder;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;

class ActivityLogResource extends Resource
{
    protected static ?string $model = ActivityLog::class;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document-magnifying-glass';

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

    protected static ?int $navigationSort = 4;

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('created_at')
                    ->label('Time')
                    ->sortable()
                    ->since(),
                TextColumn::make('action')
                    ->label('Event')
                    ->formatStateUsing(fn ($state, $record) => match ($state) {
                        'created' => class_basename($record->loggable_type) . ' Created',
                        'updated' => (function () use ($record) {
                            $model = class_basename($record->loggable_type);
                            if ($model === 'Order') {
                                $props = $record->properties ?? [];
                                $attrs = $props['attributes'] ?? [];
                                if (isset($attrs['status'])) {
                                    return 'Status Changed';
                                }
                                if (isset($attrs['payment_status'])) {
                                    return 'Payment Changed';
                                }
                                return 'Order Updated';
                            }
                            return $model . ' Updated';
                        })(),
                        default => class_basename($record->loggable_type) . ' ' . ucfirst($state),
                    })
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'created' => 'success',
                        'updated' => 'info',
                        'deleted' => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),
                TextColumn::make('from_status')
                    ->label('From')
                    ->html()
                    ->state(function ($record) {
                        $properties = $record->properties;
                        $old = $properties['old'] ?? [];

                        $renderBadge = function ($value) {
                            $style = match (strtolower($value ?? '')) {
                                'pending'    => 'background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;',
                                'processing' => 'background:#fffbeb;color:#b45309;border:1px solid #fde68a;',
                                'shipped'    => 'background:#f0f9ff;color:#0369a1;border:1px solid #bae6fd;',
                                'delivered'  => 'background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;',
                                'cancelled'  => 'background:#fff1f2;color:#be123c;border:1px solid #fecdd3;',
                                'paid'       => 'background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;',
                                'failed'     => 'background:#fff1f2;color:#be123c;border:1px solid #fecdd3;',
                                'refunded'   => 'background:#f0f9ff;color:#0369a1;border:1px solid #bae6fd;',
                                default      => 'background:#f9fafb;color:#374151;border:1px solid #e5e7eb;',
                            };
                            return '<span style="display:inline-flex;align-items:center;padding:2px 8px;font-size:11px;font-weight:600;border-radius:9999px;' . $style . '">' . e(ucfirst($value)) . '</span>';
                        };

                        $badges = [];
                        if (isset($old['status'])) {
                            $badges[] = $renderBadge($old['status']);
                        }
                        if (isset($old['payment_status'])) {
                            $badges[] = $renderBadge($old['payment_status']);
                        }

                        if (!empty($badges)) {
                            return '<div style="display:flex;flex-direction:column;gap:5px;align-items:flex-start;">' . implode('', $badges) . '</div>';
                        }

                        if (isset($old['price'])) {
                            return '<span style="font-size:13px;font-weight:500;">৳' . number_format($old['price'], 2) . '</span>';
                        }

                        return '<span style="color:#9ca3af;">—</span>';
                    }),
                TextColumn::make('to_status')
                    ->label('To')
                    ->html()
                    ->state(function ($record) {
                        $properties = $record->properties;
                        $new = $properties['attributes'] ?? [];

                        $renderBadge = function ($value) {
                            $style = match (strtolower($value ?? '')) {
                                'pending'    => 'background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;',
                                'processing' => 'background:#fffbeb;color:#b45309;border:1px solid #fde68a;',
                                'shipped'    => 'background:#f0f9ff;color:#0369a1;border:1px solid #bae6fd;',
                                'delivered'  => 'background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;',
                                'cancelled'  => 'background:#fff1f2;color:#be123c;border:1px solid #fecdd3;',
                                'paid'       => 'background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;',
                                'failed'     => 'background:#fff1f2;color:#be123c;border:1px solid #fecdd3;',
                                'refunded'   => 'background:#f0f9ff;color:#0369a1;border:1px solid #bae6fd;',
                                default      => 'background:#f9fafb;color:#374151;border:1px solid #e5e7eb;',
                            };
                            return '<span style="display:inline-flex;align-items:center;padding:2px 8px;font-size:11px;font-weight:600;border-radius:9999px;' . $style . '">' . e(ucfirst($value)) . '</span>';
                        };

                        $badges = [];
                        if (isset($new['status'])) {
                            $badges[] = $renderBadge($new['status']);
                        }
                        if (isset($new['payment_status'])) {
                            $badges[] = $renderBadge($new['payment_status']);
                        }

                        if (!empty($badges)) {
                            return '<div style="display:flex;flex-direction:column;gap:5px;align-items:flex-start;">' . implode('', $badges) . '</div>';
                        }

                        if (isset($new['price'])) {
                            return '<span style="font-size:13px;font-weight:500;">৳' . number_format($new['price'], 2) . '</span>';
                        }

                        return '<span style="color:#9ca3af;">—</span>';
                    }),
                TextColumn::make('description')
                    ->label('Activity Details')
                    ->html()
                    ->wrap()
                    ->formatStateUsing(function ($record) {
                        $html = '<div style="display:flex;flex-direction:column;gap:4px;padding:2px 0;">';

                        // Shortened description for updates
                        $desc = $record->description ?? '';
                        if ($record->action === 'updated' && str_contains($desc, 'updated:')) {
                            $desc = trim(explode('updated:', $desc)[0]) . ' updated';
                        }
                        $html .= '<div style="font-size:13px;font-weight:500;color:#111827;">' . e($desc) . '</div>';

                        // Inline diffs for updated records
                        $properties = $record->properties ?? [];
                        if ($record->action === 'updated' && isset($properties['attributes'], $properties['old'])) {
                            $diffs = [];
                            foreach ($properties['attributes'] as $field => $newVal) {
                                $oldVal = $properties['old'][$field] ?? null;
                                if ($oldVal === $newVal || $field === 'updated_at') continue;
                                if ($field === 'description' && class_basename($record->loggable_type) === 'Product') continue;

                                $fmt = function ($v) {
                                    if (is_null($v)) return 'null';
                                    if (is_bool($v)) return $v ? 'true' : 'false';
                                    $s = (string) $v;
                                    if (str_starts_with($s, '<p>') && str_ends_with($s, '</p>')) {
                                        $s = substr($s, 3, -4);
                                    }
                                    $s = trim($s);
                                    if (mb_strlen($s) > 80) {
                                        $s = mb_substr($s, 0, 80) . '...';
                                    }
                                    return e($s);
                                };

                                $pill  = '<span style="display:inline-flex;flex-wrap:wrap;align-items:center;gap:4px;';
                                $pill .= 'font-size:11px;background:#f8fafc;border:1px solid #e2e8f0;';
                                $pill .= 'border-radius:4px;padding:2px 6px;max-width:100%;word-break:break-all;">';
                                $pill .= '<span style="font-family:monospace;color:#64748b;white-space:nowrap;">' . e($field) . ':</span>';
                                $pill .= '<span style="font-family:monospace;color:#ef4444;text-decoration:line-through;word-break:break-all;">' . $fmt($oldVal) . '</span>';
                                $pill .= '<span style="color:#94a3b8;font-size:9px;">➔</span>';
                                $pill .= '<span style="font-family:monospace;color:#16a34a;font-weight:600;word-break:break-all;">' . $fmt($newVal) . '</span>';
                                $pill .= '</span>';
                                $diffs[] = $pill;
                            }

                            if (!empty($diffs)) {
                                $html .= '<div style="display:flex;flex-wrap:wrap;gap:4px;margin-top:3px;">' . implode('', $diffs) . '</div>';
                            }
                        }

                        $html .= '</div>';
                        return $html;
                    })
                    ->searchable(),
                TextColumn::make('user.name')
                    ->label('By')
                    ->default('System')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('ip_address')
                    ->label('IP Address')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('user_agent')
                    ->label('User Agent')
                    ->searchable()
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('created_at', 'desc')
            ->actions([
                ViewAction::make()
                    ->modalWidth('xl')
                    ->form([
                        Section::make('Event Metadata')
                            ->schema([
                                Placeholder::make('_meta_row')
                                    ->hiddenLabel()
                                    ->columnSpanFull()
                                    ->view('filament.components.activity-log-modal'),
                            ]),

                        Section::make('Activity Details')
                            ->schema([
                                Placeholder::make('properties_viewer')
                                    ->hiddenLabel()
                                    ->view('filament.components.activity-log-properties')
                                    ->columnSpanFull(),
                            ])
                            ->collapsible(),
                    ])
            ])
            ->bulkActions([]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListActivityLogs::route('/'),
        ];
    }
}
