<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiSetting;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class AISettingController extends Controller
{
    /**
     * Display all AI settings.
     */
    public function index(): View
    {
        $settings = AiSetting::orderBy('is_active', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        $providers = AiSetting::getAvailableProviders();
        $activeSetting = AiSetting::getActive();

        return view('admin.ai.index', compact('settings', 'providers', 'activeSetting'));
    }

    /**
     * Show the form for creating a new AI setting.
     */
    public function create(): View
    {
        $providers = AiSetting::getAvailableProviders();
        $defaultUrls = AiSetting::DEFAULT_URLS;
        $defaultModels = AiSetting::DEFAULT_MODELS;

        return view('admin.ai.create', compact('providers', 'defaultUrls', 'defaultModels'));
    }

    /**
     * Store a newly created AI setting.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'provider' => 'required|in:openai,ollama,lmstudio,custom',
            'name' => 'required|string|max:255',
            'api_key' => 'nullable|string|max:500',
            'api_url' => 'required|url|max:500',
            'model' => 'required|string|max:100',
            'system_prompt' => 'nullable|string|max:5000',
            'max_tokens' => 'nullable|integer|min:100|max:32000',
            'temperature' => 'nullable|numeric|min:0|max:2',
            'max_history' => 'nullable|integer|min:1|max:50',
            'is_active' => 'nullable|boolean',
        ]);

        // Set defaults
        $validated['max_tokens'] = $validated['max_tokens'] ?? 1000;
        $validated['temperature'] = $validated['temperature'] ?? 0.7;
        $validated['max_history'] = $validated['max_history'] ?? 10;
        $validated['is_active'] = $validated['is_active'] ?? false;

        // If setting is active, deactivate all others
        if ($validated['is_active']) {
            AiSetting::where('is_active', true)->update(['is_active' => false]);
        }

        AiSetting::create($validated);

        return redirect()
            ->route('admin.ai-settings.index')
            ->with('success', 'AI ayarı başarıyla oluşturuldu.');
    }

    /**
     * Show the form for editing the specified AI setting.
     */
    public function edit(AiSetting $aiSetting): View
    {
        $providers = AiSetting::getAvailableProviders();
        $defaultUrls = AiSetting::DEFAULT_URLS;
        $defaultModels = AiSetting::DEFAULT_MODELS;

        return view('admin.ai.edit', compact('aiSetting', 'providers', 'defaultUrls', 'defaultModels'));
    }

    /**
     * Update the specified AI setting.
     */
    public function update(Request $request, AiSetting $aiSetting)
    {
        $validated = $request->validate([
            'provider' => 'required|in:openai,ollama,lmstudio,custom',
            'name' => 'required|string|max:255',
            'api_key' => 'nullable|string|max:500',
            'api_url' => 'required|url|max:500',
            'model' => 'required|string|max:100',
            'system_prompt' => 'nullable|string|max:5000',
            'max_tokens' => 'nullable|integer|min:100|max:32000',
            'temperature' => 'nullable|numeric|min:0|max:2',
            'max_history' => 'nullable|integer|min:1|max:50',
            'is_active' => 'nullable|boolean',
        ]);

        // Set defaults
        $validated['max_tokens'] = $validated['max_tokens'] ?? 1000;
        $validated['temperature'] = $validated['temperature'] ?? 0.7;
        $validated['max_history'] = $validated['max_history'] ?? 10;
        $validated['is_active'] = $validated['is_active'] ?? false;

        // If setting is being activated, deactivate all others
        if ($validated['is_active'] && !$aiSetting->is_active) {
            AiSetting::where('id', '!=', $aiSetting->id)
                ->where('is_active', true)
                ->update(['is_active' => false]);
        }

        $aiSetting->update($validated);

        return redirect()
            ->route('admin.ai-settings.index')
            ->with('success', 'AI ayarı başarıyla güncellendi.');
    }

    /**
     * Remove the specified AI setting.
     */
    public function destroy(AiSetting $aiSetting)
    {
        $aiSetting->delete();

        if (request()->expectsJson()) {
            return response()->json(['success' => true, 'message' => 'AI ayarı başarıyla silindi.']);
        }

        return redirect()
            ->route('admin.ai-settings.index')
            ->with('success', 'AI ayarı başarıyla silindi.');
    }

    /**
     * Toggle active status of the specified AI setting.
     */
    public function toggleActive(AiSetting $aiSetting): JsonResponse
    {
        if ($aiSetting->is_active) {
            // Deactivate
            $aiSetting->update(['is_active' => false]);
            $message = 'AI ayarı devre dışı bırakıldı.';
        } else {
            // Activate and deactivate others
            AiSetting::where('id', '!=', $aiSetting->id)
                ->where('is_active', true)
                ->update(['is_active' => false]);

            $aiSetting->update(['is_active' => true]);
            $message = 'AI ayarı aktif edildi.';
        }

        return response()->json([
            'success' => true,
            'message' => $message,
            'is_active' => $aiSetting->fresh()->is_active,
        ]);
    }

    /**
     * Test connection to AI provider.
     */
    public function testConnection(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'provider' => 'required|in:openai,ollama,lmstudio,custom',
            'api_key' => 'nullable|string',
            'api_url' => 'required|url',
            'model' => 'required|string',
        ]);

        // Create temporary setting for testing
        $tempSetting = new AiSetting([
            'provider' => $validated['provider'],
            'api_key' => $validated['api_key'],
            'api_url' => $validated['api_url'],
            'model' => $validated['model'],
        ]);

        $result = \App\Services\AIService::testConnection($tempSetting);

        return response()->json($result);
    }

    /**
     * Get provider defaults (AJAX).
     */
    public function getProviderDefaults(Request $request): JsonResponse
    {
        $provider = $request->input('provider');

        if (!array_key_exists($provider, AiSetting::DEFAULT_URLS)) {
            return response()->json(['error' => 'Geçersiz provider'], 400);
        }

        return response()->json([
            'api_url' => AiSetting::DEFAULT_URLS[$provider],
            'model' => AiSetting::DEFAULT_MODELS[$provider],
            'requires_api_key' => in_array($provider, ['openai', 'custom']),
        ]);
    }
}
