<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Response;

class EditUser extends EditRecord
{
    protected static string $resource = UserResource::class;

    protected function getHeaderActions(): array
    {
        return [
            DeleteAction::make(),
            Action::make('mark_email_verified')
                ->label('Mark Email as Verified')
                ->icon(Heroicon::OutlinedEnvelope)
                ->action(function (User $user) {
                    if (! $user->hasVerifiedEmail()) {
                        $user->markEmailAsVerified();
                        Notification::make('email_verified_successfully')
                            ->title('Email Verified Successfully')
                            ->icon(Heroicon::OutlinedEnvelope)
                            ->success()
                            ->send();
                    } else {
                        Notification::make('email_already_verified')
                            ->title('Email Already Verified')
                            ->icon(Heroicon::OutlinedEnvelope)
                            ->warning()
                            ->send();
                    }
                }),
            Action::make('download_report')
                ->label('Download User Report')
                ->icon('heroicon-o-user')
                ->action(function (User $record) {
                    $userData = [
                        'Name' => $record->name,
                        'Email' => $record->email,
                        'Stripe ID' => $record->stripe_id ?? 'N/A',
                        'Payment Method Type' => $record->pm_type ?? 'N/A',
                        'Card Last 4' => $record->pm_last_four ?? 'N/A',
                        'Trial Ends At' => $record->trial_ends_at ? $record->trial_ends_at->toDateTimeString() : 'N/A',
                        'User Level' => match ($record->level) {
                            0 => 'Normal User',
                            1 => 'Banned',
                            9 => 'Super Admin',
                            default => 'Unknown',
                        },
                        'Email Verified At' => $record->email_verified_at ? $record->email_verified_at->toDateTimeString() : 'Not Verified',
                    ];

                    $csv = fopen('php://temp', 'r+');
                    // User Details Header
                    fputcsv($csv, ['User Details']);
                    fputcsv($csv, array_keys($userData));
                    fputcsv($csv, array_values($userData));
                    fputcsv($csv, []);

                    // Usage Logs Header
                    fputcsv($csv, ['Usage Logs']);
                    fputcsv($csv, ['IP Address', 'Emails Created Count', 'Emails Received Count', 'Emails Created History', 'Emails Received History', 'Created At']);
                    foreach ($record->usageLogs as $log) {
                        fputcsv($csv, [
                            $log->ip_address,
                            $log->emails_created_count,
                            $log->emails_received_count,
                            is_array($log->emails_created_history) ? implode('; ', $log->emails_created_history) : 'None',
                            is_array($log->emails_received_history) ? implode('; ', $log->emails_received_history) : 'None',
                            $log->created_at->toDateTimeString(),
                        ]);
                    }
                    fputcsv($csv, []);

                    // General Logs Header
                    fputcsv($csv, ['General Logs']);
                    fputcsv($csv, ['IP Address', 'Email', 'Created At']);
                    foreach ($record->logs as $log) {
                        fputcsv($csv, [
                            $log->ip,
                            $log->email,
                            $log->created_at->toDateTimeString(),
                        ]);
                    }

                    rewind($csv);
                    $csvContent = stream_get_contents($csv);
                    fclose($csv);

                    return Response::streamDownload(
                        function () use ($csvContent): void {
                            echo $csvContent;
                        },
                        "user_{$record->id}_report_".now()->format('Ymd_His').'.csv',
                        ['Content-Type' => 'text/csv']
                    );
                })
                ->color('primary'),
        ];
    }
}
