'use client';

import { useEffect, useState, useRef } from 'react';
import { useSocket } from '@/context/SocketContext';
import { useAuthStore } from '@/stores/authStore';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { MessageCircleOff } from 'lucide-react';

export default function ConsultationMessageModal({ consultation, currentDoctorId, onClose }) {
  const { socket } = useSocket();
  const user = useAuthStore((state) => state.user?.profile || null);
  const router = useRouter();

  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [assigned, setAssigned] = useState(!!consultation.doctorId);
  const messagesEndRef = useRef(null);

  const consultationId = consultation.id;
  const patient = consultation.patient?.patientProfile || {};

  useEffect(() => {
    setMessages(consultation.messages || []);
    setLoading(false);

    if (!socket) return;

    socket.emit('join-consultation', consultationId);

    const handleNewMessage = (msg) => {
      if (msg.consultationId === consultationId) {
        setMessages((prev) => [...prev, msg]);
      }
    };

    socket.on('new-message', handleNewMessage);

    return () => {
      socket.off('new-message', handleNewMessage);
    };
  }, [consultationId, socket, consultation.messages]);

  const sendMessage = async () => {
    if (!newMessage.trim()) return;

    let wasJustAssigned = false;

    if (!assigned) {
      try {
        const res = await fetch('/api/consultationassign', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            consultationId,
            doctorId: currentDoctorId,
          }),
        });

        if (!res.ok) throw new Error('Failed to assign doctor');
        setAssigned(true);
        wasJustAssigned = true;
      } catch (error) {
        console.error('Assign error:', error);
        return;
      }
    }

    const message = {
      consultationId,
      senderId: user.userId,
      recipientId: consultation.patientId,
      content: newMessage,
    };

    socket.emit('send-message', message);
    setNewMessage('');

    if (wasJustAssigned) {
      router.push('/dashboard/doctor/messages');
    }
  };

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const formatTime = (timestamp) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return new Intl.DateTimeFormat('default', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    }).format(date);
  };

  return (
    <div className="fixed inset-0 bg-white/30 backdrop-blur-sm flex items-center justify-center z-[9999] px-4">
      <div className="bg-white rounded-lg w-full max-w-xl p-4 relative">
        <button onClick={onClose} className="absolute top-2 right-2 text-gray-500 hover:text-black">✕</button>

        {/* Header */}
        <div className="flex items-center gap-3 mb-4">
          {patient.avatar && (
            <img
              src={patient.avatar}
              alt="Patient Avatar"
              width={50}
              height={50}
              className="rounded-full object-cover"
            />
          )}
          <div>
            <h3 className="text-lg font-bold">
              {patient.firstName} {patient.lastName}
            </h3>
            <p className="text-sm text-gray-500">{consultation.patient?.email}</p>
          </div>
        </div>

        {/* Messages Area */}
        <div className="h-64 overflow-y-auto border rounded p-2 mb-4 bg-gray-50">
          {loading ? (
            <p>Loading messages...</p>
          ) : messages.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-gray-500">
              <MessageCircleOff className="w-12 h-12 mb-3 opacity-50" />
              <p className="text-md font-semibold">No messages yet</p>
              <p className="text-sm text-gray-400 text-center px-2">
                When you start the conversation, messages will appear here.
              </p>
            </div>
          ) : (
            messages.map((msg, idx) => {
              const isMe = msg.senderId === user.userId;
              const fileLinks = msg.files ? msg.files.split(',') : [];

              return (
                <div
                  key={msg.id || idx}
                  className={`mb-2 flex ${isMe ? 'justify-end' : 'justify-start'}`}
                >
                  <div
                    className={`p-3 rounded-lg max-w-xs space-y-2 ${isMe ? 'bg-indigo-500 text-white' : 'bg-gray-200 text-black'}`}
                  >
                    {msg.content && (
                      <div>
                        {msg.content}
                      </div>
                    )}

                    {/* Display file links if any */}
                    {fileLinks.length > 0 && (
                      <div className="space-y-1">
                        {fileLinks.map((url, i) => {
                          const isImage = url.match(/\.(jpg|jpeg|png|gif|webp)$/i);
                          const isPDF = url.endsWith('.pdf');

                          return (
                            <div key={i} className="text-xs break-all">
                              {isImage ? (
                                <a href={url} target="_blank" rel="noopener noreferrer">
                                  <img
                                    src={url}
                                    alt={`Attachment ${i + 1}`}
                                    className="max-h-32 rounded cursor-pointer border border-white hover:opacity-80"
                                  />
                                </a>
                              ) : (
                                <a
                                  href={url}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="underline text-blue-200 hover:text-blue-100"
                                >
                                  {isPDF ? `📄 PDF File ${i + 1}` : `🔗 File ${i + 1}`}
                                </a>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    )}

                    <div className="text-[10px] mt-1 text-right text-gray-500">
                      {formatTime(msg.createdAt)}
                    </div>
                  </div>
                </div>
              );
            })
          )}
          <div ref={messagesEndRef} />
        </div>

        {/* Input Box */}
        <div className="flex items-center gap-2">
          <input
            type="text"
            className="flex-1 border rounded p-2"
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
            placeholder="Type your reply..."
          />
          <button
            onClick={sendMessage}
            className="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700"
          >
            Send
          </button>
        </div>
      </div>
    </div>
  );
}
