<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Concerns\HandlesWidgetCors;
use App\Http\Controllers\Controller;
use App\Models\Organization;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WidgetConfigController extends Controller
{
    use HandlesWidgetCors;

    public function show(Request $request): JsonResponse
    {
        $data = $request->validate([
            'widget_key' => ['required', 'string', 'max:80'],
        ]);

        $organization = Organization::query()
            ->where('widget_public_key', $data['widget_key'])
            ->where('widget_enabled', true)
            ->first();

        if ($organization === null) {
            return $this->jsonWithCors($request, response()->json([
                'message' => 'Widget is not available.',
            ], 404));
        }

        if (! $this->originAllowed($organization, $request->headers->get('origin'))) {
            return $this->jsonWithCors($request, response()->json([
                'message' => 'Origin is not allowed for this widget.',
            ], 403), $organization);
        }

        return $this->jsonWithCors($request, response()->json([
            'data' => [
                'appearance' => [
                    'title' => $organization->widget_title ?: 'VejalNai Support',
                    'subtitle' => $organization->widget_subtitle ?: 'Usually replies in a few minutes',
                    'statusMessage' => $organization->widget_status_message ?: 'We reply in Bangla, Banglish, or English.',
                    'greeting' => $organization->widget_greeting ?: 'Hi there. How can we help today?',
                    'launcherLabel' => $organization->widget_launcher_label ?: 'Chat',
                    'accentColor' => $organization->widget_accent_color ?: '#1976f3',
                    'headerStyle' => $organization->widget_header_style ?: 'gradient',
                    'headerColor' => $organization->widget_header_color ?: ($organization->widget_accent_color ?: '#1976f3'),
                    'headerGradientTo' => $organization->widget_header_gradient_to ?: '#0d54c7',
                    'headerTextColor' => $organization->widget_header_text_color ?: '#ffffff',
                    'statusBackgroundColor' => $organization->widget_status_background_color ?: '#2f7dcc',
                    'bodyBackgroundColor' => $organization->widget_body_background_color ?: '#f6f8fc',
                    'datePillBackgroundColor' => $organization->widget_date_pill_background_color ?: '#ffffff',
                    'datePillTextColor' => $organization->widget_date_pill_text_color ?: '#728197',
                    'botMessageBackgroundColor' => $organization->widget_bot_message_background_color ?: '#ffffff',
                    'botMessageTextColor' => $organization->widget_bot_message_text_color ?: '#22314a',
                    'quickReplyBackgroundColor' => $organization->widget_quick_reply_background_color ?: '#ffffff',
                    'quickReplyTextColor' => $organization->widget_quick_reply_text_color ?: '#22314a',
                    'composerBackgroundColor' => $organization->widget_composer_background_color ?: '#ffffff',
                    'inputBackgroundColor' => $organization->widget_input_background_color ?: '#ffffff',
                    'sendButtonColor' => $organization->widget_send_button_color ?: ($organization->widget_accent_color ?: '#1976f3'),
                    'logoUrl' => $organization->widget_logo_url,
                    'quickReplies' => $this->quickReplies($organization),
                    'position' => $organization->widget_position ?: 'bottom-right',
                    'size' => $organization->widget_size ?? 100,
                    'showPoweredBy' => $organization->widget_powered_by_branding,
                    'showClearHistory' => $organization->widget_show_clear_history ?? true,
                    'showCloseButton' => $organization->widget_show_close_button ?? true,
                ],
            ],
        ]), $organization);
    }

    public function options(Request $request): JsonResponse
    {
        return $this->jsonWithCors($request, response()->json(null, 204));
    }

    /**
     * @return list<string>
     */
    private function quickReplies(Organization $organization): array
    {
        $quickReplies = collect(preg_split('/\r\n|\r|\n/', (string) $organization->widget_quick_replies))
            ->map(fn (string $value) => trim($value))
            ->filter()
            ->take(4)
            ->values()
            ->all();

        return $quickReplies ?: ['Delivery charge koto?', 'Order status', 'Talk to human'];
    }
}
