"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 ChatWindow({ conversation, goBack }) {
  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(() => {
    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);
        console.log('Messages:', 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: 'General Consultation',
    avatar: '/images/patient2.jpg',
  };

  const profile = otherUser?.role === 'doctor'
    ? 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">
      {/* Header */}
      <div className="flex items-center p-4 border-b bg-gray-50">
        <button onClick={goBack} className="mr-4 text-lg">←</button>
        <img
          width={48}
          height={48}
          src={avatar ? avatar : '/images/patient2.jpg'}
          alt={name || 'Profile avatar'}
          className="w-12 h-12 rounded-full object-cover"
        />
        <span className="ml-3 font-semibold">{name}</span>
      </div>

      {/* Messages */}
      <div className="flex-1 p-4 overflow-y-auto bg-gray-100">
        {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={`max-w-xs md:max-w-sm p-3 rounded-lg shadow-sm space-y-2 ${isMe ? 'bg-indigo-500 text-white' : 'bg-gray-400 text-black'}`}
              >
                {/* Text content */}
                {msg.content && (
                  <p className="whitespace-pre-wrap break-words">{msg.content}</p>
                )}

                {/* File previews */}
                {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-words">
                          {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-100 hover:text-blue-200"
                            >
                              {isPDF ? `📄 PDF File ${i + 1}` : `🔗 File ${i + 1}`}
                            </a>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}

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

      {/* Input Box */}
      <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 hover:bg-blue-600 transition"
        >
          Send
        </button>
      </div>
    </div>
  );
}
