<?php

namespace App\Filament\Resources\AttendanceResource\Pages;

use App\Filament\Exports\AttendanceExporter;
use App\Filament\Imports\AttendanceImporter;
use App\Filament\Resources\AttendanceResource;
use App\Models\Attendance;
use App\Models\Company;
use App\Models\User;
use App\Services\ExcelExportService;
use App\Services\ExcelImportService;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class ListAttendances extends ListRecords
{
    protected static string $resource = AttendanceResource::class;

    protected function getHeaderActions(): array
    {
        // Cek apakah backdate enabled untuk company user saat ini
        $user = Auth::user();
        $backdateEnabled = $user?->company?->backdate_enabled ?? false;

        return [
            // Custom Export dengan Format Lengkap (Logo, Header, Footer, Tanda Tangan)
            Actions\Action::make('exportFormatted')
                ->label('Export Laporan')
                ->icon('heroicon-o-document-arrow-down')
                ->color('success')
                ->form([
                    Forms\Components\Select::make('company_id')
                        ->label('Perusahaan')
                        ->options(Company::pluck('name', 'id'))
                        ->required()
                        ->native(false)
                        ->searchable()
                        ->preload()
                        ->default(fn() => Auth::user()?->company_id)
                        ->live(),

                    Forms\Components\Select::make('user_id')
                        ->label('Karyawan (Opsional)')
                        ->options(function (callable $get) {
                            $companyId = $get('company_id');
                            if (!$companyId) {
                                return User::pluck('name', 'id');
                            }
                            return User::where('company_id', $companyId)->pluck('name', 'id');
                        })
                        ->native(false)
                        ->searchable()
                        ->preload()
                        ->placeholder('Semua Karyawan'),

                    Forms\Components\DatePicker::make('start_date')
                        ->label('Tanggal Mulai')
                        ->required()
                        ->native(false)
                        ->default(now()->startOfMonth()),

                    Forms\Components\DatePicker::make('end_date')
                        ->label('Tanggal Akhir')
                        ->required()
                        ->native(false)
                        ->default(now()->endOfMonth())
                        ->afterOrEqual('start_date'),
                ])
                ->action(function (array $data) {
                    $company = Company::find($data['company_id']);

                    if (!$company) {
                        Notification::make()
                            ->title('Error')
                            ->body('Perusahaan tidak ditemukan')
                            ->danger()
                            ->send();
                        return;
                    }

                    // Build query - include activities for URAIAN and OUTPUT columns
                    $query = Attendance::with(['user', 'company', 'activities', 'businessTripLocation'])
                        ->where('company_id', $company->id);

                    $startDate = Carbon::parse($data['start_date']);
                    $endDate = Carbon::parse($data['end_date']);

                    $query->whereBetween('date', [$startDate, $endDate]);

                    $filterUser = null;
                    if (!empty($data['user_id'])) {
                        $query->where('user_id', $data['user_id']);
                        $filterUser = User::find($data['user_id']);
                    }

                    $query->orderBy('date', 'desc')->orderBy('user_id');

                    $attendances = $query->get();

                    if ($attendances->isEmpty()) {
                        Notification::make()
                            ->title('Tidak Ada Data')
                            ->body('Tidak ada data kehadiran untuk periode yang dipilih')
                            ->warning()
                            ->send();
                        return;
                    }

                    // Generate export
                    $exportService = new ExcelExportService();
                    $filePath = $exportService->exportAttendance(
                        $attendances,
                        $company,
                        $startDate,
                        $endDate,
                        $filterUser
                    );

                    $fullPath = storage_path('app/' . $filePath);

                    Notification::make()
                        ->title('Export Berhasil')
                        ->body('Laporan berhasil dibuat dengan ' . $attendances->count() . ' data.')
                        ->success()
                        ->send();

                    return redirect()->route('admin.export.download', ['file' => basename($filePath)]);
                }),

            // Custom Import dengan Support Format Template
            // Hanya tampil jika backdate_enabled = true
            Actions\Action::make('importFormatted')
                ->label('Import Laporan')
                ->icon('heroicon-o-document-arrow-up')
                ->color('warning')
                ->visible($backdateEnabled)
                ->form([
                    Forms\Components\FileUpload::make('file')
                        ->label('File Excel')
                        ->required()
                        ->acceptedFileTypes([
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                            'application/vnd.ms-excel',
                            '.xlsx',
                            '.xls',
                        ])
                        ->maxSize(10240)
                        ->disk('local')
                        ->directory('imports')
                        ->visibility('private')
                        ->helperText('Format: .xlsx, .xls (maks 10MB). Gunakan format template yang sama dengan export.'),

                    Forms\Components\Select::make('user_id')
                        ->label('Karyawan')
                        ->options(User::pluck('name', 'id'))
                        ->searchable()
                        ->preload()
                        ->native(false)
                        ->placeholder('Auto-detect dari file (dari baris NAMA)')
                        ->helperText('Biarkan kosong jika file memiliki header NAMA yang berisi nama karyawan.'),

                    Forms\Components\Section::make('Panduan Format Template')
                        ->description('File Excel harus memiliki format seperti hasil export:')
                        ->schema([
                            Forms\Components\Placeholder::make('header_info')
                                ->label('Header (Row 7-9)')
                                ->content('• NAMA | [Nama Karyawan]
• POSISI | [Posisi]
• BULAN | [Bulan Tahun]'),
                            Forms\Components\Placeholder::make('table_columns')
                                ->label('Kolom Tabel (Row 11+)')
                                ->content('• NO - Nomor urut
• TANGGAL - Tanggal kehadiran
• Hari - Nama hari
• WAKTU - Format: "07:33 - 16:47"
• URAIAN - Aktivitas/kegiatan (opsional)
• OUTPUT - Output pekerjaan (opsional)
• KETERANGAN - Lokasi dan status (contoh: "BPKP Pusat - HADIR")'),
                            Forms\Components\Placeholder::make('auto_detect')
                                ->label('Deteksi Otomatis')
                                ->content('Sistem akan otomatis:
• Membaca nama karyawan dari baris NAMA
• Melewati header dan footer
• Mendeteksi status (HADIR/TERLAMBAT/dll) dari kolom KETERANGAN
• Mendeteksi tipe (Kantor/Dinas/Remote) dari lokasi'),
                        ])
                        ->collapsed(),
                ])
                ->action(function (array $data) {
                    $file = $data['file'];
                    $userId = $data['user_id'] ?? null;

                    // Get file path
                    $filePath = null;
                    if ($file instanceof TemporaryUploadedFile) {
                        $filePath = $file->getRealPath();
                    } elseif (is_string($file)) {
                        $filePath = Storage::disk('local')->path($file);
                    }

                    if (!$filePath || !file_exists($filePath)) {
                        Notification::make()
                            ->title('Error')
                            ->body('File tidak dapat dibaca')
                            ->danger()
                            ->send();
                        return;
                    }

                    // Process import
                    $importService = new ExcelImportService();
                    $result = $importService->import($filePath, $userId);

                    // Cleanup
                    if (is_string($file)) {
                        Storage::disk('local')->delete($file);
                    }

                    // Show result
                    if ($result['success'] > 0) {
                        $message = "Berhasil import {$result['success']} data kehadiran.";
                        if ($result['employee_name']) {
                            $message .= "\nKaryawan: {$result['employee_name']}";
                        }
                        if ($result['month']) {
                            $message .= " ({$result['month']})";
                        }
                        if ($result['failed'] > 0) {
                            $message .= "\n{$result['failed']} data gagal diimport.";
                        }

                        Notification::make()
                            ->title('Import Berhasil')
                            ->body($message)
                            ->success()
                            ->send();
                    } elseif (!empty($result['errors'])) {
                        $errorList = array_slice($result['errors'], 0, 5);
                        $errorMsg = implode("\n", $errorList);
                        if (count($result['errors']) > 5) {
                            $errorMsg .= "\n+" . (count($result['errors']) - 5) . " error lainnya";
                        }

                        Notification::make()
                            ->title('Import Gagal')
                            ->body($errorMsg)
                            ->danger()
                            ->persistent()
                            ->send();
                    } else {
                        Notification::make()
                            ->title('Import Selesai')
                            ->body('Tidak ada data yang diimport')
                            ->warning()
                            ->send();
                    }
                }),

            // Export Custom - Pilih kolom yang ingin diexport
            Actions\Action::make('exportCustom')
                ->label('Export Custom')
                ->icon('heroicon-o-table-cells')
                ->color('gray')
                ->form([
                    Forms\Components\Select::make('company_id')
                        ->label('Perusahaan')
                        ->options(Company::pluck('name', 'id'))
                        ->required()
                        ->native(false)
                        ->searchable()
                        ->preload()
                        ->default(fn() => Auth::user()?->company_id)
                        ->live(),

                    Forms\Components\Select::make('user_id')
                        ->label('Karyawan (Opsional)')
                        ->options(function (callable $get) {
                            $companyId = $get('company_id');
                            if (!$companyId) {
                                return User::pluck('name', 'id');
                            }
                            return User::where('company_id', $companyId)->pluck('name', 'id');
                        })
                        ->native(false)
                        ->searchable()
                        ->preload()
                        ->placeholder('Semua Karyawan'),

                    Forms\Components\DatePicker::make('start_date')
                        ->label('Tanggal Mulai')
                        ->required()
                        ->native(false)
                        ->default(now()->startOfMonth()),

                    Forms\Components\DatePicker::make('end_date')
                        ->label('Tanggal Akhir')
                        ->required()
                        ->native(false)
                        ->default(now()->endOfMonth())
                        ->afterOrEqual('start_date'),

                    Forms\Components\Select::make('format')
                        ->label('Format File')
                        ->options([
                            'xlsx' => 'Excel (.xlsx)',
                            'csv' => 'CSV (.csv)',
                        ])
                        ->default('xlsx')
                        ->required()
                        ->native(false),

                    Forms\Components\CheckboxList::make('columns')
                        ->label('Pilih Kolom')
                        ->options([
                            'date' => 'Tanggal',
                            'day' => 'Hari',
                            'user_name' => 'Nama Karyawan',
                            'user_employee_id' => 'NIP',
                            'type' => 'Tipe (Kantor/Dinas/WFH)',
                            'status' => 'Status',
                            'check_in_time' => 'Jam Masuk',
                            'check_out_time' => 'Jam Pulang',
                            'work_duration' => 'Durasi Kerja (Menit)',
                            'overtime_duration' => 'Lembur (Menit)',
                            'check_in_address' => 'Alamat Masuk',
                            'check_out_address' => 'Alamat Pulang',
                            'check_in_latitude' => 'Latitude Masuk',
                            'check_in_longitude' => 'Longitude Masuk',
                            'check_out_latitude' => 'Latitude Pulang',
                            'check_out_longitude' => 'Longitude Pulang',
                            'location_name' => 'Nama Lokasi',
                            'check_in_notes' => 'Catatan Masuk',
                            'check_out_notes' => 'Catatan Pulang',
                            'activities' => 'Aktivitas (Uraian)',
                            'outputs' => 'Output',
                        ])
                        ->default(['date', 'day', 'user_name', 'type', 'status', 'check_in_time', 'check_out_time', 'work_duration', 'location_name'])
                        ->columns(2)
                        ->required()
                        ->helperText('Pilih kolom yang ingin ditampilkan di file export'),
                ])
                ->action(function (array $data) {
                    $company = Company::find($data['company_id']);

                    if (!$company) {
                        Notification::make()
                            ->title('Error')
                            ->body('Perusahaan tidak ditemukan')
                            ->danger()
                            ->send();
                        return;
                    }

                    $startDate = Carbon::parse($data['start_date']);
                    $endDate = Carbon::parse($data['end_date']);
                    $columns = $data['columns'];
                    $format = $data['format'];

                    // Build query
                    $query = Attendance::with(['user', 'company', 'activities', 'location', 'office', 'businessTripLocation'])
                        ->where('company_id', $company->id)
                        ->whereBetween('date', [$startDate, $endDate]);

                    if (!empty($data['user_id'])) {
                        $query->where('user_id', $data['user_id']);
                    }

                    $query->orderBy('date', 'desc')->orderBy('user_id');
                    $attendances = $query->get();

                    if ($attendances->isEmpty()) {
                        Notification::make()
                            ->title('Tidak Ada Data')
                            ->body('Tidak ada data kehadiran untuk periode yang dipilih')
                            ->warning()
                            ->send();
                        return;
                    }

                    // Column definitions with labels
                    $columnDefs = [
                        'date' => 'Tanggal',
                        'day' => 'Hari',
                        'user_name' => 'Nama Karyawan',
                        'user_employee_id' => 'NIP',
                        'type' => 'Tipe',
                        'status' => 'Status',
                        'check_in_time' => 'Jam Masuk',
                        'check_out_time' => 'Jam Pulang',
                        'work_duration' => 'Durasi Kerja (Menit)',
                        'overtime_duration' => 'Lembur (Menit)',
                        'check_in_address' => 'Alamat Masuk',
                        'check_out_address' => 'Alamat Pulang',
                        'check_in_latitude' => 'Latitude Masuk',
                        'check_in_longitude' => 'Longitude Masuk',
                        'check_out_latitude' => 'Latitude Pulang',
                        'check_out_longitude' => 'Longitude Pulang',
                        'location_name' => 'Nama Lokasi',
                        'check_in_notes' => 'Catatan Masuk',
                        'check_out_notes' => 'Catatan Pulang',
                        'activities' => 'Aktivitas (Uraian)',
                        'outputs' => 'Output',
                    ];

                    $dayNames = [
                        'Monday' => 'Senin', 'Tuesday' => 'Selasa', 'Wednesday' => 'Rabu',
                        'Thursday' => 'Kamis', 'Friday' => 'Jumat', 'Saturday' => 'Sabtu', 'Sunday' => 'Minggu',
                    ];

                    $typeLabels = [
                        'office' => 'Kantor', 'wfh' => 'WFH', 'business_trip' => 'Dinas',
                        'pusdiklat' => 'Pusdiklat', 'sick' => 'Sakit', 'permission' => 'Izin', 'leave' => 'Cuti',
                    ];

                    $statusLabels = [
                        'present' => 'Hadir', 'late' => 'Terlambat', 'early_leave' => 'Pulang Awal',
                        'absent' => 'Tidak Hadir', 'sick' => 'Sakit', 'leave' => 'Cuti', 'permission' => 'Izin',
                    ];

                    // Create spreadsheet
                    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
                    $sheet = $spreadsheet->getActiveSheet();
                    $sheet->setTitle('Data Kehadiran');

                    // Add headers
                    $colIndex = 1;
                    foreach ($columns as $col) {
                        $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex);
                        $sheet->setCellValue("{$colLetter}1", $columnDefs[$col] ?? $col);
                        $colIndex++;
                    }

                    // Style header row
                    $lastColLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(count($columns));
                    $sheet->getStyle("A1:{$lastColLetter}1")->applyFromArray([
                        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
                        'fill' => [
                            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                            'startColor' => ['rgb' => '4472C4'],
                        ],
                    ]);

                    // Add data rows
                    $rowIndex = 2;
                    foreach ($attendances as $attendance) {
                        $colIndex = 1;
                        foreach ($columns as $col) {
                            $value = match ($col) {
                                'date' => Carbon::parse($attendance->date)->format('Y-m-d'),
                                'day' => $dayNames[Carbon::parse($attendance->date)->format('l')] ?? Carbon::parse($attendance->date)->format('l'),
                                'user_name' => $attendance->user?->name ?? '-',
                                'user_employee_id' => $attendance->user?->employee_id ?? '-',
                                'type' => $typeLabels[$attendance->type] ?? $attendance->type ?? '-',
                                'status' => $statusLabels[$attendance->status] ?? $attendance->status ?? '-',
                                'check_in_time' => $attendance->check_in_time ? Carbon::parse($attendance->check_in_time)->format('H:i') : '-',
                                'check_out_time' => $attendance->check_out_time ? Carbon::parse($attendance->check_out_time)->format('H:i') : '-',
                                'work_duration' => $attendance->work_duration ?? '-',
                                'overtime_duration' => $attendance->overtime_duration ?? '-',
                                'check_in_address' => $attendance->check_in_address ?? '-',
                                'check_out_address' => $attendance->check_out_address ?? '-',
                                'check_in_latitude' => $attendance->check_in_latitude ?? '-',
                                'check_in_longitude' => $attendance->check_in_longitude ?? '-',
                                'check_out_latitude' => $attendance->check_out_latitude ?? '-',
                                'check_out_longitude' => $attendance->check_out_longitude ?? '-',
                                'location_name' => $attendance->location?->name ?? $attendance->office?->name ?? $attendance->businessTripLocation?->name ?? '-',
                                'check_in_notes' => $attendance->check_in_notes ?? '-',
                                'check_out_notes' => $attendance->check_out_notes ?? '-',
                                'activities' => implode('; ', $attendance->activities?->pluck('activity')->filter()->toArray() ?? []) ?: '-',
                                'outputs' => implode('; ', $attendance->activities?->pluck('output')->filter()->toArray() ?? []) ?: '-',
                                default => '-',
                            };
                            $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex);
                            $sheet->setCellValue("{$colLetter}{$rowIndex}", $value);
                            $colIndex++;
                        }
                        $rowIndex++;
                    }

                    // Auto-size columns
                    foreach (range(1, count($columns)) as $col) {
                        $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col);
                        $sheet->getColumnDimension($colLetter)->setAutoSize(true);
                    }

                    // Generate filename
                    $filename = 'kehadiran_' . str_replace(' ', '_', strtolower($company->name)) . '_' . $startDate->format('Ymd') . '-' . $endDate->format('Ymd');

                    // Save file
                    $tempDir = storage_path('app/exports');
                    if (!is_dir($tempDir)) {
                        mkdir($tempDir, 0755, true);
                    }

                    if ($format === 'csv') {
                        $filename .= '.csv';
                        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
                        $writer->setDelimiter(',');
                        $writer->setEnclosure('"');
                    } else {
                        $filename .= '.xlsx';
                        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
                    }

                    $fullPath = $tempDir . '/' . $filename;
                    $writer->save($fullPath);

                    Notification::make()
                        ->title('Export Berhasil')
                        ->body('Data berhasil diexport dengan ' . $attendances->count() . ' baris.')
                        ->success()
                        ->send();

                    return redirect()->route('admin.export.download', ['file' => $filename]);
                }),

            // Legacy Import (Raw Data)
            // Hanya tampil jika backdate_enabled = true
            Actions\ImportAction::make('importRaw')
                ->importer(AttendanceImporter::class)
                ->label('Import Data Mentah')
                ->icon('heroicon-o-arrow-up-tray')
                ->color('gray')
                ->csvDelimiter(',')
                ->maxRows(5000)
                ->visible($backdateEnabled),

            Actions\CreateAction::make(),
        ];
    }
}
