import { sub } from 'date-fns';
import { useRef, useMemo, useState, useCallback } from 'react';
import InputBase from '@mui/material/InputBase';
import { useMockedUser } from '@/hooks/use-mocked-user';
import uuidv4 from '@/utils/uuidv4';
import { sendMessage, createConversation } from '@/shared/api/chat';
import { IChatMessage, IChatParticipant, IClient } from '@/shared/types/chat';

// ----------------------------------------------------------------------

type Props = {
  recipients: IClient[];
  onAddRecipients: (recipients: IClient[]) => void;
  //
  disabled: boolean;
  selectedConversationId: string;
};

export default function ChatMessageInput({
  recipients,
  onAddRecipients,
  //
  disabled,
  selectedConversationId,
}: Props) {
  // const router = useRouter();

  const { user1 } = useMockedUser();

  const fileRef = useRef<HTMLInputElement>(null);

  const [message, setMessage] = useState('');

  const myContact: IClient = useMemo(
    () => ({
      id: `${user1?.id}`, 
      uuid: `${user1?.uuid}`, 
      dsiplayname: user1?.displayName || '', 
      firstname: user1?.firstname || '', 
      lastname: user1?.lastname || '', 
      username: user1?.displayName || '', 
      usernameType: 'user', // 
      avatarUrl: `${user1?.photoURL}`, 
      phoneNumber: `${user1?.phoneNumber}`, 
      status: 'online' as 'online' | 'offline', 
      lastActivity: new Date(), 
    }),
    [user1]
  );

  const messageData: IChatMessage = useMemo(
    () => ({
      id:0,
      uuid: uuidv4(),
      createdAt: new Date(),
      date: sub(new Date(), { minutes: 1 }),
      body: message,
      sourceUuid: myContact.uuid, 
      type: 'text', // 
      destinationUuid: null, 
      owner: myContact, 
      update: false, 
      reactions: [], 
      pined: false, 
      conversation: '', 
      replyTo: null, 
      attachments: [], 
    }),
    [message, myContact]
  );

  const conversationData = useMemo(
    () => ({
      id: uuidv4(),
      name: '',
      messages: [messageData],
      participants: [...recipients, myContact],
      type: recipients.length > 1 ? 'GROUP' : 'ONE_TO_ONE',
      unreadCount: 0,
    }),
    [messageData, myContact, recipients]
  );

  const handleAttach = useCallback(() => {
    if (fileRef.current) {
      fileRef.current.click();
    }
  }, []);

  const handleChangeMessage = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setMessage(event.target.value);
  }, []);

  const handleSendMessage = useCallback(
    async (event: React.KeyboardEvent<HTMLInputElement>) => {
      try {
        if (event.key === 'Enter') {
          if (message) {
            if (selectedConversationId) {
              await sendMessage(selectedConversationId, messageData);
            } else {
              const res = await createConversation(conversationData);
              onAddRecipients([]);
            }
          }
          setMessage('');
        }
      } catch (error) {
        console.error(error);
      }
    },
    [conversationData, message, messageData, onAddRecipients, selectedConversationId]
  );

  return (
    <>
      <InputBase
        value={message}
        onKeyUp={handleSendMessage}
        onChange={handleChangeMessage}
        placeholder="Message Stunar AI"
        disabled={disabled}
        sx={{
          px: 1,
          height: 56,
          flexShrink: 0,
          width: '100%',
          borderTop: (theme) => `solid 1px ${theme.palette.divider}`,
        }}
      />

      <input type="file" ref={fileRef} style={{ display: 'none' }} />
    </>
  );
}
