<?php

namespace App\Http\Controllers\Api\V1\Cms\Admin;

use App\Http\Controllers\Controller;
use App\Models\ReceivedDocument;
use App\Services\DocumentReceptionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LegislationController extends Controller
{
    public function __construct(
        protected DocumentReceptionService $documentService
    ) {
    }

    /**
     * Get a list of all legislation documents.
     */
    public function index(Request $request): JsonResponse
    {
        $query = ReceivedDocument::with('chunks');

        // Apply search filter
        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhere('original_filename', 'like', "%{$search}%");
            });
        }

        // Apply status filter
        if ($status = $request->get('status')) {
            $query->where('status', $status);
        }

        // Apply jurisdiction filter
        if ($jurisdiction = $request->get('jurisdiction')) {
            $query->whereJsonContains('jurisdictions', ['code' => $jurisdiction]);
        }

        // Apply category filter
        if ($category = $request->get('category')) {
            $query->whereJsonContains('doc_categories', ['code' => $category]);
        }

        // Apply sorting
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        // Paginate
        $perPage = $request->get('per_page', 15);
        $documents = $query->paginate($perPage);

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

    /**
     * Get a single legislation document with all chunks.
     */
    public function show(ReceivedDocument $legislation): JsonResponse
    {
        $legislation->load('chunks');

        return response()->json([
            'document' => $legislation,
        ]);
    }

    /**
     * Update a legislation document and optionally sync with Python app.
     */
    public function update(Request $request, ReceivedDocument $legislation): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'sometimes|string|max:500',
            'markdown_content' => 'sometimes|nullable|string',
            'html_content' => 'sometimes|nullable|string',
            'notes' => 'sometimes|nullable|string',
            'sync' => 'sometimes|boolean',
            'chunks' => 'sometimes|array',
            'chunks.*.id' => 'required|integer|exists:received_document_chunks,id',
            'chunks.*.title' => 'sometimes|nullable|string|max:500',
            'chunks.*.content' => 'sometimes|string',
            'chunks.*.markdown_content' => 'sometimes|string',
            'chunks.*.html_content' => 'sometimes|nullable|string',
        ]);

        $shouldSync = $validated['sync'] ?? true;
        unset($validated['sync']);

        if ($shouldSync) {
            $result = $this->documentService->updateAndSync($legislation, $validated);
        } else {
            // Update locally only
            $legislation->update([
                'title' => $validated['title'] ?? $legislation->title,
                'markdown_content' => $validated['markdown_content'] ?? $legislation->markdown_content,
                'html_content' => $validated['html_content'] ?? $legislation->html_content,
                'notes' => $validated['notes'] ?? $legislation->notes,
                'status' => 'modified',
            ]);

            // Update chunks if provided
            if (!empty($validated['chunks'])) {
                foreach ($validated['chunks'] as $chunkData) {
                    $chunk = $legislation->chunks()->where('id', $chunkData['id'])->first();
                    if ($chunk) {
                        $chunk->update([
                            'title' => $chunkData['title'] ?? $chunk->title,
                            'content' => $chunkData['content'] ?? $chunk->content,
                            'markdown_content' => $chunkData['markdown_content'] ?? $chunk->markdown_content,
                            'html_content' => $chunkData['html_content'] ?? $chunk->html_content,
                        ]);
                    }
                }
            }

            $result = [
                'success' => true,
                'document' => $legislation->fresh()->load('chunks'),
                'sync_status' => 'not_synced',
            ];
        }

        if ($result['success']) {
            return response()->json([
                'message' => 'Legislation updated successfully',
                'document' => $result['document'],
                'sync_status' => $result['sync_status'] ?? 'synced',
            ]);
        }

        return response()->json([
            'message' => $result['message'],
            'error_code' => $result['error_code'] ?? 'UPDATE_ERROR',
        ], 500);
    }

    /**
     * Force sync a document with Python application.
     */
    public function sync(ReceivedDocument $legislation): JsonResponse
    {
        $result = $this->documentService->updateAndSync($legislation, []);

        if ($result['success']) {
            return response()->json([
                'message' => 'Legislation synced successfully',
                'document' => $result['document'],
                'sync_status' => $result['sync_status'],
            ]);
        }

        return response()->json([
            'message' => $result['message'],
            'error_code' => $result['error_code'] ?? 'SYNC_ERROR',
        ], 500);
    }

    /**
     * Delete a legislation document.
     */
    public function destroy(ReceivedDocument $legislation): JsonResponse
    {
        $legislation->delete();

        return response()->json([
            'message' => 'Legislation deleted successfully',
        ]);
    }

    /**
     * Get document statistics.
     */
    public function stats(): JsonResponse
    {
        $stats = [
            'total' => ReceivedDocument::count(),
            'received' => ReceivedDocument::where('status', 'received')->count(),
            'modified' => ReceivedDocument::where('status', 'modified')->count(),
            'synced' => ReceivedDocument::where('status', 'synced')->count(),
            'updated' => ReceivedDocument::where('status', 'updated')->count(),
        ];

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

    /**
     * Get unique values for filters (jurisdictions, categories, etc.).
     */
    public function filters(): JsonResponse
    {
        $documents = ReceivedDocument::select('jurisdictions', 'doc_categories', 'law_subjects', 'pathways')->get();

        $jurisdictions = collect();
        $categories = collect();
        $subjects = collect();
        $pathways = collect();

        foreach ($documents as $doc) {
            if ($doc->jurisdictions) {
                $jurisdictions = $jurisdictions->merge($doc->jurisdictions);
            }
            if ($doc->doc_categories) {
                $categories = $categories->merge($doc->doc_categories);
            }
            if ($doc->law_subjects) {
                $subjects = $subjects->merge($doc->law_subjects);
            }
            if ($doc->pathways) {
                $pathways = $pathways->merge($doc->pathways);
            }
        }

        return response()->json([
            'jurisdictions' => $jurisdictions->unique('code')->values(),
            'categories' => $categories->unique('code')->values(),
            'subjects' => $subjects->unique('code')->values(),
            'pathways' => $pathways->unique('code')->values(),
            'statuses' => ['received', 'modified', 'synced', 'updated'],
        ]);
    }
}
