<script setup lang="ts">
import { ref } from 'vue';
import { useForm } from '@inertiajs/vue3';
import { useEcho, echoIsConfigured, configureEcho } from '@laravel/echo-vue';
import { route } from 'ziggy-js';
import { Paperclip, Info } from '@lucide/vue';

const props = defineProps<{
    chat: {
        id: number;
        messages: Array<{
            id: number;
            user: { name: string };
            content: string;
            created_at: string;
            media?: Array<{
                id: number;
                url: string;
                file_name: string;
                mime_type: string;
            }>;
        }>;
    };
}>();

if (!echoIsConfigured()) {
    configureEcho({
        broadcaster: 'reverb',
        key: import.meta.env.VITE_REVERB_APP_KEY || 'mock-key',
        wsHost: import.meta.env.VITE_REVERB_HOST || 'localhost',
        wsPort: import.meta.env.VITE_REVERB_PORT
            ? Number(import.meta.env.VITE_REVERB_PORT)
            : 8080,
        wssPort: import.meta.env.VITE_REVERB_PORT
            ? Number(import.meta.env.VITE_REVERB_PORT)
            : 8080,
        forceTLS: false,
        enabledTransports: ['ws', 'wss'],
    });
}

const fileInput = ref<HTMLInputElement | null>(null);

const form = useForm({
    content: '',
    media: [] as File[],
});

useEcho(`chats.${props.chat.id}`, 'MessageSent', (e: any) => {
    props.chat.messages.push(e.message);
});

function handleFileChange(event: Event) {
    const files = (event.target as HTMLInputElement).files;
    if (files) {
        for (let i = 0; i < files.length; i++) {
            form.media.push(files[i]);
        }
    }
}

function removeFile(index: number) {
    form.media.splice(index, 1);
}

function submit() {
    form.post(route('chats.messages.store', props.chat.id), {
        onSuccess: () => {
            form.reset();
            if (fileInput.value) {
                fileInput.value.value = '';
            }
        },
    });
}

// Lightbox Modal state
const activeLightboxUrl = ref<string | null>(null);
const activeLightboxType = ref<'image' | 'video' | null>(null);

function openLightbox(url: string, mimeType: string) {
    activeLightboxUrl.value = url;
    activeLightboxType.value = mimeType.startsWith('image/')
        ? 'image'
        : 'video';
}

function closeLightbox() {
    activeLightboxUrl.value = null;
    activeLightboxType.value = null;
}
</script>

<template>
    <div class="c-chat">
        <h4 class="c-chat__title">Chat</h4>
        <div class="c-chat__list">
            <div
                v-for="message in chat.messages"
                :key="message.id"
                :class="[
                    'c-chat__message',
                    {
                        'c-chat__message--system':
                            message.content.startsWith('System:'),
                    },
                ]"
            >
                <!-- Standard User Chat Message -->
                <template v-if="!message.content.startsWith('System:')">
                    <div class="c-chat__message-header">
                        <span class="c-chat__message-author">{{
                            message.user.name
                        }}</span>
                        <span class="c-chat__message-time">{{
                            new Date(message.created_at).toLocaleString()
                        }}</span>
                    </div>
                    <p class="c-chat__message-text">
                        {{ message.content }}
                    </p>

                    <!-- Attached Media Display -->
                    <div
                        v-if="message.media && message.media.length > 0"
                        class="c-chat__message-media"
                    >
                        <div
                            v-for="item in message.media"
                            :key="item.id"
                            class="c-chat__media-item"
                        >
                            <img
                                v-if="item.mime_type.startsWith('image/')"
                                :src="item.url"
                                :alt="item.file_name"
                                class="c-chat__image cursor-pointer transition-opacity hover:opacity-90"
                                @click="openLightbox(item.url, item.mime_type)"
                            />
                            <div
                                v-else-if="item.mime_type.startsWith('video/')"
                                class="relative cursor-pointer transition-opacity hover:opacity-90"
                                @click="openLightbox(item.url, item.mime_type)"
                            >
                                <video
                                    :src="item.url"
                                    class="c-chat__video"
                                ></video>
                                <div class="c-chat__play-overlay">▶</div>
                            </div>
                        </div>
                    </div>
                </template>

                <!-- Subtle Activity Log System Message -->
                <template v-else>
                    <div class="c-chat__system-inner">
                        <Info class="c-chat__system-icon" />
                        <span class="c-chat__system-text">
                            {{ message.content.replace(/^System:\s*/, '') }}
                        </span>
                        <span class="c-chat__system-time">
                            {{
                                new Date(message.created_at).toLocaleTimeString(
                                    [],
                                    { hour: '2-digit', minute: '2-digit' },
                                )
                            }}
                        </span>
                    </div>
                </template>
            </div>
            <div v-if="chat.messages.length === 0" class="c-chat__empty">
                No messages yet.
            </div>
        </div>
        <form @submit.prevent="submit" class="c-chat__form">
            <div class="c-chat__form-group">
                <label for="content" class="c-chat__label">Message</label>
                <textarea
                    v-model="form.content"
                    id="content"
                    rows="3"
                    class="c-chat__textarea"
                    placeholder="Type a message..."
                ></textarea>
                <div v-if="form.errors.content" class="c-chat__error">
                    {{ form.errors.content }}
                </div>

                <!-- Attachment Button & Hidden Input -->
                <div class="c-chat__attachment-container">
                    <button
                        type="button"
                        @click="fileInput?.click()"
                        class="c-chat__attach-btn"
                    >
                        <Paperclip class="c-chat__attach-icon" />
                        Attach Photos/Videos
                    </button>
                    <input
                        ref="fileInput"
                        type="file"
                        multiple
                        accept="image/*,video/*"
                        class="hidden"
                        @change="handleFileChange"
                    />
                </div>

                <!-- Previews List -->
                <div v-if="form.media.length > 0" class="c-chat__preview-list">
                    <div
                        v-for="(file, index) in form.media"
                        :key="index"
                        class="c-chat__preview-item"
                    >
                        <span class="c-chat__preview-name">{{
                            file.name
                        }}</span>
                        <button
                            type="button"
                            @click="removeFile(index)"
                            class="c-chat__preview-remove"
                        >
                            ✕
                        </button>
                    </div>
                </div>
            </div>
            <div class="c-chat__submit-box">
                <button
                    type="submit"
                    :disabled="form.processing"
                    class="c-chat__button"
                >
                    Send
                </button>
            </div>
        </form>

        <!-- Gorgeous Dark Lightbox Modal -->
        <div
            v-if="activeLightboxUrl"
            class="c-chat__lightbox"
            @click="closeLightbox"
        >
            <button @click="closeLightbox" class="c-chat__lightbox-close">
                ✕
            </button>
            <div class="c-chat__lightbox-content" @click.stop>
                <img
                    v-if="activeLightboxType === 'image'"
                    :src="activeLightboxUrl"
                    class="c-chat__lightbox-image"
                />
                <video
                    v-else-if="activeLightboxType === 'video'"
                    :src="activeLightboxUrl"
                    controls
                    autoplay
                    class="c-chat__lightbox-video"
                ></video>
            </div>
        </div>
    </div>
</template>

<style scoped>
@reference "../../css/app.css";

.c-chat {
    @apply mt-8;
}

.c-chat__title {
    @apply text-lg font-medium text-gray-900 dark:text-gray-100;
}

.c-chat__list {
    @apply mt-4 space-y-4;
}

.c-chat__message {
    @apply overflow-hidden bg-white p-4 shadow-sm sm:rounded-lg dark:bg-gray-800;
}

.c-chat__message--system {
    @apply border-0 bg-transparent p-0 shadow-none;
}

.c-chat__system-inner {
    @apply flex items-center gap-2 rounded-md border border-neutral-200/60 bg-neutral-50 px-3 py-1.5 text-xs text-neutral-500 dark:border-neutral-800/40 dark:bg-neutral-900/10 dark:text-neutral-400;
}

.c-chat__system-icon {
    @apply size-3.5 shrink-0 text-neutral-400;
}

.c-chat__system-text {
    @apply flex-1 font-medium;
}

.c-chat__system-time {
    @apply shrink-0 text-[10px] text-neutral-400;
}

.c-chat__message-header {
    @apply flex justify-between;
}

.c-chat__message-author {
    @apply font-semibold;
}

.c-chat__message-time {
    @apply text-xs text-gray-500;
}

.c-chat__message-text {
    @apply mt-2 text-sm text-gray-600 dark:text-gray-400;
}

.c-chat__message-media {
    @apply mt-3 flex flex-wrap gap-2;
}

.c-chat__media-item {
    @apply relative max-w-[240px] overflow-hidden rounded-md border border-neutral-200 bg-black dark:border-neutral-700;
}

.c-chat__image {
    @apply h-auto max-h-[180px] w-full object-cover;
}

.c-chat__video {
    @apply h-auto max-h-[180px] w-full;
}

.c-chat__play-overlay {
    @apply absolute inset-0 flex items-center justify-center bg-black/40 text-2xl font-bold text-white;
}

.c-chat__empty {
    @apply text-gray-500;
}

.c-chat__form {
    @apply mt-6 space-y-6;
}

.c-chat__form-group {
    @apply space-y-2;
}

.c-chat__label {
    @apply block text-sm font-medium text-gray-700 dark:text-gray-300;
}

.c-chat__textarea {
    @apply mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:focus:border-indigo-600 dark:focus:ring-indigo-600;
}

.c-chat__error {
    @apply text-sm text-red-600;
}

.c-chat__attachment-container {
    @apply mt-2 flex items-center;
}

.c-chat__attach-btn {
    @apply inline-flex cursor-pointer items-center gap-1.5 text-xs text-neutral-500 transition-colors hover:text-foreground;
}

.c-chat__attach-icon {
    @apply size-3.5;
}

.c-chat__preview-list {
    @apply mt-2 flex flex-wrap gap-2;
}

.c-chat__preview-item {
    @apply relative inline-flex items-center gap-2 rounded border border-neutral-200 bg-neutral-100 p-1.5 pr-8 text-xs dark:border-neutral-700 dark:bg-neutral-800;
}

.c-chat__preview-name {
    @apply max-w-[150px] truncate;
}

.c-chat__preview-remove {
    @apply absolute top-1.5 right-1.5 cursor-pointer text-[10px] text-neutral-400 hover:text-red-500;
}

.c-chat__submit-box {
    @apply flex items-center gap-4;
}

.c-chat__button {
    @apply inline-flex items-center rounded-md border border-transparent bg-gray-800 px-4 py-2 text-xs font-semibold tracking-widest text-white uppercase transition duration-150 ease-in-out hover:bg-gray-700 focus:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-none active:bg-gray-900 dark:bg-gray-200 dark:text-gray-800 dark:hover:bg-white dark:focus:bg-white dark:focus:ring-offset-gray-800 dark:active:bg-gray-300;
}

/* Lightbox Styling */
.c-chat__lightbox {
    @apply fixed inset-0 z-50 flex items-center justify-center bg-black/95 p-4;
}

.c-chat__lightbox-close {
    @apply absolute top-6 right-6 cursor-pointer text-3xl text-white transition-colors duration-200 hover:text-red-500;
}

.c-chat__lightbox-content {
    @apply max-h-full max-w-full;
}

.c-chat__lightbox-image {
    @apply max-h-[90vh] max-w-full rounded object-contain shadow-lg;
}

.c-chat__lightbox-video {
    @apply max-h-[90vh] max-w-full rounded shadow-lg;
}
</style>
