<?php

namespace App\Filament\App\Resources;

use App\Filament\App\Resources\TlRapatResource\Pages;
use App\Filament\App\Resources\TlRapatResource\RelationManagers;
use App\Models\AgendaRapat;
use App\Models\TlRapat;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Auth;

class TlRapatResource extends Resource
{
    protected static ?string $model = TlRapat::class;
    protected static ?int $navigationSort = -2;
    protected static ?string $navigationIcon = 'heroicon-o-document-duplicate';
    protected static ?string $navigationLabel = 'Tindak Lanjut Rapat';
    protected static ?string $pluralModelLabel = 'Tindak Lanjut Rapat';

    protected static ?string $navigationGroup = 'hidden-nav';

    public static function form(Form $form): Form
    {
        $tlRapat = $form->getRecord(); // Ini instance HasilRapat
        $agendaRapat = AgendaRapat::find($tlRapat->agenda_rapat_id); // Ambil agenda rapat berdasarkan id
        $user = User::find(Auth::id());
        $isRecordUser = $tlRapat->user_id == $user->id;
        $isRecordUser = $isRecordUser ? $isRecordUser : false;

        return $form
            ->schema([
                Forms\Components\Section::make("Agenda Rapat")
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('judul')
                            ->formatStateUsing(fn() => $agendaRapat->judul)
                            ->label('Judul Rapat')
                            ->disabled(),
                        Forms\Components\TextInput::make('pelaksanaan')
                            ->formatStateUsing(fn() => $agendaRapat->pelaksanaan)
                            ->disabled(),
                        Forms\Components\Textarea::make('keterangan')
                            ->formatStateUsing(fn() => $agendaRapat->keterangan)
                            ->autosize()
                            ->columnSpanFull()
                            ->disabled(),
                        Forms\Components\TextInput::make('tanggal')
                            ->formatStateUsing(fn() => $agendaRapat->tanggal)
                            ->disabled(),
                        Forms\Components\TextInput::make('mulai')
                            ->label('Waktu Mulai')
                            ->formatStateUsing(fn() => $agendaRapat->mulai)
                            ->disabled(),
                        Forms\Components\TextInput::make('selesai')
                            ->label('Waktu Selesai')
                            ->formatStateUsing(fn() => $agendaRapat->selesai)
                            ->disabled(),
                        Forms\Components\TextInput::make('ruangan_id')
                            ->label('Ruangan')
                            ->formatStateUsing(function () use ($agendaRapat) {
                                return $agendaRapat->ruangan->name;
                            })
                            ->disabled()
                    ]),
                Forms\Components\Section::make('Hasil Rapat')
                    ->columns(2)
                    ->relationship('HasilRapat')
                    ->schema([
                        Forms\Components\TextInput::make('risalah_rapat')
                            ->label('Risalah Rapat')
                            ->placeholder('-')
                            ->disabled(),
                        Forms\Components\TextInput::make('deskripsi')
                            ->label('Deskripsi')
                            ->placeholder('-')
                            ->disabled(),
                        Forms\Components\Repeater::make('dokumen')
                            ->label('Dokumen Hasil Rapat')
                            ->relationship('dokumen')
                            ->addable(false)
                            ->deletable(false)
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->label('Nama Dokumen')
                                    ->placeholder('-')
                                    ->disabled(),
                                Forms\Components\TextInput::make('deskripsi')
                                    ->label('Deskripsi')
                                    ->placeholder('-')
                                    ->disabled(),
                                Forms\Components\FileUpload::make('dokumen')
                                    ->label('Dokumen')
                                    ->openable()
                                    ->downloadable()
                                    ->deletable(false)
                                    ->disabled(),
                            ]),
                        Forms\Components\Repeater::make('foto')
                            ->addable(false)
                            ->relationship('foto')
                            ->deletable(false)
                            ->schema([
                                Forms\Components\FileUpload::make('foto')
                                    ->image()
                                    ->disabled()
                                    ->openable()
                                    ->downloadable()
                                    ->deletable(false)
                                    ->imagePreviewHeight(250)
                                    ->previewable()
                                    ->label(''),
                            ]),
                    ]),
                Forms\Components\Section::make("Tindak Lanjut Rapat")
                    ->columns(2)
                    ->schema([

                        Forms\Components\Hidden::make('user_id'),
                        Forms\Components\Hidden::make('hasil_rapat_id'),
                        Forms\Components\Hidden::make('agenda_rapat_id'),
                        Forms\Components\Select::make('status')
                            ->options([
                                'Belum Diisi' => 'Belum Diisi',
                                'Pengajuan' => 'Pengajuan',
                                'Ditolak' => 'Ditolak',
                                'Selesai' => 'Selesai',
                            ])
                            ->required()
                            ->default('Belum Diisi')
                            ->disabled(function () use ($user) {
                                if ($user->can('persetujuan_agenda::rapat')) {
                                    return false;
                                }
                                return true;
                            }),

                        Forms\Components\DatePicker::make('target')
                            ->displayFormat('d/m/Y')
                            ->native(false)
                            ->disabled(true)
                            ->required(),
                        Forms\Components\Textarea::make('alasan_ditolak')
                            ->label('Alasan Ditolak')
                            ->disabled(function () use ($user) {
                                if ($user->can('persetujuan_agenda::rapat')) {
                                    return false;
                                }
                                return true;
                            })
                            ->hidden(function ($get) use ($user) {
                                if ($user->can('persetujuan_agenda::rapat')) {
                                    return false;
                                }
                                if ($get('status') == 'Ditolak') {
                                    return false;
                                }
                                return true;
                            })
                            ->columnSpanFull(),
                        Forms\Components\Textarea::make('tanggapan')
                            ->label('Deskripsi')
                            ->disabled()
                            ->columnSpanFull(),
                    ]),
                Forms\Components\Repeater::make('dokumen')
                    ->relationship('dokumen')
                    ->label('Dokumen Tindak Lanjut')
                    ->addActionLabel('Tambah Dokumen')
                    ->itemLabel(fn(array $state): ?string => $state['name'] ?? null)
                    ->collapsible()
                    ->columnSpanFull()
                    ->columns(2)
                    ->addable($isRecordUser)
                    ->deletable($isRecordUser)
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('Nama Dokumen')
                            ->required()
                            ->disabled(!$isRecordUser)
                            ->default('Dokumen'),
                        Forms\Components\FileUpload::make('file')
                            ->label('Dokumen')
                            ->maxSize(1024 * 1024 * 5)
                            ->disk('public')
                            ->directory('dokumen-rapat')
                            ->disabled(!$isRecordUser)
                            ->required()
                            ->downloadable(),
                        Forms\Components\Textarea::make('deskripsi')
                            ->label('Deskripsi')
                            ->disabled(!$isRecordUser)
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->recordUrl(null)
            ->modifyQueryUsing(function (Builder $query) {
                $query->where('user_id', Auth::id())
                    ->whereHas('AgendaRapat', function (Builder $query) {
                        $query->where('tindak_lanjut', '!=', 'Belum');
                    });
            })
            ->columns([
                Tables\Columns\TextColumn::make('AgendaRapat.judul')
                    ->searchable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'Belum Diisi' => 'gray',
                        'Pengajuan' => 'warning',
                        'Ditolak' => 'danger',
                        'Selesai' => 'success',
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('target')
                    ->date()
                    ->sortable(),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make()
                    ->button()
                    ->hidden(function ($record) {
                        if ($record->status != 'Selesai') {
                            return false;
                        }
                        return true;
                    }),
                Tables\Actions\ViewAction::make()
                    ->stickyModalHeader()
                    ->stickyModalFooter()
                    ->modalHeading('Tindak Lanjut Agenda Rapat')
                    ->button()
                    ->hidden(function ($record) {
                        if ($record->status == 'Selesai') {
                            return false;
                        }
                        return true;
                    }),
            ])
            ->bulkActions([
                // Tables\Actions\BulkActionGroup::make([
                //     Tables\Actions\DeleteBulkAction::make(),
                // ]),
            ]);
    }

    protected static ?string $navigationBadgeTooltip = 'Tindak lanjut rapat yang harus diisi';

    public static function getNavigationBadge(): ?string
    {
        return static::$model::where('user_id', Auth::id())
            ->whereIn('status', ['Belum Diisi', 'Ditolak'])
            ->whereHas('AgendaRapat', function (Builder $query) {
                $query->where('tindak_lanjut', '!=', 'Belum');
            })->count();
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTlRapats::route('/'),
            'create' => Pages\CreateTlRapat::route('/create'),
            'edit' => Pages\EditTlRapat::route('/{record}/edit'),
        ];
    }
}
