/* 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, 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';
// import Tooltip from '@mui/material/Tooltip';
interface GroupMessage {
    groupId: string;
    timestamp: string;
    sender_id: string;
    message: string | null; 
    sender_name:string | null;

    file_path?: string | null;
    sender_profile: string | null;
  }
  
  interface GroupChatRoomProps {
    groupId: string;
    groupName: string;
    memberNames: string; // New prop
    router: any;
  }

export default function ChatRoom({ groupId, groupName, memberNames, router}: GroupChatRoomProps) {
  const [messages, setMessages] = useState<GroupMessage[]>([]);
  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 currentUserName = loggedInUser?.name;
  // const currentUserprofile = loggedInUser?.profile;
  const currentUserprofile: string | null = loggedInUser?.profile as string ?? null;



  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: GroupMessage) => {
      setMessages((prev) => [...prev, data]);
    });

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

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

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

  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: GroupMessage & {
    //   receiverId?: string | string[];
    //   chat_with?: any;
      company_id?: number;
    } = {
      groupId,
      message: newMessage.trim(),
      timestamp: mysqlFormattedTimestamp,
      sender_id: currentUserId ? currentUserId : '',

      sender_name: currentUserName || null,
      sender_profile: currentUserprofile ?? null,
      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-group-message', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(messageData),
      });

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

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

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

  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('file', 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('company_id', companyId?.toString() || ''); // replace with your company id (string)
    formData.append('groupId', groupId);          // your role variable
    formData.append('timestamp', mysqlFormattedTimestamp);
  
   
  
    try {
      const response = await fetch('https://gohelloprovider.com/chat/group-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 || '',
      
          groupId: groupId,
          message: null,
          timestamp: mysqlFormattedTimestamp,
       
          company_id: companyId,
        });
  
        // Update local messages state if you have it
        setMessages((prev) => [
          ...prev,
          {
            message: null,
            sender_id: currentUserId || '',
        
            groupId:groupId,
            timestamp: mysqlFormattedTimestamp,
            file_path: data.file_path,
         
            company_id: companyId,
            sender_name: currentUserName || null,
            sender_profile: currentUserprofile ?? null,

            
          },
        ]);
      }
    } catch (error) {
      // console.error('❌ Error Uploading Image:', error);
    }
  };

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

  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"
      spacing={2}
      alignItems="center"
      p={2}
      bgcolor="#f5f5f5"
      borderBottom="1px solid #ccc"
      flex="0 0 auto"
    >
      <Avatar sx={{ bgcolor: '#1976d2' }}>{groupName[0]}</Avatar>
      <Box>
        <Typography variant="h6">{groupName}</Typography>
        <Typography variant="body2" color="text.secondary">
          {memberNames}
        </Typography>
      </Box>
    </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(msg,'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'}
          >
            {/* Show sender's name and image if not current user */}
            {!isSender && (
  <Box display="flex" alignItems="center" mb={0.5}>
    <Avatar
      src={msg.sender_profile ? `https://gohelloprovider.com/${msg.sender_profile}` : '/admin/assets/Portrait_Placeholder.png'}
      alt={msg.sender_name || 'User'}
      sx={{ width: 24, height: 24, mr: 1 }}
    />
    <Typography variant="caption" fontWeight="bold">
      {msg.sender_name}
    </Typography>
  </Box>
)}

          
            <Paper
              sx={{
                p: 1.5,
                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,
                    }}
                  />
                  <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>
)}
          
              {/* Timestamp for text messages */}
              {!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 direction="row" spacing={2} alignItems="center">
        <TextareaAutosize
          minRows={1}
          maxRows={4}
          placeholder="Type your message..."
          style={{
            flexGrow: 1,
            resize: 'none',
            padding: 8,
            fontSize: '1rem',
            borderRadius: 4,
            borderColor: '#ccc',
            fontFamily: 'inherit',
          }}
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
              e.preventDefault();
              sendMessage();
            }
          }}
        />
        <Button variant="contained" onClick={sendMessage} disabled={!newMessage.trim()}>
          Send
        </Button>
      </Stack> */}
    </Stack>
  );
}
