<?php

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

use App\Enums\IssueSentiment;
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\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 IssueManagementTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('mediaMonitoring.title')
                    ->label('Judul Berita')
                    ->limit(30)
                    ->searchable()
                    ->sortable(),

                TextColumn::make('issue')
                    ->label('Isu')
                    ->badge()
                    ->searchable()
                    ->sortable(),

                TextColumn::make('response')
                    ->label('Respon')
                    ->badge()
                    ->searchable()
                    ->sortable(),

                TextColumn::make('location.name')
                    ->label('Lokus')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('subLocation.name')
                    ->label('Sub Lokus')
                    ->searchable()
                    ->sortable(),

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

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

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

                SelectFilter::make('issue')
                    ->label('Filter Isu')
                    ->options(IssueSentiment::class)
                    ->native(false),

                SelectFilter::make('response')
                    ->label('Filter Respon')
                    ->options(IssueSentiment::class)
                    ->native(false),

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

                SelectFilter::make('subLocation')
                    ->label('Sub Lokus')
                    ->relationship('subLocation', 'name')
                    ->searchable()
                    ->preload()
                    ->native(false),

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

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

                Filter::make('date_filter')
                    ->schema([
                        Select::make('date_type')
                            ->label('Jenis Filter Tanggal')
                            ->options([
                                'date' => 'Tanggal Rilis Berita',
                                '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;

                        return $query->when($type, function (Builder $query) use ($type, $data) {
                            return $query->whereHas('mediaMonitoring', function (Builder $query) use ($type, $data) {
                                $column = 'release_date';

                                if ($type === 'date' && ! empty($data['specific_date'])) {
                                    $query->whereDate($column, $data['specific_date']);
                                } elseif ($type === 'month' && ! empty($data['month']) && ! empty($data['year'])) {
                                    $query->whereMonth($column, $data['month'])
                                        ->whereYear($column, $data['year']);
                                } elseif ($type === 'year' && ! empty($data['year'])) {
                                    $query->whereYear($column, $data['year']);
                                } elseif ($type === 'range' && ! empty($data['start_date']) && ! empty($data['end_date'])) {
                                    $query->whereBetween($column, [$data['start_date'], $data['end_date']]);
                                }
                            });
                        });
                    }),
            ], FiltersLayout::AboveContentCollapsible)
            ->filtersFormColumns(3)
            ->recordActions([
                EditAction::make(),

                DeleteAction::make(),

                RestoreAction::make(),

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