<?php

namespace App\Filament\Resources;

use App\Filament\Resources\KartuKeluargaResource\Pages;
use App\Filament\Resources\KartuKeluargaResource\RelationManagers;
use App\Models\Dusun;
use App\Models\KartuKeluarga;
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 KartuKeluargaResource extends Resource
{
    protected static ?string $model = KartuKeluarga::class;

    protected static ?string $navigationIcon = 'heroicon-o-paper-clip';
    protected static ?string $activeNavigationIcon = 'heroicon-s-paper-clip';
    protected static ?string $navigationGroup = 'Kelola Data';
    protected static ?string $navigationLabel = 'Data Kartu Keluarga';
    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('nomor_kk')
                    ->required()
                    ->placeholder('Masukan nomor KK')
                    ->minLength(16)
                    ->maxLength(16),
                Forms\Components\TextInput::make('kepala_keluarga')
                    ->placeholder('Masukan nama kepala keluarga')
                    ->required(),
                Forms\Components\Select::make('dusun_id')
                    ->options(Dusun::where('status','aktif')->where('tipe', 'utama')->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')
                    ->label("RT")
                    ->placeholder('Masukan nomor RT')
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('rw')
                    ->label("RW")
                    ->placeholder('Masukan nomor RW')
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('kabupaten')
                    ->placeholder('Masukan kabupaten')
                    ->label("Kabupaten/Kota")
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('kecamatan')
                    ->placeholder('Masukan kecamatan')
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('provinsi')
                    ->placeholder('Masukan provinsi')
                    ->required()
                    ->maxLength(255),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('nomor_kk')
                    ->searchable(),
                Tables\Columns\TextColumn::make('kepala_keluarga')
                    ->default('-')
                    ->sortable(),
                Tables\Columns\TextColumn::make('dusun.nama')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('rt')
                    ->searchable(),
                Tables\Columns\TextColumn::make('rw')
                    ->searchable(),
                Tables\Columns\TextColumn::make('kecamatan')
                    ->searchable(),
                Tables\Columns\TextColumn::make('kabupaten')
                    ->searchable(),
                Tables\Columns\TextColumn::make('provinsi')
                    ->searchable(),
                Tables\Columns\TextColumn::make('jumlah_anak')
                    ->label('Jumlah Anak')
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\Action::make('manage_anggota')
                    ->label('Atur Anggota')
                    ->icon('heroicon-o-users') // Icon untuk mengelola anggota
                    ->color('info') // Warna tombol (misal: biru muda)
                    ->url(fn (KartuKeluarga $record): string => static::getUrl('manage-anggota', ['record' => $record])),
                Tables\Actions\EditAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
                Tables\Actions\DeleteAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
            ])
            ->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()
            ->withCount([
                'anggotaKeluarga as jumlah_anak' => function ($query) {
                    $query->where('hubungan', 'anak');
                },
            ]);

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

        return $query;
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListKartuKeluargas::route('/'),
            'create' => Pages\CreateKartuKeluarga::route('/create'),
            'edit' => Pages\EditKartuKeluarga::route('/{record}/edit'),
            'manage-anggota' => Pages\ManageAnggotaKeluarga::route('/{record}/anggota'),
        ];
    }
    
    public static function canAccess(): bool
    {
        return Auth::user()->role !== 'warga';
    }
}
