<?php

namespace App\Filament\Actions;

use App\Models\Attendance;
use App\Models\Company;
use App\Models\User;
use App\Services\ExcelExportService;
use Carbon\Carbon;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ExportFormattedAttendanceAction extends Action
{
    public static function getDefaultName(): ?string
    {
        return 'exportFormatted';
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->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),

                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
                // Include location (unified), office (legacy), businessTripLocation (legacy) for KETERANGAN column
                $query = Attendance::with(['user', 'company', 'activities', 'location', 'office', '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
                );

                // Store file path for download
                $fullPath = storage_path('app/' . $filePath);

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

                // Return file for download
                return response()->download($fullPath, basename($filePath), [
                    'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                ])->deleteFileAfterSend(false);
            });
    }
}
