<?php

namespace App\Filament\Resources\Monitoring\ContentRecaps\Tables;

use App\Enums\Channel;
use App\Enums\ContentType;
use App\Enums\RoleEnum;
use App\Enums\SocialMedia;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Models\ContentRecap;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Enums\FiltersLayout;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class ContentRecapsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('title')
                    ->label('Judul')
                    ->searchable()
                    ->sortable()
                    ->wrap()
                    ->description(fn (ContentRecap $contentRecap): string => $contentRecap->link),

                TextColumn::make('type')
                    ->label('Tipe')
                    ->badge()
                    ->color(fn (ContentType $state): string => $state->getColor())
                    ->searchable()
                    ->sortable(),

                TextColumn::make('channel')
                    ->label('Kanal')
                    ->badge()
                    ->color(fn (Channel $state): string => $state->getColor())
                    ->searchable()
                    ->sortable(),

                TextColumn::make('social_media')
                    ->label('Media Sosial')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('classification.name')
                    ->label('Klasifikasi')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('posting_date')
                    ->label('Tgl Posting')
                    ->searchable()
                    ->sortable()
                    ->date('l, d F Y'),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn () => auth()->user()?->hasRole(RoleEnum::DEVELOPER->value)),

                SelectFilter::make('social_media')
                    ->label('Media Sosial')
                    ->options(SocialMedia::class)
                    ->native(false),

                SelectFilter::make('classification')
                    ->label('Klasifikasi')
                    ->relationship('classification', 'name')
                    ->searchable()
                    ->preload()
                    ->native(false),

                SelectFilter::make('type')
                    ->label('Jenis Konten')
                    ->options(ContentType::class)
                    ->native(false),

                SelectFilter::make('channel')
                    ->label('Kanal')
                    ->options(Channel::class)
                    ->native(false),

                Filter::make('date_filter')
                    ->schema([
                        Select::make('date_type')
                            ->label('Jenis Filter Tanggal')
                            ->options([
                                'date' => 'Tanggal Posting',
                                'month' => 'Bulan & Tahun',
                                'year' => 'Tahun',
                                'range' => 'Rentang Tanggal',
                            ])
                            ->live()
                            ->native(false),

                        DatePicker::make('specific_date')
                            ->label('Tanggal')
                            ->placeholder('Pilih tanggal')
                            ->visible(fn (Get $get) => $get('date_type') === 'date')
                            ->native(false),

                        Select::make('month')
                            ->label('Bulan')
                            ->options([
                                1 => 'Januari',
                                2 => 'Februari',
                                3 => 'Maret',
                                4 => 'April',
                                5 => 'Mei',
                                6 => 'Juni',
                                7 => 'Juli',
                                8 => 'Agustus',
                                9 => 'September',
                                10 => 'Oktober',
                                11 => 'November',
                                12 => 'Desember',
                            ])
                            ->visible(fn (Get $get) => $get('date_type') === 'month')
                            ->native(false),

                        Select::make('year')
                            ->label('Tahun')
                            ->options(function () {
                                $years = range(date('Y'), 2020);

                                return array_combine($years, $years);
                            })
                            ->visible(fn (Get $get) => in_array($get('date_type'), ['month', 'year']))
                            ->native(false),

                        DatePicker::make('start_date')
                            ->label('Tanggal Mulai')
                            ->placeholder('Pilih tanggal mulai')
                            ->visible(fn (Get $get) => $get('date_type') === 'range')
                            ->native(false)
                            ->displayFormat('l, d F Y'),

                        DatePicker::make('end_date')
                            ->label('Tanggal Selesai')
                            ->placeholder('Pilih tanggal selesai')
                            ->visible(fn (Get $get) => $get('date_type') === 'range')
                            ->native(false)
                            ->displayFormat('l, d F Y'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $type = $data['date_type'] ?? null;
                        $column = 'posting_date';

                        if ($type === 'date' && ! empty($data['specific_date'])) {
                            return $query->whereDate($column, $data['specific_date']);
                        }
                        if ($type === 'month' && ! empty($data['month']) && ! empty($data['year'])) {
                            return $query->whereMonth($column, $data['month'])
                                ->whereYear($column, $data['year']);
                        }
                        if ($type === 'year' && ! empty($data['year'])) {
                            return $query->whereYear($column, $data['year']);
                        }
                        if ($type === 'range' && ! empty($data['start_date']) && ! empty($data['end_date'])) {
                            return $query->whereBetween($column, [$data['start_date'], $data['end_date']]);
                        }

                        return $query;
                    }),
            ], FiltersLayout::AboveContentCollapsible)
            ->filtersFormColumns(3)
            ->recordActions([
                EditAction::make(),

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Rekap Konten'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::ClipboardDocumentList)
            ->emptyStateDescription('Setelah Anda membubat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }
}
