<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AiTrainingItemDestroyRequest;
use App\Http\Requests\Admin\AiTrainingItemStoreRequest;
use App\Http\Requests\Admin\AiTrainingItemUpdateRequest;
use App\Models\AiTrainingDataset;
use App\Models\AiTrainingItem;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AiTrainingItemController extends Controller
{
    use LogsAdminActivity;

    /**
     * Get training item records for DataTables within a dataset.
     */
    public function records(Request $request, AiTrainingDataset $dataset): JsonResponse
    {
        $query = AiTrainingItem::where('dataset_id', $dataset->id);

        // Total count before filtering
        $totalRecords = $query->count();

        // Search
        if ($request->filled('search.value')) {
            $searchValue = $request->input('search.value');
            $query->where(function ($q) use ($searchValue) {
                $q->where('user_message', 'like', "%{$searchValue}%")
                    ->orWhere('assistant_message', 'like', "%{$searchValue}%")
                    ->orWhere('source', 'like', "%{$searchValue}%");
            });
        }

        $filteredRecords = $query->count();

        // Ordering
        $orderColumn = 'id';
        $orderDir = 'desc';

        if ($request->has('order') && isset($request->input('order')[0])) {
            $order = $request->input('order')[0];
            $columns = ['id', 'user_message', 'assistant_message', 'source', 'approved', 'created_at'];

            $colIndex = $order['column'] ?? 0;
            if (isset($columns[$colIndex]) && $columns[$colIndex] !== null) {
                $orderColumn = $columns[$colIndex];
                $orderDir = $order['dir'] ?? 'desc';
            }
        }

        $query->orderBy($orderColumn, $orderDir);

        // Pagination
        $start = $request->input('start', 0);
        $length = $request->input('length', 10);

        $items = $query->skip($start)->take($length)->get();

        $data = [];
        foreach ($items as $item) {
            $data[] = [
                'id' => $item->id,
                'system_message' => $item->system_message,
                'user_message' => $item->user_message,
                'assistant_message' => $item->assistant_message,
                'source' => $item->source,
                'source_id' => $item->source_id,
                'approved' => $item->approved,
                'created_at' => $item->created_at->format('d.m.Y H:i'),
            ];
        }

        return response()->json([
            'draw' => (int) $request->input('draw'),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'data' => $data,
        ]);
    }

    /**
     * Store a newly created training item.
     */
    public function store(AiTrainingItemStoreRequest $request): JsonResponse
    {
        $validated = $request->validated();

        $item = AiTrainingItem::create([
            'dataset_id' => $validated['dataset_id'],
            'system_message' => $validated['system_message'] ?? null,
            'user_message' => $validated['user_message'],
            'assistant_message' => $validated['assistant_message'],
            'source' => $validated['source'] ?? 'manual',
            'approved' => $validated['approved'] ?? false,
        ]);

        $this->logCreated($item, "Created AI Training Item #{$item->id}");

        // Update dataset item count
        $item->dataset->updateItemCount();

        return response()->json([
            'success' => true,
            'data' => $item,
            'message' => __('admin/ai-staff.messages_item_created'),
        ]);
    }

    /**
     * Update the specified training item.
     */
    public function update(AiTrainingItemUpdateRequest $request, AiTrainingItem $item): JsonResponse
    {
        $validated = $request->validated();

        $item->update([
            'system_message' => $validated['system_message'] ?? $item->system_message,
            'user_message' => $validated['user_message'] ?? $item->user_message,
            'assistant_message' => $validated['assistant_message'] ?? $item->assistant_message,
            'approved' => $validated['approved'] ?? $item->approved,
        ]);

        $this->logUpdated($item, "Updated AI Training Item #{$item->id}");

        // Update dataset item count if approval changed
        if (isset($validated['approved'])) {
            $item->dataset->updateItemCount();
        }

        return response()->json([
            'success' => true,
            'data' => $item,
            'message' => __('admin/ai-staff.messages_item_updated'),
        ]);
    }

    /**
     * Remove the specified training item.
     */
    public function destroy(AiTrainingItemDestroyRequest $request, AiTrainingItem $item): JsonResponse
    {
        $dataset = $item->dataset;

        $this->logDeleted($item, "Deleted AI Training Item #{$item->id}");

        $item->delete();

        // Update dataset item count
        $dataset->updateItemCount();

        return response()->json([
            'success' => true,
            'message' => __('admin/ai-staff.messages_item_deleted'),
        ]);
    }
}
