<?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)
                    // )
                    
                    ->options(
                        Penduduk::where('is_ignore', '=', false)
                            ->where('dusun_id', Auth::user()->dusun_id)
                            ->get()
                            ->mapWithKeys(fn ($item) => [
                                $item->id => "{$item->nama} - NIK : " . ($item->nik ?? 'N/A')
                            ])
                    )
                    ->label('Penduduk')
                    ->required(),
                Forms\Components\DatePicker::make('tanggal_pindah')
                    ->required(),
                Forms\Components\TextInput::make('alamat_sebelumnya')
                    ->placeholder('Masukan alamat sebelumnya')
                    ->required()
                    ->maxLength(255),
                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('penduduk.dusun.nama')
                    ->label('Dusun Awal')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tanggal_pindah')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('alamat_sebelumnya')
                    ->searchable(),
                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 getEloquentQuery(): Builder
    {       
        $user = Auth::user();

        $query = parent::getEloquentQuery()
            ->with('penduduk');

        if ($user->role === 'admin_dusun') {
            $query->whereHas('penduduk', function ($q) use ($user) {
                $q->where('dusun_id', $user->dusun_id);
            });
        }

        return $query;
    }

    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'),
        ];
    }
}
