<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PendudukResource\Pages;
use App\Filament\Resources\PendudukResource\RelationManagers;
use App\Models\Dusun;
use App\Models\Penduduk;
use App\Models\User;
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\Facades\Auth;

class PendudukResource extends Resource
{
    protected static ?string $model = Penduduk::class;

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

    protected static ?string $pluralModelLabel = 'Data Penduduk';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('nik')
                    ->required()
                    ->placeholder('Masukan NIK')
                    ->integer()
                    ->label("NIK")
                    ->unique(ignoreRecord: true)
                    ->validationMessages([
                        'unique' => 'NIK sudah terdaftar, silakan gunakan yang lain.',
                    ])
                    ->maxLength(16),
                Forms\Components\TextInput::make('nama')
                    ->required()
                    ->placeholder('Masukan Nama')
                    ->maxLength(255),
                Forms\Components\TextInput::make('tempat_lahir')
                    ->required()
                    ->placeholder('Masukan Tempat Lahir')
                    ->maxLength(255),
                Forms\Components\DatePicker::make('tanggal_lahir') // Gunakan DatePicker
                    ->required(),
                Forms\Components\Select::make('jenis_kelamin')
                    ->options([
                        'laki' => 'Laki-laki',
                        'perempuan' => 'Perempuan',
                    ])
                    ->required(),
                Forms\Components\TextInput::make('alamat')
                    ->placeholder('Masukan Alamat (optional)')
                    ->maxLength(255),
                Forms\Components\Select::make('dusun_id')
                    ->options(Dusun::where('status','aktif')->where('tipe', 'utama')->where('id', Auth::user()->dusun_id)->pluck('nama', 'id'))
                    ->default('3')
                    ->label("Dusun")
                    ->required(),
                Forms\Components\Select::make('sub_dusun_id')
                    ->options(Dusun::where('status','aktif')->where('tipe', 'sub_dusun')->pluck('nama', 'id'))
                    ->label("Sub Dusun"),
                Forms\Components\TextInput::make('rt')
                    ->required()
                    ->label('RT')
                    ->placeholder('Masukan nomor RT')
                    ->maxLength(255),
                    Forms\Components\TextInput::make('rw')
                    ->label('RW')
                    ->placeholder('Masukan nomor RW')
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('agama')
                    ->options([
                        'Islam' => 'Islam',
                        'Kristen Protestan' => 'Kristen Protestan',
                        'Katolik' => 'Katolik',
                        'Hindu' => 'Hindu',
                        'Buddha' => 'Buddha',
                        'Konghucu' => 'Konghucu',
                    ])
                    ->nullable(),
                Forms\Components\Select::make('perkawinan')
                    ->label('Status Perkawinan')
                    ->options([
                        'sudah' => 'Sudah Kawin',
                        'belum' => 'Belum Kawin',
                        'cerai_mati' => 'Cerai Mati',
                        'cerai_hidup' => 'Cerai Hidup',
                    ])
                    ->required(),
                Forms\Components\TextInput::make('pekerjaan')
                    ->required()
                    ->placeholder('Masukan Nama Pekerjaan')
                    ->maxLength(255),
                Forms\Components\Select::make('status_penduduk')
                    ->options([
                        'ada' => 'Ada',
                        'meninggal' => 'Meninggal',
                        'pindah' => 'Pindah',
                    ])
                    ->default('ada')
                    ->hidden()
                    ->required(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('NIK')
                    ->label('NIK')
                    ->default('-')
                    ->searchable(),
                Tables\Columns\TextColumn::make('nama')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nomor_kk')
                    ->label('Nomor KK')
                    ->default('-') // Default to '-' if not found
                    ->state(function (Penduduk $record): ?string {
                        // 1. Check if the Penduduk is a 'kepala_keluarga'
                        if ($record->kartuKeluargaSebagaiKepala()->exists()) {
                            return $record->kartuKeluargaSebagaiKepala->first()->nomor_kk;
                        }

                        // 2. Check if the Penduduk is an 'anggotaKeluarga'
                        // Assuming a Penduduk can be an anggota of only one KK at a time
                        if ($record->anggotaKeluarga()->exists()) {
                            // Loop through anggotaKeluarga (though usually one is expected for main KK)
                            foreach ($record->anggotaKeluarga as $anggota) {
                                if ($anggota->kartuKeluarga) { // Check if kartuKeluarga relationship exists
                                    return $anggota->kartuKeluarga->nomor_kk;
                                }
                            }
                        }

                        return '-'; // Return '-' if no KK found
                    }),
                Tables\Columns\TextColumn::make('dusun.nama')
                    ->label('Dusun')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('jenis_kelamin')
                    ->sortable(),
                Tables\Columns\TextColumn::make('agama')
                    ->sortable(),
                Tables\Columns\TextColumn::make('perkawinan'),
                Tables\Columns\TextColumn::make('status_penduduk')
                    ->sortable()
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'ada' => 'success',
                        'meninggal' => 'danger',
                        'pindah' => 'warning',
                    }),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('dusun_id')
                    ->relationship('dusun', 'nama'),
                Tables\Filters\SelectFilter::make('jenis_kelamin')
                    ->options([
                        'laki' => 'Laki-laki',
                        'perempuan' => 'Perempuan',
                    ]),
                Tables\Filters\SelectFilter::make('agama')
                    ->options([
                        'Islam' => 'Islam',
                        'Kristen Protestan' => 'Kristen Protestan',
                        'Katolik' => 'Katolik',
                        'Hindu' => 'Hindu',
                        'Buddha' => 'Buddha',
                        'Konghucu' => 'Konghucu',
                    ]),
            ])
            ->actions([
                Tables\Actions\ViewAction::make()->label('Detail'),
                Tables\Actions\EditAction::make()->visible(fn (): bool => Auth::user()->role !== 'kepala_desa'),
                Tables\Actions\DeleteAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
            ])
            ->defaultPaginationPageOption(50)
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
                ]),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        $user = Auth::user();

        $query = parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ])
            ->where('is_ignore', false);

        if ($user->role === 'admin_dusun') {
            $query->where('dusun_id', $user->dusun_id);
        }

        return $query;
    }


    public static function getRelations(): array
    {
        return [
            // Tambahkan relasi untuk Anggota Kartu Keluarga di sini (misalnya di KartuKeluargaResource)
        ];
    }

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