import React, { useState, useEffect, useRef } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm } from '@inertiajs/react';
import InputError from '@/Components/InputError';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import { format } from 'date-fns';

export default function Show({ auth, conversation, messages }) {
    const messagesEndRef = useRef(null);
    const { data, setData, post, processing, errors, reset } = useForm({
        body: '',
        conversation_id: conversation.id,
    });

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const sendMessage = (e) => {
        e.preventDefault();
        post(route('admin.messages.store'), {
            onSuccess: () => {
                reset('body');
                scrollToBottom();
            },
            preserveScroll: true,
        });
    };

    return (
        <AdminLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Conversation with {conversation.user.name} and {conversation.doctor.name}</h2>}
        >
            <Head title={`Conversation: ${conversation.subject || 'No Subject'}`} />

            <div className="py-12">
                <div className="max-w-3xl mx-auto sm:px-6 lg:px-8">
                    <div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <h3 className="text-lg font-medium text-gray-900 mb-4">Subject: {conversation.subject || 'No Subject'}</h3>

                            {/* Message List */}
                            <div className="h-96 overflow-y-auto border border-gray-200 rounded-lg p-4 mb-4">
                                {messages.map((message) => (
                                    <div
                                        key={message.id}
                                        className={`flex mb-4 ${
                                            message.sender_id === auth.user.id ? 'justify-end' : 'justify-start'
                                        }`}
                                    >
                                        <div
                                            className={`max-w-[70%] p-3 rounded-lg ${
                                                message.sender_id === auth.user.id
                                                    ? 'bg-indigo-500 text-white'
                                                    : 'bg-gray-200 text-gray-800'
                                            }`}
                                        >
                                            <p className="text-sm font-medium">{message.sender.name}</p>
                                            <p className="text-sm mt-1">{message.body}</p>
                                            <p className="text-xs text-right mt-1 opacity-75">
                                                {format(new Date(message.created_at), 'MMM d, yyyy h:mm a')}
                                            </p>
                                        </div>
                                    </div>
                                ))}
                                <div ref={messagesEndRef} />
                            </div>

                            {/* Message Input */}
                            <form onSubmit={sendMessage} className="flex items-center space-x-2">
                                <TextInput
                                    id="body"
                                    name="body"
                                    value={data.body}
                                    className="flex-1"
                                    onChange={(e) => setData('body', e.target.value)}
                                    placeholder="Type your message..."
                                />
                                <PrimaryButton disabled={processing}>Send</PrimaryButton>
                                <InputError message={errors.body} className="mt-2" />
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
