<?php

declare(strict_types=1);

namespace App\Filament\Resources\SupportTickets\Pages;

use App\Filament\Resources\SupportTickets\SupportTicketResource;
use App\Models\SupportTicket;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\Auth;

class ViewSupportTicket extends ViewRecord
{
    protected static string $resource = SupportTicketResource::class;

    public function mount(int|string $record): void
    {
        parent::mount($record);

        $this->getRecord()->load('user');

        $ticket = $this->getRecord();

        if (in_array($ticket->status, [SupportTicket::STATUS_UNREAD, SupportTicket::STATUS_OPEN], true)) {
            $ticket->update([
                'status' => SupportTicket::STATUS_READ,
                'updated_by' => Auth::id(),
            ]);
        }
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('close')
                ->label('بستن تیکت')
                ->icon('heroicon-o-lock-closed')
                ->color('danger')
                ->visible(fn (): bool => $this->getRecord()->status !== SupportTicket::STATUS_CLOSED)
                ->schema([
                    Textarea::make('close_reason')->label('دلیل بستن')->required()->rows(3),
                ])
                ->action(function (array $data): void {
                    $this->getRecord()->update([
                        'status' => SupportTicket::STATUS_CLOSED,
                        'closed_at' => now(),
                        'close_reason' => $data['close_reason'],
                        'closed_by' => Auth::id(),
                        'updated_by' => Auth::id(),
                    ]);

                    Notification::make()->title('تیکت بسته شد.')->success()->send();
                }),
            Action::make('reopen')
                ->label('بازگشایی تیکت')
                ->icon('heroicon-o-lock-open')
                ->color('warning')
                ->visible(fn (): bool => $this->getRecord()->status === SupportTicket::STATUS_CLOSED)
                ->requiresConfirmation()
                ->action(function (): void {
                    $this->getRecord()->update([
                        'status' => SupportTicket::STATUS_OPEN,
                        'closed_at' => null,
                        'close_reason' => null,
                        'closed_by' => null,
                        'updated_by' => Auth::id(),
                    ]);

                    Notification::make()->title('تیکت بازگشایی شد.')->success()->send();
                }),
        ];
    }

    public function infolist(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('اطلاعات کاربر')
                    ->schema([
                        TextEntry::make('user.getFilamentName')
                            ->label('نام کاربر')
                            ->getStateUsing(fn (SupportTicket $record) => $record->user?->getFilamentName())
                            ->placeholder('-'),
                        TextEntry::make('user.national_code')->label('شماره ملی')->placeholder('-'),
                        TextEntry::make('user.cellphone')->label('شماره همراه')->placeholder('-'),
                        TextEntry::make('user.email')->label('ایمیل')->placeholder('-'),
                    ])
                    ->columns(2),
                Section::make('جزئیات تیکت')
                    ->schema([
                        TextEntry::make('code')->label('کد'),
                        TextEntry::make('title')->label('عنوان'),
                        TextEntry::make('category')
                            ->label('دسته‌بندی')
                            ->formatStateUsing(fn (?string $state) => SupportTicket::categoryOptions()[(string) $state] ?? $state ?? '-')
                            ->badge(),
                        TextEntry::make('status')
                            ->label('وضعیت')
                            ->formatStateUsing(fn (?string $state) => SupportTicket::statusOptions()[(string) $state] ?? $state ?? '-')
                            ->badge()
                            ->color(fn (?string $state) => match ($state) {
                                SupportTicket::STATUS_OPEN => 'warning',
                                SupportTicket::STATUS_CLOSED => 'gray',
                                SupportTicket::STATUS_READ => 'success',
                                SupportTicket::STATUS_UNREAD => 'danger',
                                default => 'gray',
                            }),
                        TextEntry::make('body')->label('متن')->columnSpanFull(),
                        TextEntry::make('attachments')
                            ->label('پیوست‌ها')
                            ->formatStateUsing(function (?array $state): string {
                                if (empty($state)) {
                                    return '-';
                                }

                                return collect($state)
                                    ->map(fn (string $file): string => str_starts_with($file, 'http') ? $file : url($file))
                                    ->implode("\n");
                            })
                            ->placeholder('-')
                            ->columnSpanFull(),
                        TextEntry::make('close_reason')
                            ->label('دلیل بستن')
                            ->visible(fn (SupportTicket $record) => $record->status === SupportTicket::STATUS_CLOSED)
                            ->placeholder('-')
                            ->columnSpanFull(),
                        TextEntry::make('closed_at')
                            ->label('تاریخ بسته شدن')
                            ->jalaliDateTime('Y/m/d H:i')
                            ->visible(fn (SupportTicket $record) => $record->status === SupportTicket::STATUS_CLOSED)
                            ->placeholder('-'),
                        TextEntry::make('created_at')->label('تاریخ ثبت')->jalaliDateTime('Y/m/d H:i'),
                    ])
                    ->columns(2),
            ]);
    }
}
