<?php

declare(strict_types=1);

namespace App\Filament\Support;

use App\Services\Leave\LeaveDaysCalculator;
use Carbon\Carbon;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;

class HrForm
{
    public static function fileUpload(string $name): FileUpload
    {
        return FileUpload::make($name)
            ->disk(config('hr.file_uploads.disk'))
            ->directory(config('hr.file_uploads.directory'))
            ->visibility('private');
    }

    public static function employeeSelect(): Select
    {
        return Select::make('employee_id')
            ->label(__('hr.fields.employee'))
            ->relationship('employee', 'full_name')
            ->searchable()
            ->preload()
            ->required();
    }

    public static function leaveDaysDisplay(): TextInput
    {
        return TextInput::make('days')
            ->label(__('hr.fields.days'))
            ->numeric()
            ->disabled()
            ->dehydrated(false)
            ->afterStateHydrated(function (TextInput $component, $state, Set $set, Get $get): void {
                self::syncLeaveDays($set, $get);
            });
    }

    public static function leaveDatePicker(string $name, string $label): DatePicker
    {
        return DatePicker::make($name)
            ->label($label)
            ->required()
            ->live()
            ->afterStateUpdated(fn (Set $set, Get $get) => self::syncLeaveDays($set, $get));
    }

    public static function syncLeaveDays(Set $set, Get $get): void
    {
        $startDate = $get('start_date');
        $endDate = $get('end_date');

        if (! $startDate || ! $endDate) {
            $set('days', null);

            return;
        }

        $days = app(LeaveDaysCalculator::class)->between(
            Carbon::parse($startDate),
            Carbon::parse($endDate),
        );

        $set('days', $days);
    }
}
