@php
    $routePrefix = $routePrefix ?? 'admin';
    $lookups = $lookups ?? [];
    $longTextFields = ['description', 'details', 'features', 'admin_note', 'notes', 'instructions', 'body', 'bio', 'skills', 'education', 'experience'];
    $booleanFields = ['auto_submit', 'refill_enabled', 'dripfeed_enabled'];
    $dateFields = ['deadline', 'paid_at', 'starts_at', 'ends_at'];
    $statusOptions = ['active', 'inactive', 'pending', 'queued', 'processing', 'partial', 'assigned', 'in_progress', 'submitted', 'approved', 'revision_required', 'completed', 'published', 'rejected'];

    $selected = fn ($current, $option): string => (string) $current === (string) $option ? ' selected' : '';
    $headline = fn ($value): string => str($value)->replace('_', ' ')->headline()->toString();
    $fieldLabel = fn ($field): string => str($field)->replace('_', ' ')->headline()->toString();

    $lookupFor = function (string $field) use ($module): string {
        return match (true) {
            str_contains($field, 'client_request') => 'requests',
            str_contains($field, 'payment_method') => 'paymentMethods',
            str_contains($field, 'gts_service') => 'gtsServices',
            str_contains($field, 'gts_provider') => 'gtsProviders',
            str_contains($field, 'gts_wallet') => 'gtsWallets',
            str_contains($field, 'designer') => 'designers',
            str_contains($field, 'service') => 'services',
            str_contains($field, 'plan') => 'plans',
            default => str_starts_with($module, 'gts-') ? 'gtsClients' : 'clients',
        };
    };

    $optionTag = function ($optionValue, string $label, $current) use ($selected): string {
        return '<option value="'.e($optionValue).'"'.$selected($current, $optionValue).'>'.e($label).'</option>';
    };

    $lookupLabel = function ($row): string {
        if (isset($row->name)) {
            return (string) $row->name;
        }

        if (isset($row->title)) {
            return (string) $row->title;
        }

        $walletOwner = $row->user->name ?? 'Wallet';
        $currency = $row->currency ?? 'PKR';
        $balance = number_format((float) ($row->balance ?? 0));

        return "{$walletOwner} - {$currency} {$balance}";
    };

    $renderSelect = function (string $field, array $options, $value, $default = null) use ($optionTag): string {
        $current = $value !== null && $value !== '' ? $value : $default;
        $html = '<select name="'.e($field).'">';

        foreach ($options as $optionValue => $label) {
            if (is_int($optionValue)) {
                $optionValue = $label;
            }

            $html .= $optionTag($optionValue, (string) $label, $current);
        }

        return $html.'</select>';
    };

    $renderField = function (string $field, $value) use ($module, $config, $lookups, $longTextFields, $booleanFields, $dateFields, $statusOptions, $lookupFor, $lookupLabel, $optionTag, $renderSelect, $headline): string {
        $fieldName = e($field);
        $safeValue = e($value ?? '');

        if (str_ends_with($field, '_id')) {
            $lookup = $lookupFor($field);
            $html = '<select name="'.$fieldName.'"><option value="">Select</option>';

            foreach (($lookups[$lookup] ?? collect()) as $row) {
                $html .= $optionTag($row->id, $lookupLabel($row), $value);
            }

            return $html.'</select>';
        }

        if (in_array($field, $longTextFields, true)) {
            return '<textarea name="'.$fieldName.'">'.$safeValue.'</textarea>';
        }

        if (str_contains($field, 'path') || $field === 'task_file' || array_key_exists($field, $config['files'] ?? [])) {
            return '<input type="file" name="'.$fieldName.'">';
        }

        if ($field === 'password') {
            $placeholder = $value ? 'Leave blank to keep current password' : '';
            return '<input type="password" name="'.$fieldName.'" placeholder="'.e($placeholder).'">';
        }

        if ($field === 'api_key') {
            $placeholder = $value ? 'Leave blank to keep current API key' : 'Provider API key';
            return '<input type="password" name="'.$fieldName.'" placeholder="'.e($placeholder).'" autocomplete="new-password">';
        }

        if ($field === 'ads_included') {
            return $renderSelect($field, [1 => 'Ads Included', 0 => 'No Ads'], $value, 1);
        }

        if (in_array($field, $booleanFields, true)) {
            return $renderSelect($field, [1 => 'Enabled', 0 => 'Disabled'], $value, 1);
        }

        if ($field === 'type') {
            return $renderSelect($field, ['credit', 'debit', 'refund', 'adjustment'], $value, 'credit');
        }

        if ($field === 'client_type') {
            return $renderSelect($field, ['plan' => 'Plan / Monthly Client', 'one_time' => 'One-Time Order Client'], $value, 'plan');
        }

        if ($field === 'progress') {
            return '<input type="number" name="'.$fieldName.'" min="0" max="100" value="'.e($value ?: 0).'">';
        }

        if ($field === 'sort_order') {
            return '<input type="number" name="'.$fieldName.'" min="0" value="'.e($value ?: 0).'">';
        }

        if ($field === 'status') {
            $labels = collect($statusOptions)->mapWithKeys(fn ($option) => [$option => $headline($option)])->all();
            return $renderSelect($field, $labels, $value, $module === 'tasks' ? 'pending' : 'active');
        }

        if (in_array($field, $dateFields, true)) {
            $dateValue = $value instanceof \Carbon\CarbonInterface ? $value->format('Y-m-d') : $value;
            return '<input type="date" name="'.$fieldName.'" value="'.e($dateValue).'">';
        }

        return '<input name="'.$fieldName.'" value="'.$safeValue.'">';
    };
@endphp

<x-layouts.dashboard :title="($item ? 'Edit ' : 'Add ').$config['singular']">
    <form class="form-card" method="post" enctype="multipart/form-data" action="{{ $item ? route($routePrefix.'.'.$module.'.update', $item->id) : route($routePrefix.'.'.$module.'.store') }}">
        @csrf
        @if ($item)
            @method('PUT')
        @endif

        <div class="form-grid">
            @foreach ($config['fields'] as $field)
                @php
                    $rawValue = data_get($item, $field);
                    $value = old($field, is_array($rawValue) ? implode("\n", $rawValue) : $rawValue);
                    $isLongText = in_array($field, $longTextFields, true);
                @endphp

                <div class="field {{ $isLongText ? 'full-field' : '' }}">
                    <label>{{ $fieldLabel($field) }}</label>
                    {!! $renderField($field, $value) !!}
                </div>
            @endforeach
        </div>

        <p><button class="btn">Save {{ $config['singular'] }}</button></p>
    </form>
</x-layouts.dashboard>
