<?php

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

use App\Enums\Channel;
use App\Enums\RoleEnum;
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 Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
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 MediaMonitoringsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('code')
                    ->label('Kode')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('media_name')
                    ->label('Nama media')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('title')
                    ->label('Judul')
                    ->limit(30)
                    ->searchable()
                    ->sortable(),

                TextColumn::make('channel')
                    ->label('Kanal')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('writter')
                    ->label('Penulis')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('link')
                    ->label('Tautan')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('news_page')
                    ->label('Halaman Berita')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('influencer')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('keyword')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('themes.name')
                    ->label('Tema')
                    ->searchable()
                    ->sortable()
                    ->wrap()
                    ->badge(),

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

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

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

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

                Filter::make('writter')
                    ->form([
                        TextInput::make('writter')
                            ->label('Penulis')
                            ->placeholder('Cari penulis...'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query->when(
                            $data['writter'],
                            fn (Builder $query, $term): Builder => $query->where('writter', 'like', "%{$term}%"),
                        );
                    }),

                Filter::make('date_filter')
                    ->schema([
                        Select::make('date_type')
                            ->label('Jenis Filter Tanggal')
                            ->options([
                                'date' => 'Tanggal Rilis',
                                '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 = 'release_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('Monitoring Media'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::ClipboardDocumentCheck)
            ->emptyStateDescription('Setelah Anda membubat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }
}
