<?php

namespace App\Filament\Employee\Imports;

use App\Models\Activity;
use App\Models\Attendance;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Carbon\Carbon;

class MyActivityImporter extends Importer
{
    protected static ?string $model = Activity::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('date')
                ->label('Tanggal')
                ->requiredMapping()
                ->rules(['required'])
                ->example('2026-01-03'),

            ImportColumn::make('start_time')
                ->label('Jam Mulai')
                ->requiredMapping()
                ->rules(['required'])
                ->example('08:00'),

            ImportColumn::make('end_time')
                ->label('Jam Selesai')
                ->requiredMapping()
                ->rules(['required'])
                ->example('12:00'),

            ImportColumn::make('activity')
                ->label('Aktivitas')
                ->requiredMapping()
                ->rules(['required', 'string'])
                ->example('Rapat koordinasi tim'),

            ImportColumn::make('output')
                ->label('Output/Hasil')
                ->rules(['nullable', 'string'])
                ->example('Notulen rapat'),

            ImportColumn::make('notes')
                ->label('Catatan')
                ->rules(['nullable', 'string'])
                ->example('Peserta: 10 orang'),
        ];
    }

    public function resolveRecord(): ?Activity
    {
        $data = $this->data;
        $user = auth()->user();

        // Parse date
        $date = $this->parseDate($data['date'] ?? null);
        if (!$date) {
            return null;
        }

        // Parse times
        $startTime = $this->parseTime($data['start_time'] ?? null);
        $endTime = $this->parseTime($data['end_time'] ?? null);

        if (!$startTime || !$endTime) {
            return null;
        }

        // Find related attendance
        $attendance = Attendance::where('user_id', $user->id)
            ->whereDate('date', $date)
            ->first();

        // Create new activity
        return Activity::create([
            'user_id' => $user->id,
            'attendance_id' => $attendance?->id,
            'date' => $date,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'activity' => $data['activity'] ?? '',
            'output' => $data['output'] ?? null,
            'notes' => $data['notes'] ?? null,
        ]);
    }

    protected function parseDate(mixed $date): ?string
    {
        if (empty($date)) {
            return null;
        }

        // Handle Excel serial date number
        if (is_numeric($date) && $date > 1) {
            $unixTimestamp = ($date - 25569) * 86400;
            return Carbon::createFromTimestamp($unixTimestamp)->format('Y-m-d');
        }

        try {
            return Carbon::parse($date)->format('Y-m-d');
        } catch (\Exception $e) {
            return null;
        }
    }

    protected function parseTime(mixed $time): ?string
    {
        if (empty($time)) {
            return null;
        }

        // Handle Excel numeric time format
        if (is_numeric($time) && $time < 1) {
            $totalSeconds = round($time * 86400);
            $hours = floor($totalSeconds / 3600);
            $minutes = floor(($totalSeconds % 3600) / 60);
            $seconds = $totalSeconds % 60;
            return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
        }

        $time = trim((string) $time);

        // Handle various time formats
        if (preg_match('/^(\d{1,2}):(\d{2})(:\d{2})?/', $time, $matches)) {
            $hours = str_pad($matches[1], 2, '0', STR_PAD_LEFT);
            $minutes = $matches[2];
            $seconds = isset($matches[3]) ? substr($matches[3], 1) : '00';
            return "$hours:$minutes:$seconds";
        }

        try {
            return Carbon::parse($time)->format('H:i:s');
        } catch (\Exception $e) {
            return null;
        }
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Import aktivitas selesai. ' . number_format($import->successful_rows) . ' baris berhasil diimport.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $body .= ' ' . number_format($failedRowsCount) . ' baris gagal.';
        }

        return $body;
    }
}
