<?php

namespace App\Http\Controllers\Admin\Settings;

use App\Http\Controllers\Controller;
use App\Models\AiTokenLog;
use App\Services\ModalIndexQuey;
use Illuminate\Http\Request;

class AIController extends Controller
{
    /**
     * Display the AI providers settings.
     */
    public function index()
    {
        adminUserHasPermission(permission: 'read');

        $buttons = [
            [
                'label' => __('Logs'),
                'icon' => 'ph ph-list',
                'type' => 'link',
                'link' => route('admin.settings.ai-settings.logs'),
            ],
        ];

        $providers = [];
        $aiConfig = getOptionWithJsonDecode('ai_providers_config', config('services.ai', []));

        foreach ($aiConfig as $key => $cfg) {
            $providers[] = [
                'name' => ucfirst($key),
                'key' => $key,
                'api_url' => $cfg['api_url'] ?? '',
                'api_key' => $cfg['api_key'] ?? '',
                'model' => $cfg['model'] ?? '',
                'timeout' => $cfg['timeout'] ?? 3,
                'is_active' => $cfg['is_active'] ?? false,
            ];
        }

        $columns = [
            ['label' => __('Name'), 'key' => 'name'],
            ['label' => __('API URL'), 'key' => 'api_url'],
            ['label' => __('Model'), 'key' => 'model'],
            ['label' => __('Is Active'), 'key' => 'is_active', 'render' => function ($item) {
                return $item['is_active']
                    ? '<span class="status success">'.__('Yes').'</span>'
                    : '<span class="status danger">'.__('No').'</span>';
            }],
            ['label' => __('Action'), 'render' => function ($item) {
                $action_buttons = [
                    [
                        'label' => __('Edit'),
                        'icon' => 'ph ph-pencil',
                        'id' => 'ai_edit_modal_id',
                        'row' => json_encode($item),
                        'type' => 'modal',
                        'href' => route('admin.settings.ai-settings.update', $item['key']),
                    ],
                    [
                        'label' => $item['is_active'] ? __('Deactivate') : __('Activate'),
                        'icon' => $item['is_active'] ? 'ph ph-toggle-left' : 'ph ph-toggle-right',
                        'type' => 'link',
                        'href' => route('admin.settings.ai-settings.enable', $item['key']),
                    ],
                ];

                return view('admin.components.table-action', compact('action_buttons'))->render();
            }],
        ];

        return view('admin.pages.settings.ai.index', compact('providers', 'columns', 'buttons'));
    }

    /**
     * Update settings for an AI provider.
     */
    public function update(Request $request, $key)
    {
        adminUserHasPermission(permission: 'edit');

        $validated = $request->validate([
            'api_url' => 'required|url',
            'api_key' => 'required|string',
            'model' => 'required|string',
            'timeout' => 'required|integer',
            'is_active' => 'sometimes|boolean',
        ]);

        $providers = getOptionWithJsonDecode('ai_providers_config', config('services.ai', []));

        if (! isset($providers[$key])) {
            abort(404, __('AI provider not found'));
        }

        $providers[$key] = array_merge($providers[$key], [
            'api_url' => $validated['api_url'],
            'api_key' => $validated['api_key'],
            'model' => $validated['model'],
            'timeout' => $validated['timeout'],
            'is_active' => $validated['is_active'] ?? ($providers[$key]['is_active'] ?? false),
        ]);

        if (! empty($validated['is_active'])) {
            foreach ($providers as $providerKey => &$providerConfig) {
                if ($providerKey !== $key) {
                    $providerConfig['is_active'] = false;
                }
            }
            unset($providerConfig);
        }

        storeOption([
            'ai_providers_config' => $providers,
        ]);

        return response()->json([
            'message' => __('AI provider settings updated successfully'),
            'reload' => true,
        ]);
    }

    /**
     * Toggle activation status of an AI provider.
     */
    public function enable(Request $request, $key)
    {
        adminUserHasPermission(permission: 'edit');

        $providers = getOptionWithJsonDecode('ai_providers_config', config('services.ai', []));

        if (! isset($providers[$key])) {
            abort(404, __('AI provider not found'));
        }
        foreach ($providers as $providerKey => &$providerConfig) {
            $providerConfig['is_active'] = ($providerKey === $key);
        }
        unset($providerConfig);

        storeOption([
            'ai_providers_config' => $providers,
        ]);

        return back()->withSuccess(__('AI provider activation updated'));
    }

    public function logs()
    {
        adminUserHasPermission(permission: 'read');

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-back',
                'type' => 'link',
                'link' => route('admin.settings.ai-settings.index'),
            ],
        ];

        $logs = ModalIndexQuey::get(model: AiTokenLog::query());

        $columns = [
            [
                'label' => __('Modal'),
                'key' => 'model',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Prompt Token Count'),
                'key' => 'prompt_token_count',
            ],
            [
                'label' => __('Completion Count'),
                'key' => 'completion_tokens',
            ],
            [
                'label' => __('Total Count'),
                'key' => 'total_token_count',
            ],
            [
                'label' => __('Created At'),
                'key' => 'created_at',
                'render' => function ($item) {
                    return $item->created_at->format('Y-m-d h:i A').' <br> '.$item->created_at->diffForHumans();
                },
            ],
        ];

        return view('admin.pages.settings.ai.list', compact('logs', 'columns', 'buttons'));
    }
}
