<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Ticket;
use App\Notifications\TicketCreated;
new class extends Component {
    use WithFileUploads;

    public $subject = '';
    public $priority = '';
    public $attachments = [];
    public $description = '';

    protected function rules()
    {
        return [
            'subject' => 'required|string|max:255',
            'priority' => 'required|in:low,medium,high',
            'attachments' => 'nullable|array|max:5',
            'attachments.*' => 'file|max:5120|mimes:jpg,jpeg,png,webp,pdf,doc,docx,xls,xlsx',
            'description' => 'required|string|min:10',
        ];
    }

    protected $messages = [
        'subject.required' => 'Please enter a subject for your ticket.',
        'priority.required' => 'Please select a priority level.',
        'attachments.max' => 'You can upload a maximum of 5 attachments.',
        'attachments.*.max' => 'Each attachment must not exceed 5MB.',
        'attachments.*.mimes' => 'Allowed file types: jpg, jpeg, png, webp, pdf, doc, docx, xls, xlsx.',
        'description.required' => 'Please enter a description for your ticket.',
    ];

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function updatedAttachments()
    {
        if (count($this->attachments) > 5) {
            $this->attachments = array_slice($this->attachments, 0, 5);
            $this->addError('attachments', 'You can upload a maximum of 5 attachments.');
        }
    }

    public function removeAttachment($index)
    {
        unset($this->attachments[$index]);
        $this->attachments = array_values($this->attachments); // reindex
    }

    public function submitTicket()
    {
        $this->validate();

        // Store all attachments and get paths
        $paths = [];
        foreach ($this->attachments as $file) {
            $paths[] = $file->store('tickets', 'public');
        }

        // Create the ticket
        $ticket = Ticket::create([
            'user_id' => auth()->id(),
            'subject' => $this->subject,
            'priority' => $this->priority,
            'status' => Ticket::STATUS_OPEN,
        ]);

        // Create the first message with description and attachments
        $ticket->messages()->create([
            'user_id' => auth()->id(),
            'message' => $this->description,
            'attachments' => $paths, // JSON cast will automatically convert array to JSON
            'is_admin' => false,
        ]);

        // Notify user via mail and database
        $ticket->user->notify(new TicketCreated($ticket));

        // Reset form
        $this->reset(['subject', 'priority', 'attachments', 'description']);
        $this->dispatch('notification-sent');
        $this->dispatch('showToast', message: 'Ticket submitted successfully.', type: 'success');
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || Create Support Ticket
</x-slot:title>

<div class="space-y-5 py-4 font-sans">
    <div class="flex items-center justify-between">
        <a href="{{ route('user.ticket.index') }}"
            class="bg-sky-600 text-white flex items-center hover:shadow-2xl justify-center gap-1 px-3 py-2 rounded-md">
            <x-flux::icon.arrow-left variant="solid" class="w-4 h-4" />
            <span class="text-sm font-medium">Back to Information</span>
        </a>

        <div class="flex justify-end mb-4 relative" x-data="{ open: false }">
            <!-- Dropdown Button -->
            <button @click="open = !open" type="button"
                class="inline-flex justify-center w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm font-medium text-gray-700 dark:text-gray-100 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-sky-500">
                {{ strtoupper(app()->getLocale()) }}
                <svg class="-mr-1 ml-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                </svg>
            </button>

            <!-- Dropdown Menu -->
            <div x-show="open" x-cloak @click.away="open = false"
                class="absolute right-0 mt-2 w-40 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg z-50">
                <ul class="py-1">
                    <li>
                        <a href="{{ route('locale.switch', 'en') }}"
                            class="flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <img src="/images/flags/us.svg" alt="English" class="w-4 h-4 mr-2">
                            English
                        </a>
                    </li>
                    <li>
                        <a href="{{ route('locale.switch', 'es') }}"
                            class="flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <img src="/images/flags/es.svg" alt="Español" class="w-4 h-4 mr-2">
                            Español
                        </a>
                    </li>
                    <li>
                        <a href="{{ route('locale.switch', 'fr') }}"
                            class="flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <img src="/images/flags/fr.svg" alt="Français" class="w-4 h-4 mr-2">
                            Français
                        </a>
                    </li>
                </ul>
            </div>
        </div>



    </div>

    <div class="bg-white dark:bg-gray-900 border border-gray-100 dark:border-gray-800 rounded-xl p-4 md:p-6 space-y-4">
        <h2 class="flex items-center gap-3 text-sm md:text-base font-semibold text-gray-800 dark:text-gray-100">
            <span
                class="bg-sky-500/10 dark:bg-sky-400/10 w-9 h-9 flex items-center justify-center rounded-full text-sky-600 dark:text-sky-400">
                <x-flux::icon.chat-bubble-left-ellipsis variant="solid" class="w-5 h-5" />
            </span>
            <div>
                <span> Support Center</span>
                <p class="text-xs text-gray-600 dark:text-gray-100">We're here to help. Tell us about your issue and
                    we'll find a solution.</p>
            </div>
        </h2>

        <form wire:transition wire:submit.prevent="submitTicket"
            class="space-y-6 p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm">

            {{-- Ticket Subject --}}
            <div>
                <x-input wire:model.live.blur="subject" label="{{ __('support.ticket_subject') }}"
                    placeholder="{{ __('support.ticket_subject_placeholder') }}" />
            </div>

            {{-- Priority Level --}}
            <div>
                <x-select wire:model.live.blur="priority" label="{{ __('support.priority_label') }}"
                    placeholder="{{ __('support.priority_placeholder') }}">
                    <option value="low">{{ __('support.priority_low') }}</option>
                    <option value="medium">{{ __('support.priority_medium') }}</option>
                    <option value="high">{{ __('support.priority_high') }}</option>
                </x-select>
            </div>

            {{-- Issue Description --}}
            <div>
                <x-textarea wire:model.live.blur="description" label="{{ __('support.description_label') }}"
                    placeholder="{{ __('support.description_placeholder') }}" rows="4" />
            </div>

            {{-- Attachment --}}
            <div>
                @include('partials.support-upload')
            </div>

            {{-- Support Information --}}
            <div class="bg-blue-50 dark:bg-blue-900/30 rounded-lg p-3 border border-blue-100 dark:border-blue-800">
                <div class="flex">
                    <div class="shrink-0">
                        <x-flux::icon.information-circle variant="solid"
                            class="w-4 h-4 text-blue-500 dark:text-blue-400 " />
                    </div>
                    <div class="ml-3">
                        <h3 class="text-xs font-medium text-blue-800 dark:text-blue-300">
                            {{ __('support.support_info_title') }}
                        </h3>
                        <p class="mt-1 text-xs text-blue-700 dark:text-blue-400">
                            {{ __('support.support_info_text') }}
                        </p>
                    </div>
                </div>
            </div>

            {{-- Submit Button --}}
            <div class="mt-6">
                <x-button type="submit" class="w-full">
                    {{ __('support.submit_ticket') }}
                </x-button>
            </div>

        </form>


        {{-- FAQ Section Accordion --}}
        <div class="mt-8 space-y-4" x-data="{ active: 0 }"> <!-- open first by default -->
            <h2 class="flex items-center gap-3 text-sm md:text-base font-semibold text-gray-800 dark:text-gray-100">
                <span
                    class="bg-sky-500/10 dark:bg-sky-400/10 w-9 h-9 flex items-center justify-center rounded-full text-sky-600 dark:text-sky-400">
                    <x-flux::icon.question-mark-circle variant="solid" class="w-5 h-5" />
                </span>
                <div>
                    <span> Support Center FAQs</span>
                    <p class="text-xs text-gray-600 dark:text-gray-100">Common questions about submitting tickets and
                        using
                        our support system.</p>
                </div>
            </h2>

            <div class="space-y-2">
                @php
                    $faqs = [
                        [
                            'question' => 'How long does it take to get a response?',
                            'answer' => 'Our support team typically responds within 24 hours on business days.',
                        ],
                        [
                            'question' => 'Can I attach multiple files?',
                            'answer' =>
                                'Yes, you can attach up to 5 files. Each file must be under 5MB and in allowed formats (jpg, png, pdf, doc, etc.).',
                        ],
                        [
                            'question' => 'Can I track the status of my ticket?',
                            'answer' =>
                                'Absolutely! Once submitted, you can view your ticket status in your support dashboard.',
                        ],
                        [
                            'question' => 'Can I update my ticket after submission?',
                            'answer' => 'Yes, you can reply to your ticket to add more information or attachments.',
                        ],
                        [
                            'question' => 'Who can view my tickets?',
                            'answer' => 'Only you and our support team can view the tickets you submit.',
                        ],
                        [
                            'question' => 'What should I do if I didn’t receive a response?',
                            'answer' =>
                                'Check your spam folder. If you still don’t see a reply, please submit a follow-up ticket.',
                        ],
                    ];
                @endphp

                @foreach ($faqs as $index => $faq)
                    <div class="border border-gray-200 dark:border-gray-700 rounded-lg">
                        <button @click="active === {{ $index }} ? active = null : active = {{ $index }}"
                            class="w-full flex justify-between items-center px-4 py-3 bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 text-left rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500">
                            <span class="text-sm font-medium text-gray-800 dark:text-gray-100">
                                {{ $faq['question'] }}
                            </span>
                            <svg :class="{ 'rotate-180': active === {{ $index }} }"
                                class="w-4 h-4 transition-transform duration-200" fill="none" stroke="currentColor"
                                viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>
                        <div x-show="active === {{ $index }}" x-collapse x-cloak
                            class=" text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700">
                            <div class="px-4 py-3">
                                {{ $faq['answer'] }}
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>


</div>
