<?php

namespace App\Filament\Resources;

use App\Filament\Resources\CompanyResource\Pages;
use App\Models\Company;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class CompanyResource extends Resource
{
    protected static ?string $model = Company::class;

    protected static ?string $navigationIcon = 'heroicon-o-building-office-2';

    protected static ?string $navigationGroup = 'Master Data';

    protected static ?string $navigationLabel = 'Perusahaan/Instansi';

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Dasar')
                    ->schema([
                        Forms\Components\Grid::make(2)
                            ->schema([
                                Forms\Components\FileUpload::make('logo')
                                    ->label('Logo Kiri (Instansi)')
                                    ->image()
                                    ->disk('public_direct')
                                    ->directory('logos')
                                    ->visibility('public')
                                    ->helperText('Logo utama (kiri) di header laporan Excel. Format: JPG, PNG.'),
                                Forms\Components\FileUpload::make('secondary_logo')
                                    ->label('Logo Kanan (Project/Client)')
                                    ->image()
                                    ->disk('public_direct')
                                    ->directory('logos')
                                    ->visibility('public')
                                    ->helperText('Logo kedua (kanan) di header laporan Excel. Format: JPG, PNG.'),
                            ]),
                        Forms\Components\TextInput::make('name')
                            ->label('Nama Perusahaan/Instansi')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('code')
                            ->label('Kode')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(255),
                        Forms\Components\TextInput::make('project_name')
                            ->label('Nama Project')
                            ->maxLength(255)
                            ->placeholder('PROJECT MANAGEMENT CONSULTANT (PMC)')
                            ->helperText('Nama project yang tampil di laporan Excel (baris ke-4)')
                            ->columnSpanFull(),
                        Forms\Components\Textarea::make('address')
                            ->label('Alamat')
                            ->columnSpanFull(),
                        Forms\Components\TextInput::make('city')
                            ->label('Kota')
                            ->maxLength(255)
                            ->placeholder('Jakarta')
                            ->helperText('Kota untuk tanda tangan di laporan Excel'),
                        Forms\Components\TextInput::make('phone')
                            ->label('No. Telepon')
                            ->tel()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('email')
                            ->email()
                            ->maxLength(255),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Kontak Support')
                    ->description('Informasi kontak untuk bantuan karyawan di aplikasi mobile')
                    ->schema([
                        Forms\Components\TextInput::make('support_phone')
                            ->label('No. Telepon Support')
                            ->tel()
                            ->maxLength(255)
                            ->helperText('Nomor telepon/WhatsApp untuk bantuan karyawan'),
                        Forms\Components\TextInput::make('support_email')
                            ->label('Email Support')
                            ->email()
                            ->maxLength(255)
                            ->helperText('Jika kosong, akan menggunakan email perusahaan'),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Team Leader / Atasan')
                    ->description('Informasi atasan untuk tanda tangan laporan kegiatan')
                    ->schema([
                        Forms\Components\TextInput::make('team_leader_name')
                            ->label('Nama Team Leader')
                            ->maxLength(255)
                            ->helperText('Nama atasan yang akan muncul di laporan'),
                        Forms\Components\TextInput::make('team_leader_position')
                            ->label('Jabatan Team Leader')
                            ->maxLength(255)
                            ->helperText('Contoh: Team Leader'),
                        Forms\Components\TextInput::make('honorarium_per_day')
                            ->label('Honorarium Per Hari (Rp)')
                            ->numeric()
                            ->prefix('Rp')
                            ->helperText('Untuk kalkulasi honorarium di laporan bulanan'),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Lokasi & Radius')
                    ->schema([
                        Forms\Components\TextInput::make('latitude')
                            ->label('Latitude')
                            ->numeric()
                            ->step(0.00000001),
                        Forms\Components\TextInput::make('longitude')
                            ->label('Longitude')
                            ->numeric()
                            ->step(0.00000001),
                        Forms\Components\TextInput::make('radius')
                            ->label('Radius (meter)')
                            ->required()
                            ->numeric()
                            ->default(100)
                            ->helperText('Radius dalam meter untuk validasi lokasi absensi'),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Jam Kerja')
                    ->schema([
                        Forms\Components\TimePicker::make('work_start_time')
                            ->label('Jam Masuk')
                            ->required()
                            ->seconds(false),
                        Forms\Components\TimePicker::make('work_end_time')
                            ->label('Jam Pulang')
                            ->required()
                            ->seconds(false),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Pengaturan Umum')
                    ->schema([
                        Forms\Components\Toggle::make('is_active')
                            ->label('Aktif')
                            ->default(true)
                            ->helperText('Nonaktifkan untuk menonaktifkan seluruh aktivitas perusahaan'),
                        Forms\Components\Toggle::make('bypass_claim_approval')
                            ->label('Bypass Approval Klaim')
                            ->default(false)
                            ->helperText('Aktifkan untuk melewati proses approval klaim'),
                        Forms\Components\Toggle::make('allow_document_upload')
                            ->label('Aktifkan Upload Dokumen')
                            ->default(true)
                            ->helperText('Tampilkan fitur upload dokumen pendukung untuk perjalanan dinas'),
                        Forms\Components\Toggle::make('allow_business_trip')
                            ->label('Aktifkan Perjalanan Dinas')
                            ->default(true)
                            ->helperText('Aktifkan fitur perjalanan dinas untuk karyawan'),
                        Forms\Components\Toggle::make('office_time_enabled')
                            ->label('Aktifkan Sistem Shift')
                            ->default(false)
                            ->helperText('Jika aktif, gunakan sistem shift untuk menentukan jam masuk/pulang per karyawan'),
                        Forms\Components\TextInput::make('late_tolerance_minutes')
                            ->label('Toleransi Keterlambatan (menit)')
                            ->numeric()
                            ->default(15)
                            ->helperText('Menit toleransi sebelum dianggap terlambat'),
                        Forms\Components\Toggle::make('allow_employee_edit_home_location')
                            ->label('Izinkan Karyawan Edit Lokasi Rumah')
                            ->default(false)
                            ->helperText('Jika aktif, karyawan dapat mengubah lokasi rumah mereka sendiri untuk keperluan WFH'),
                    ])
                    ->columns(2),

                // Advanced settings - managed via API
                Forms\Components\Hidden::make('allow_editable_location')
                    ->default(true),
                Forms\Components\Hidden::make('backdate_enabled')
                    ->default(true),
                Forms\Components\Hidden::make('attendance_auto_enabled')
                    ->default(true),
                Forms\Components\Hidden::make('device_validation_enabled')
                    ->default(false),
                Forms\Components\Hidden::make('max_devices_per_user')
                    ->default(3),

                Forms\Components\Section::make('Pengaturan Hari Libur')
                    ->description('Atur hari libur mingguan dan pengingat')
                    ->schema([
                        Forms\Components\CheckboxList::make('weekend_days')
                            ->label('Hari Libur Mingguan')
                            ->options([
                                0 => 'Minggu',
                                1 => 'Senin',
                                2 => 'Selasa',
                                3 => 'Rabu',
                                4 => 'Kamis',
                                5 => 'Jumat',
                                6 => 'Sabtu',
                            ])
                            ->default([0, 6])
                            ->columns(4)
                            ->helperText('Pilih hari yang dianggap libur'),
                        Forms\Components\Toggle::make('alarm_enabled')
                            ->label('Aktifkan Pengingat/Alarm')
                            ->default(true)
                            ->helperText('Aktifkan notifikasi pengingat check-in/check-out'),
                        Forms\Components\TimePicker::make('checkin_reminder_time')
                            ->label('Waktu Pengingat Check-in')
                            ->seconds(false)
                            ->helperText('Jam pengingat untuk check-in (kosongkan untuk menggunakan jam masuk)'),
                        Forms\Components\TextInput::make('checkout_reminder_after_hours')
                            ->label('Pengingat Check-out Setelah (jam)')
                            ->numeric()
                            ->default(9)
                            ->helperText('Ingatkan check-out setelah X jam dari check-in'),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Pengaturan Lembur/Overtime')
                    ->schema([
                        Forms\Components\Toggle::make('overtime_enabled')
                            ->label('Aktifkan Fitur Lembur')
                            ->default(true)
                            ->helperText('Izinkan karyawan mengajukan lembur'),
                        Forms\Components\Toggle::make('overtime_auto_approval')
                            ->label('Auto Approve Lembur')
                            ->default(false)
                            ->helperText('Otomatis setujui pengajuan lembur tanpa approval admin'),
                        Forms\Components\TextInput::make('minimum_overtime_minutes')
                            ->label('Minimal Durasi Lembur (menit)')
                            ->numeric()
                            ->default(30)
                            ->helperText('Durasi minimal agar lembur bisa diklaim'),
                    ])
                    ->columns(3),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Nama')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('code')
                    ->label('Kode')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('phone')
                    ->label('Telepon')
                    ->searchable(),
                Tables\Columns\TextColumn::make('email')
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('radius')
                    ->label('Radius')
                    ->suffix(' m')
                    ->sortable(),
                Tables\Columns\TextColumn::make('work_start_time')
                    ->label('Jam Masuk')
                    ->time('H:i'),
                Tables\Columns\TextColumn::make('work_end_time')
                    ->label('Jam Pulang')
                    ->time('H:i'),
                Tables\Columns\IconColumn::make('is_active')
                    ->label('Aktif')
                    ->boolean(),
                Tables\Columns\IconColumn::make('allow_document_upload')
                    ->label('Upload Dok')
                    ->boolean(),
                Tables\Columns\TextColumn::make('users_count')
                    ->label('Jml User')
                    ->counts('users')
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d M Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Status Aktif'),
                Tables\Filters\TernaryFilter::make('allow_document_upload')
                    ->label('Upload Dokumen'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                // Bulk actions disabled - admin can only view/edit companies
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCompanies::route('/'),
            'create' => Pages\CreateCompany::route('/create'),
            'view' => Pages\ViewCompany::route('/{record}'),
            'edit' => Pages\EditCompany::route('/{record}/edit'),
        ];
    }

    // Only super_admin can create companies
    public static function canCreate(): bool
    {
        $user = auth()->user();
        return $user && $user->role === 'super_admin';
    }

    // Only super_admin can delete companies
    public static function canDelete(\Illuminate\Database\Eloquent\Model $record): bool
    {
        $user = auth()->user();
        return $user && $user->role === 'super_admin';
    }

    public static function canDeleteAny(): bool
    {
        $user = auth()->user();
        return $user && $user->role === 'super_admin';
    }
}
