'use client';

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

export default function ChatWindowModal({ conversation }) {
  const { socket } = useSocket();
  const user = useAuthStore((state) => state.user?.profile || null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const messagesEndRef = useRef(null);

  const consultationId = conversation.id;

  useEffect(() => {
    console.log('Conversation received in ChatWindowModal:', conversation);
  }, [conversation]);

  useEffect(() => {
    const fetchMessages = async () => {
      try {
        const res = await fetch(`/api/consultations/${consultationId}/messages`);
        if (!res.ok) throw new Error('Failed to fetch messages');
        const data = await res.json();
        setMessages(data);
      } catch (error) {
        console.error(error);
      }
    };

    fetchMessages();

    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]);

  const sendMessage = async () => {
    if (input.trim()) {
      const message = {
        consultationId,
        senderId: user.userId,
        content: input,
      };

      socket.emit('send-message', message);
      setInput('');
    }
  };

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

  const otherUser = conversation.patientId === user.userId
    ? conversation.doctor
    : conversation.patient;

  const fallback = {
    name: 'New Consultation',
    avatar: '/uploads/avatars/default-avatar.jpg',
  };

  const profile = otherUser?.doctorProfile || otherUser?.patientProfile || {};

  const name = otherUser
    ? `${otherUser.role === 'doctor' ? 'Dr. ' : ''}${profile.firstName || 'Unknown'} ${profile.lastName || ''}`.trim()
    : fallback.name;

  const avatar = otherUser
    ? profile.avatar || '/images/patient2.jpg'
    : fallback.avatar;

  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="flex flex-col flex-1 w-full h-[90vh] bg-white rounded-xl shadow-lg">
      <div className="flex items-center p-4 border-b bg-gray-50">
        <img
          width={58}
          height={58}
          src={avatar}
          alt={name}
          className="w-12 h-12 rounded-full"
        />
        <span className="ml-3 font-semibold text-lg">{name}</span>
      </div>

      <div className="flex-1 p-4 overflow-y-auto bg-gray-50">
        {messages.map((msg, idx) => {
          const isMe = msg.senderId === user.userId;
          const fileLinks = msg.files ? msg.files.split(',') : [];

          return (
            <div
              key={idx}
              className={`mb-4 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-blue-200 text-black'}`}
              >
                {/* Text content */}
                {msg.content && <div>{msg.content}</div>}

                {/* Files (images or links) */}
                {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 border cursor-pointer hover:opacity-80"
                              />
                            </a>
                          ) : (
                            <a
                              href={url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="underline text-blue-900 hover:text-blue-600"
                            >
                              {isPDF ? `📄 PDF File ${i + 1}` : `🔗 File ${i + 1}`}
                            </a>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}

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

      <div className="flex items-center p-4 border-t bg-white">
        <input
          type="text"
          className="flex-1 border rounded p-2"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
              e.preventDefault();
              sendMessage();
            }
          }}
          placeholder="Type a message..."
        />
        <button
          onClick={sendMessage}
          className="bg-blue-500 text-white px-4 py-2 rounded-full"
        >
          Send
        </button>
      </div>
    </div>
  );
}
