/* eslint-disable -- temporary disable for development/testing purposes */

'use client';

import React, { useEffect, useState, useRef,useContext } from 'react';
import { io, Socket } from 'socket.io-client';
import { Stack, Typography, Button, Paper, Box,InputAdornment,  IconButton,TextField, } from '@mui/material';
import SendIcon from '@mui/icons-material/Send';
 
import { UserContext } from '@/contexts/user-context';
// import SendIcon from '@mui/icons-material/Send';
import AttachFileIcon from '@mui/icons-material/AttachFile';
import Avatar from '@mui/material/Avatar';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
 
interface Message {
  chatId: string;
  timestamp: string;
  sender_id: string;
//   senderName: string;
  file_path?: string | null;
  // message: string;
  message: string | null; 
}

interface ChatRoomProps {
  chatId: string | null;
  router: any;
  receiverId: string | null;
  role: string | null;
  receiverName: string | null;
  receiverAvatar?: string;
}

export default function ChatRoom({ chatId, router, receiverId,role,receiverName, receiverAvatar,}: ChatRoomProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const socketRef = useRef<Socket | null>(null);
  const { user: loggedInUser } = useContext(UserContext) ?? {};
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const messagesEndRef = useRef<HTMLDivElement | null>(null);
  const messagesContainerRef = useRef<HTMLDivElement | null>(null);


 

  // Extract from router query
//   const { chat, receiver_id, role } = router.query;

  // Replace with actual logged-in user ID & company ID from your app state
  const currentUserId = loggedInUser?.id;

  const activeCompany = loggedInUser?.companies?.find(company => company.active);
  const companyId = activeCompany?.id;

  useEffect(() => {
    socketRef.current = io('https://gohelloprovider.com/chat', {
      path: '/socket.io',
      transports: ['websocket'],
      timeout: 10000,
    });

    socketRef.current.on('connect', () => console.log('✅ Connected (Web)'));

    socketRef.current.on('message', (data: Message) => {
      setMessages((prev) => [...prev, data]);
    });

    return () => {
      socketRef.current?.disconnect();
    };
  }, []);

  useEffect(() => {
    if (!chatId) return;

    fetch(`https://gohelloprovider.com/chat/messages?chat_id=${chatId}`)
      .then((res) => res.json())
      .then((data: Message[]) => {
        setMessages(data.reverse());
      })
      .catch((error) => console.error('❌ Fetch Error:', error));
  }, [chatId]);

  const formatTimestampForMySQL = (isoString: string) => {
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

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

    const isoTimestamp = new Date().toISOString();
    const mysqlFormattedTimestamp = formatTimestampForMySQL(isoTimestamp);
    const safeReceiverId = receiverId ?? undefined; // converts null to undefined

    const messageData: Message & {
      receiverId?: string | string[];
      chat_with?: any;
      company_id?: number;
    } = {
      chatId: chatId || '',


      message: newMessage.trim(),
      timestamp: mysqlFormattedTimestamp,
      sender_id: currentUserId ? currentUserId : '',

    //   senderName: 'You',
      file_path: null,
      receiverId: safeReceiverId,
      chat_with: role,
      company_id: companyId,
    };
    // console.log("Sending messageData:", messageData);

    // Emit the message through socket
    socketRef.current.emit('message', messageData);

    try {
      // Send message to backend API
      const response = await fetch('https://gohelloprovider.com/chat/send-message', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(messageData),
      });

      const responseJson = await response.json();
      // console.log('✅ Server Response:', responseJson);

      // Optionally update chatId if needed (if you handle creating new chats)
      if (!chatId && responseJson.chatId) {
        // setChatId(responseJson.chatId); // Uncomment if you have setChatId in scope
      }

      // Update messages list and clear input
      setMessages((prev) => [...prev, messageData]);
      setNewMessage('');
    } catch (error) {
      // console.error('❌ Send Message Error:', error);
    }
  };

  const handleAttachClick = () => {
    fileInputRef.current?.click();
  };

  const sendImageMessage = async (file: File) => {
    if (!file) return;
  
    const formatTimestampForMySQL = (isoString: string) => {
      const date = new Date(isoString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
  
    const isoTimestamp = new Date().toISOString();
    const mysqlFormattedTimestamp = formatTimestampForMySQL(isoTimestamp);
  
    // Prepare form data like in React Native
    const formData = new FormData();
    formData.append('image', file);  // key must be 'image' to match multer backend
  
    // Append your other fields here:
    formData.append('sender_id', currentUserId || ''); // replace with your user id state or prop
    formData.append('receiverId', receiverId || '');   // replace with your receiver id state or prop
    formData.append('company_id', companyId?.toString() || ''); // replace with your company id (string)
    formData.append('chat_with', role || '');          // your role variable
    formData.append('timestamp', mysqlFormattedTimestamp);
  
    // Append chatId - pass string 'null' if no chatId exists (to mimic your React Native logic)
    if (chatId && chatId !== 'null') {
      formData.append('chatId', chatId);
    } else {
      formData.append('chatId', 'null');
    }
  
    try {
      const response = await fetch('https://gohelloprovider.com/chat/upload', {
        method: 'POST',
        body: formData,
        // Note: DO NOT set Content-Type header here! Let browser set it with boundary.
      });
  
      if (!response.ok) {
        // console.error('❌ Upload failed');
        return;
      }
  
      const data = await response.json();
      // console.log('✅ Image Uploaded:', data);
  
      if (data.file_path) {
        // Emit socket message if you have socket in scope
        socketRef.current?.emit('message', {
          file_path: data.file_path,
          sender_id: currentUserId || '',
          receiverId: receiverId || '',
          chatId: data.chatId || chatId || null,
          message: null,
          timestamp: mysqlFormattedTimestamp,
          chat_with: role,
          company_id: companyId,
        });
  
        // Update local messages state if you have it
        setMessages((prev) => [
          ...prev,
          {
            message: null,
            sender_id: currentUserId || '',
            receiverId: receiverId || '',
            chatId: data.chatId || chatId || null,
            timestamp: mysqlFormattedTimestamp,
            file_path: data.file_path,
            chat_with: role,
            company_id: companyId,
          },
        ]);
      }
    } catch (error) {
      // console.error('❌ Error Uploading Image:', error);
    }
  };

  useEffect(() => {
    if (messagesEndRef.current && messagesContainerRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
    }
  }, [messages]);
  
  
  return (
    <Stack spacing={3} sx={{ height: '100%', p: 3 }}>
  
      {/* Header with receiver image & name */}
      <Stack direction="row" alignItems="center" spacing={2} mb={2}>
        <Avatar
          src={receiverAvatar || undefined}
          alt={receiverName || 'User'}
          sx={{ width: 48, height: 48 }}
        />
        <Typography variant="h5" fontWeight="medium">
          {receiverName || 'Unknown User'}
        </Typography>
      </Stack>

      {/* The rest of your chatroom UI */}
      {/* Messages list and message input */}
      {/* ...existing code here... */}
 

      <Paper
        variant="outlined"
        sx={{
          flexGrow: 1,
          overflowY: 'auto',
          p: 2,
          maxHeight: '60vh',
          bgcolor: 'background.paper',
          scrollbarWidth: 'none',
          msOverflowStyle: 'none',
        }}
        ref={messagesContainerRef}
      >
        {messages.map((msg, index) => {
          const isSender = msg.sender_id === currentUserId;
          const filePath = msg.file_path;
          const fileExtension = filePath?.split('.').pop()?.toLowerCase();
          const isImage =
            filePath && ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension || '');
          const isPDF = filePath && fileExtension === 'pdf';
          const formatted = msg.timestamp.replace('T', ' ').replace('.000Z', '');
          // const filePath = msg.file_path;

          // console.log(formatted,'formatted')
          const formattedTime = formatted
          ? new Date(formatted).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
          : '';
          return (
            <Box
              key={index}
              mb={2}
              display="flex"
              flexDirection="column"
              alignItems={isSender ? 'flex-end' : 'flex-start'}
            >
             <Paper
  sx={{
    p: isImage ? 0.75 : 1.5, // Reduce padding if image is present
    maxWidth: '75%',
    bgcolor: isSender ? '#DCF8C6' : '#F0F0F0',
    borderTopLeftRadius: isSender ? 16 : 0,
    borderTopRightRadius: isSender ? 0 : 16,
    borderBottomLeftRadius: 16,
    borderBottomRightRadius: 16,
  }}
>
                {/* Message Text */}
                {msg.message && (
                  <Typography variant="body1" mb={filePath ? 1 : 0}>
                    {msg.message}
                  </Typography>
                )}

                {/* Image Rendering */}
                {isImage && (
  <Box sx={{ position: 'relative', width: 180, height: 180, borderRadius: 1, overflow: 'hidden' }}>
  <img
    src={`https://gohelloprovider.com/chat${filePath}`}
    alt="Sent image"
    style={{
      width: '100%',
      height: '100%',
      objectFit: 'cover',
      borderRadius: 8,
    }}
  />

  {/* Absolute Timestamp Overlay */}
  <Box
    sx={{
      position: 'absolute',
      bottom: 4,
      right: 4,
      bgcolor: 'rgba(0, 0, 0, 0.6)',
      color: 'white',
      fontSize: '10px',
      px: 0.5,
      py: 0.25,
      borderRadius: 0.5,
    }}
  >
     {formattedTime}
  </Box>
</Box>
  )}

                {/* PDF Link Rendering */}
                {isPDF && (
  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, position: 'relative' }}>
    {/* PDF Icon */}
    <PictureAsPdfIcon color="error" fontSize="large" />

    {/* File name and "View PDF" link */}
    <Box>
    <Typography variant="body1" sx={{ color: 'black', mb: '2px' }}>
  {filePath ? filePath.split('/').pop()?.replace(/^\d+_/, '') ?? '' : ''}
</Typography>
<Typography
  variant="caption"
  sx={{ color: 'gray', cursor: 'pointer', mb:'2px' }}
>
  View PDF
</Typography>
    </Box>

    {/* Timestamp at bottom right */}
    <Typography
      variant="caption"
      sx={{
        position: 'absolute',
        bottom: -12, // Adjust as needed
        right: 0,
        // mt:5,
        color: 'text.secondary',
      }}
    >
      {formattedTime}
    </Typography>
  </Box>
)}
                {!isImage && ! isPDF && (

             
                <Typography
                  variant="caption"
                  color="textSecondary"
                  display="block"
                  mt={0.5}
                  textAlign="right"
                >
               {formattedTime}
                </Typography> 
                )}
              </Paper>
            </Box>
          );
        })}
                  <div ref={messagesEndRef} />

      </Paper>


      <Paper
  elevation={1}
  sx={{
    p: 1,
    borderRadius: 1.5, // Reduced radius
    backgroundColor: '#f5f5f5' // Light gray
  }}
>
  <Box display="flex" alignItems="center">
  <IconButton onClick={handleAttachClick}>
            <AttachFileIcon />
          </IconButton>
          <input
  type="file"
  style={{ display: 'none' }}
  ref={fileInputRef}
  onChange={(e) => {
    if (e.target.files && e.target.files.length > 0) {
      sendImageMessage(e.target.files[0]);  // pass the first selected file
      e.target.value = ''; // clear input to allow same file selection again if needed
    }
  }}
  accept="image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
/>

    <TextField
      fullWidth
      placeholder="Type your message..."
      multiline
      maxRows={4}
      value={newMessage}
      onChange={(e) => setNewMessage(e.target.value)}
      variant="standard" // Removes border outline
      sx={{
        mx: 1,
        flex: 1,
        '& .MuiInputBase-root': {
          backgroundColor: 'transparent'
        }
      }}
      InputProps={{
        disableUnderline: true, // Ensure no underline for standard input
        endAdornment: (
          <InputAdornment position="end">
            <IconButton
              color="primary"
              onClick={sendMessage}
              disabled={!newMessage.trim()}
            >
              <SendIcon />
            </IconButton>
          </InputAdornment>
        )
      }}
    />
  </Box>
</Paper>

 
    </Stack>
  );
}
