<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PindahResource\Pages;
use App\Filament\Resources\PindahResource\RelationManagers;
use App\Models\Penduduk;
use App\Models\Pindah;
use Filament\Forms;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PindahResource extends Resource
{
    protected static ?string $model = Pindah::class;

    protected static ?string $navigationIcon = 'heroicon-o-arrow-up-on-square';
    protected static ?string $navigationGroup = 'Sirkulasi Penduduk';
    protected static ?string $navigationLabel = 'Data Pindah';
    protected static ?int $navigationSort = 4;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('penduduk_id')
                    ->relationship(
                        name: 'penduduk',
                        titleAttribute: 'nama',
                        modifyQueryUsing: fn (Builder $query, Forms\Get $get, ?Pindah $record) => $query
                            ->where('status_penduduk', '!=', 'pindah')
                            ->when(
                                $record,
                                fn (Builder $query) => $query->orWhere('id', $record->penduduk_id) 
                            )
                            ->where('is_ignore', false)
                    )
                    ->required(),
                Forms\Components\DatePicker::make('tanggal_pindah')
                    ->required(),
                Forms\Components\TextInput::make('alasan')
                    ->placeholder('Masukan alasan pindah')
                    ->required()
                    ->maxLength(255)
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('penduduk.nama')
                    ->label('Nama')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tanggal_pindah')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('alasan')
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
                 SelectFilter::make('dusun_id')
                    ->label('Dusun Asal')
                    ->relationship('penduduk.dusun', 'nama') // Filter berdasarkan dusun dari relasi penduduk
                    ->preload(),
                Filter::make('tanggal_pindah')
                    ->form([
                        DatePicker::make('tanggal_pindah_dari')
                            ->placeholder('Tanggal Dari'),
                        DatePicker::make('tanggal_pindah_sampai')
                            ->placeholder('Tanggal Sampai'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['tanggal_pindah_dari'],
                                fn (Builder $query, $date): Builder => $query->whereDate('tanggal_pindah', '>=', $date),
                            )
                            ->when(
                                $data['tanggal_pindah_sampai'],
                                fn (Builder $query, $date): Builder => $query->whereDate('tanggal_pindah', '<=', $date),
                            );
                    })
            ])
            ->actions([
                Tables\Actions\EditAction::make()->visible(fn (): bool => Auth::user()->role !== 'kepala_desa'),
                Tables\Actions\Action::make('deleteCustom') // Beri nama unik untuk action
                    ->label('Hapus')
                    ->color('danger')
                    ->visible(fn (): bool => Auth::user()->role === 'admin_desa')
                    ->icon('heroicon-o-trash') // Memberikan ikon tempat sampah
                    ->requiresConfirmation() // Menambahkan konfirmasi sebelum menghapus
                    ->action(function (Pindah $record) { // Menggunakan action() dengan $record
                        DB::transaction(function () use ($record) {
                            Log::info('Memulai custom delete action (via Action::make) untuk Pindah ID: ' . $record->id);

                            $penduduk = $record->penduduk;

                            if ($penduduk) {
                                Log::info('Penduduk terkait ditemukan: ' . $penduduk->id . ' - ' . $penduduk->nama);

                                // update status penduduk
                                $penduduk->update(['status_penduduk' => 'ada']);

                            } else {
                                Log::info('Tidak ada penduduk terkait ditemukan untuk kematian ID: ' . $record->id);
                            }

                            $record->delete();
                            Log::info('Record kematian ID: ' . $record->id . ' berhasil dihapus.');
                        });
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->visible(fn (): bool => Auth::user()->role === 'admin_desa')
                        ->action(function (Collection $records) {
                            DB::transaction(function () use ($records) {
                                foreach ($records as $record) {
                                    Log::info('Memulai custom bulk delete action untuk kematian ID: ' . $record->id);

                                    $penduduk = $record->penduduk;

                                    if ($penduduk) {
                                        Log::info('Penduduk terkait ditemukan: ' . $penduduk->id . ' - ' . $penduduk->nama);

                                        // update status penduduk
                                        $penduduk->update(['status_penduduk' => 'ada']);
                                        Log::info('Status Penduduk ID: ' . $penduduk->id . ' diupdate menjadi "ada" (bulk).');
                                    } else {
                                        Log::info('Tidak ada penduduk terkait ditemukan untuk kematian ID: ' . $record->id . ' (bulk).');
                                    }

                                    $record->delete();
                                    Log::info('Record kematian ID: ' . $record->id . ' berhasil dihapus (bulk).');
                                }
                            });
                        })
                ]),
            ]);
    }

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

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