<?php

namespace App\Filament\Resources\Manage\Contacts;

use App\Enums\NotifStyle;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\RowIndexColumn;
use App\Filament\Resources\Manage\Contacts\Actions\ReplyAction;
use App\Filament\Resources\Manage\Contacts\Pages\ManageContacts;
use App\Filament\Support\CheerfulNotification;
use App\Models\Contact;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\ViewAction;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use UnitEnum;

class ContactResource extends Resource
{
    protected static ?string $model = Contact::class;

    protected static ?string $modelLabel = 'Kontak';

    protected static string|UnitEnum|null $navigationGroup = 'Kelola';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelope;

    protected static ?string $navigationLabel = 'Kontak';

    protected static ?int $navigationSort = 9;

    protected static ?string $slug = 'manage/contacts';

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('replied_at', null)->count();
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Section::make(fn () => CheerfulNotification::getByKey('contact.sender_info_title'))
                    ->description(fn () => CheerfulNotification::getByKey('contact.sender_info_desc'))
                    ->icon(fn () => CheerfulNotification::getNotifStyle() === NotifStyle::CHEERFUL ? 'heroicon-o-user' : null)
                    ->schema([
                        Grid::make(4)
                            ->schema([
                                TextEntry::make('name')
                                    ->label('Nama Pengirim')
                                    ->icon('heroicon-o-user'),

                                TextEntry::make('email')
                                    ->label('Alamat Surel')
                                    ->icon('heroicon-o-envelope'),

                                TextEntry::make('subject')
                                    ->label('Subyek Pesan')
                                    ->icon('heroicon-o-tag'),

                                TextEntry::make('created_at')
                                    ->label('Diterima Pada')
                                    ->date('l, d F Y H:i')
                                    ->icon('heroicon-o-calendar'),
                            ]),
                    ])
                    ->columnSpanFull(),

                Section::make(fn () => CheerfulNotification::getByKey('contact.message_content_title'))
                    ->description(fn () => CheerfulNotification::getByKey('contact.message_content_desc'))
                    ->icon(fn () => CheerfulNotification::getNotifStyle() === NotifStyle::CHEERFUL ? 'heroicon-o-chat-bubble-left-right' : null)
                    ->schema([
                        TextEntry::make('message')
                            ->label('Konten Pesan')
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),

                Section::make(fn () => CheerfulNotification::getByKey('contact.reply_history_title'))
                    ->description(fn () => CheerfulNotification::getByKey('contact.reply_history_desc'))
                    ->icon(fn () => CheerfulNotification::getNotifStyle() === NotifStyle::CHEERFUL ? 'heroicon-o-paper-airplane' : null)
                    ->schema([
                        TextEntry::make('repliedBy.name')
                            ->label('Dibalas Oleh')
                            ->placeholder('Belum dibalas')
                            ->icon('heroicon-o-user-circle'),

                        TextEntry::make('replied_at')
                            ->label('Waktu Balasan')
                            ->date('l, d F Y H:i')
                            ->placeholder('Belum dibalas')
                            ->icon('heroicon-o-clock'),

                        TextEntry::make('reply_message')
                            ->label('Isi Balasan')
                            ->placeholder('Belum dibalas')
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull()
                    ->visible(fn (Contact $record): bool => $record->replied_at !== null),
            ])
            ->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                ...RowIndexColumn::make(),

                TextColumn::make('name')
                    ->label('Nama')
                    ->searchable(),

                TextColumn::make('email')
                    ->label('Email')
                    ->searchable(),

                TextColumn::make('subject')
                    ->label('Subyek')
                    ->limit(30),

                IconColumn::make('replied_at')
                    ->label('Dibalas')
                    ->boolean()
                    ->getStateUsing(fn (Contact $record): bool => $record->replied_at !== null),

                TextColumn::make('repliedBy.name')
                    ->label('Dibalas Oleh')
                    ->badge()
                    ->placeholder('Belum dibalas')
                    ->sortable(),

                TextColumn::make('created_at')
                    ->label('Diterima pada')
                    ->date('l, d F Y H:i')
                    ->sortable(),
            ])
            ->filters([
                TernaryFilter::make('replied_at')
                    ->label('Status Balasan')
                    ->placeholder('Semua Pesan')
                    ->trueLabel('Sudah Dibalas')
                    ->falseLabel('Belum Dibalas')
                    ->queries(
                        true: fn ($query) => $query->whereNotNull('replied_at'),
                        false: fn ($query) => $query->whereNull('replied_at'),
                    )
                    ->native(false),
            ])
            ->recordActions([
                ViewAction::make()
                    ->label('Lihat'),

                ReplyAction::make('reply'),

                DeleteAction::make()
                    ->label('Hapus'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Kontak'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::OutlinedEnvelope)
            ->emptyStateHeading(fn () => CheerfulNotification::getByKey('contact.empty_state_heading'))
            ->emptyStateDescription(fn () => CheerfulNotification::getByKey('contact.empty_state'))
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false)
            ->paginated([25, 50, 100, 'all'])
            ->deferLoading();
    }

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