<?php

namespace App\Filament\Resources;

use App\Filament\Resources\KematianResource\Pages;
use App\Filament\Resources\KematianResource\RelationManagers;
use App\Models\Dusun;
use App\Models\Kematian;
use App\Models\Penduduk;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
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 KematianResource extends Resource
{
    protected static ?string $model = Kematian::class;

    protected static ?string $navigationIcon = 'heroicon-o-user-group';
    protected static ?string $activeNavigationIcon = 'heroicon-s-user-group';
    protected static ?string $navigationGroup = 'Sirkulasi Penduduk';
    protected static ?string $navigationLabel = 'Data Kematian';
    protected static ?int $navigationSort = 2;

    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, ?Kematian $record) => $query
                    //         ->where('status_penduduk', '!=', 'meninggal')
                    //         ->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')
                            ])
                    )
                    ->required(),
                Forms\Components\DatePicker::make('tanggal_kematian')
                    ->required(),
                Forms\Components\TextInput::make('penyebab')
                    ->required()
                    ->placeholder('Masukan penyebab kematian')
                    ->maxLength(255),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('penduduk.nama')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tanggal_kematian')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('penyebab')
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //

                // Filter Dusun
                Tables\Filters\SelectFilter::make('dusun_id')
                    ->label('Dusun')
                    ->options(
                        Dusun::pluck('nama', 'id')->toArray() // Ambil nama dusun dan ID-nya
                    )
                    ->query(function (Builder $query, array $data): Builder {
                        if (isset($data['value']) && $data['value']) {
                            // Join dengan tabel penduduk untuk filter dusun_id
                            return $query->whereHas('penduduk', function (Builder $pendudukQuery) use ($data) {
                                $pendudukQuery->where('dusun_id', $data['value']);
                            });
                        }
                        return $query;
                    }),
            ])
            ->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')
                    ->visible(fn (): bool => Auth::user()->role === 'admin_desa')
                    ->color('danger') // Memberikan warna merah
                    ->icon('heroicon-o-trash') // Memberikan ikon tempat sampah
                    ->requiresConfirmation() // Menambahkan konfirmasi sebelum menghapus
                    ->action(function (Kematian $record) { // Menggunakan action() dengan $record
                        DB::transaction(function () use ($record) {
                            Log::info('Memulai custom delete action (via Action::make) 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']);

                            } 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\ListKematians::route('/'),
            'create' => Pages\CreateKematian::route('/create'),
            'edit' => Pages\EditKematian::route('/{record}/edit'),
        ];
    }
}
