<?php

namespace App\Filament\App\Resources\AgendaRapatResource\RelationManagers;

use App\Models\AgendaRapat;
use App\Models\User;
use App\Models\Departemen;
use App\Models\HasilRapat;
use App\Models\Log;
use App\Models\TlRapat;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Auth;

class TlRapatRelationManager extends RelationManager
{
    protected static string $relationship = 'TlRapat';
    protected static ?string $title = 'Tindak Lanjut Rapat';

    public function form(Form $form): Form
    {
        $tlRapat = $form->getRecord(); // Ini instance HasilRapat

        $user = User::find(Auth::id());
        $isRecordUser = $tlRapat->user_id == $user->id;
        $isRecordUser = $isRecordUser ? $isRecordUser : false;

        return $form
            ->schema([
                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 function table(Table $table): Table
    {
        $user = User::find(Auth::id());
        $agendaRapat = $this->ownerRecord;
        $statusMenunggu = $agendaRapat->tindak_lanjut == 'Menunggu';
        $statusReview = $agendaRapat->tindak_lanjut == 'Review';
        $viewHeaderButton = $user->can('persetujuan_agenda::rapat') && ($statusMenunggu || $statusReview);
        $hasilRapat = HasilRapat::where('agenda_rapat_id', $agendaRapat->id)->first();
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('PIC Rapat')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.departemen.name')
                    ->label('Departemen')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'Belum Diisi' => 'gray',
                        'Pengajuan' => 'warning',
                        'Ditolak' => 'danger',
                        'Selesai' => 'success',
                    })
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\Action::make('Edit')
                    ->button()
                    ->color('warning')
                    ->icon('heroicon-c-pencil-square')
                    ->visible(function () use ($user) {
                        return $user->can('persetujuan_agenda::rapat');
                    })
                    ->action(function () use ($hasilRapat) {
                        //dd($hasilRapat);
                        return redirect()->route('filament.app.resources.hasil-rapats.edit', [
                            'record' => $hasilRapat->id,
                        ]);
                    }),
                Tables\Actions\Action::make('Setujui Semua')
                    ->button()
                    ->color('success')
                    ->icon('heroicon-c-check')
                    ->requiresConfirmation()
                    ->visible($viewHeaderButton)
                    ->action(function () use ($agendaRapat) {

                        TlRapat::where('hasil_rapat_id', $agendaRapat->hasil_rapat_id)
                            ->update(['status' => 'Selesai']);
                        $agendaRapat->update(['tindak_lanjut' => 'Selesai']);
                        $record = $this->ownerRecord;
                        Log::create([
                            'agenda_rapat_id' => $record->id,
                            'user_id' => Auth::id(),
                            'log' => "Tindak lanjut rapat disetujui semua",
                        ]);
                        Notification::make()
                            ->title('Tindak Lanjut Rapat Disetujui Semua')
                            ->success()
                            ->send();
                    }),
                Tables\Actions\Action::make('Tolak Semua')
                    ->button()
                    ->color('danger')
                    ->icon('heroicon-c-x-mark')
                    ->requiresConfirmation()
                    ->visible($viewHeaderButton)
                    ->form([
                        Forms\Components\Textarea::make('alasan_ditolak')
                            ->label('Alasan Ditolak')
                            ->required()
                            ->placeholder('Masukkan alasan penolakan tindak lanjut rapat')
                            ->columnSpanFull(),
                    ])
                    ->action(function (array $data) use ($agendaRapat) {

                        TlRapat::where('hasil_rapat_id', $agendaRapat->hasil_rapat_id)
                            ->update([
                                'status' => 'Ditolak',
                                'alasan_ditolak' => $data['alasan_ditolak'],
                            ]);
                        $record = $this->ownerRecord;
                        Log::create([
                            'agenda_rapat_id' => $record->id,
                            'user_id' => Auth::id(),
                            'log' => "Tindak lanjut rapat ditolak semua",
                        ]);
                        Notification::make()
                            ->title('Tindak Lanjut Rapat Ditolak Semua')
                            ->success()
                            ->send();
                    }),
            ])
            ->actions(self::ActionRecordPIC($user))
            ->bulkActions([]);
    }
    protected function ActionRecordPIC($user): array
    {
        return [
            self::tombolSetujui($user),
            self::tombolTolak($user),
            Tables\Actions\ViewAction::make()
                ->button(),
        ];
    }
    protected function tombolTolak($user)
    {
        return Tables\Actions\Action::make('Tolak')
            ->button()
            ->color('danger')
            ->icon('heroicon-c-x-mark')
            ->requiresConfirmation()
            ->hidden(function ($record) use ($user) {
                if ($user->can('persetujuan_agenda::rapat') && $record->status == 'Pengajuan') {
                    return false;
                }
                return true;
            })
            ->form([
                Forms\Components\Textarea::make('alasan_ditolak')
                    ->label('Alasan Ditolak')
                    ->required()
                    ->placeholder('Masukkan alasan penolakan tindak lanjut rapat')
                    ->columnSpanFull(),
            ])
            ->action(function (TlRapat $record) use ($user) {
                $record->update([
                    'status' => 'Ditolak',
                ]);
                $record = $this->ownerRecord;
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Tindak lanjut dari " . $user->name . " ditolak",
                ]);
                Notification::make()
                    ->title('Tindak Lanjut Rapat Ditolak')
                    ->danger()
                    ->send();
            });
    }
    protected function tombolSetujui($user)
    {
        return Tables\Actions\Action::make('Setujui')
            ->button()
            ->color('success')
            ->icon('heroicon-c-check')
            ->requiresConfirmation()
            ->hidden(function (TlRapat $record) use ($user) {
                if ($user->can('persetujuan_agenda::rapat') && $record->status == 'Pengajuan') {
                    return false;
                }
                return true;
            })

            ->action(function (TlRapat $record) use ($user) {
                $record->update([
                    'status' => 'Selesai',
                ]);

                $userId = $record->user_id;
                // Ambil semua data dengan hasil_rapat_id ==  $data['hasil_rapat_id']
                $list = TlRapat::where('hasil_rapat_id',  $record->hasil_rapat_id)->get();

                // Cek apakah semua data memiliki status == "Pengajuan"
                $semuaPengajuan = $list->every(function ($item) use ($userId) {
                    if ($userId == $item->user_id) {
                        return true;
                    }
                    return $item->status === 'Pengajuan';
                });
                if ($semuaPengajuan) {
                    AgendaRapat::where('id', $record->agenda_rapat_id)->update(['tindak_lanjut' => 'Selesai']);
                }
                $record = $this->ownerRecord;
                Log::create([
                    'agenda_rapat_id' => $record->id,
                    'user_id' => Auth::id(),
                    'log' => "Tindak lanjut dari " . $user->name . " disetujui",
                ]);
                // Kalau benar, kasih alert berhasil
                Notification::make()
                    ->title('Tindak Lanjut Rapat Disetujui')
                    ->success()
                    ->send();
            });
    }
}
