<?php

namespace App\Filament\Resources\Manage\Contacts;

use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Resources\Manage\Contacts\Pages\ManageContacts;
use App\Mail\ContactReplyMail;
use App\Models\Contact;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Textarea;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
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\Table;
use Illuminate\Support\Facades\Mail;
use UnitEnum;

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

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

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

    protected static ?string $navigationLabel = 'Kontak';

    protected static ?string $recordTitleAttribute = 'subject';

    protected static ?string $modelLabel = 'Kontak';

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

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                // Form usually not needed as we use View/Reply
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Section::make('Informasi Pengirim')
                    ->schema([
                        Grid::make(4)
                            ->schema([
                                TextEntry::make('name')
                                    ->label('Nama'),

                                TextEntry::make('email')
                                    ->label('Email'),

                                TextEntry::make('subject')
                                    ->label('Subyek'),

                                TextEntry::make('created_at')
                                    ->label('Diterima pada')
                                    ->date('l, d F Y H:i'),
                            ]),
                    ])
                    ->columnSpanFull(),

                Section::make('Pesan')
                    ->schema([
                        TextEntry::make('message')
                            ->label('Isi Pesan')
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),

                Section::make('Balasan')
                    ->schema([
                        TextEntry::make('repliedBy.name')
                            ->label('Dibalas Oleh')
                            ->placeholder('Belum dibalas'),

                        TextEntry::make('replied_at')
                            ->label('Dibalas pada')
                            ->date('l, d F Y H:i')
                            ->placeholder('Belum dibalas'),

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

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                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 ($record) => $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([
                //
            ])
            ->recordActions([
                ViewAction::make()
                    ->label('Lihat'),

                Action::make('reply')
                    ->label('Balas')
                    ->icon(Heroicon::ChatBubbleLeftRight)
                    ->color('success')
                    ->modalHeading('Balas Pesan Kontak')
                    ->modalDescription('Pesan balasan tidak bisa diubah setelah dikirim.')
                    ->schema([
                        Textarea::make('reply_message')
                            ->label('Pesan Balasan')
                            ->placeholder(fn ($record) => "Halo {$record->name}, ...")
                            ->required()
                            ->rows(5),
                    ])
                    ->action(function (Contact $record, array $data) {
                        Mail::to($record->email)->send(new ContactReplyMail($record, $data['reply_message']));

                        $record->update([
                            'reply_message' => $data['reply_message'],
                            'replied_at' => now(),
                            'replied_by' => auth()->id(),
                        ]);

                        Notification::make()
                            ->title('Balasan terkirim')
                            ->success()
                            ->send();
                    })
                    ->visible(fn ($record) => $record->replied_at === null),

                DeleteAction::make()
                    ->label('Hapus'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Kontak'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::Envelope)
            ->emptyStateDescription('Belum ada kontak atau pesan masuk.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false)
            ->reorderable('sort_order');
    }

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