import { useEffect, useMemo } from 'react';
import keyBy from 'lodash/keyBy';
import useSWR, { mutate } from 'swr';
import axios, { fetcher, endpoints } from '@/utils/axios';

import {
    IChatMessage,
    IChatParticipant,
    IChatConversation,
    IChatConversations,
    IClient,
    IChatConversationClient,
} from '@/shared/types/chat';
import { useMockedUser, useRouter } from '@/hooks';
import { paths } from '@/routes/paths';

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

const options = {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
};



export function useGetContactsTest() {
    const URL = `http://localhost:4000/client/clients`;

    const { data, error, isValidating } = useSWR(URL, fetcher, options);

    const memoizedValue = useMemo(() => {

        const contacts = Array.isArray(data) ? data as IClient[] : [];
        const contactsLoading = !error && !data;
        const contactsError = error;
        const contactsValidating = isValidating;
        const contactsEmpty = !contactsLoading && contacts.length === 0;


        return {
            contacts,
            contactsLoading,
            contactsError,
            contactsValidating,
            contactsEmpty,
        };
    }, [data, error, isValidating]);

    return memoizedValue;
}

// const fetcher = async (userId: number) => {
//     const response = await fetch(`http://localhost:4000/client/infos`, {
//       method: 'GET',
//       headers: {
//         'Content-Type': 'application/json',
//       },
//       body: JSON.stringify({ id: userId }),
//     });

//     if (!response.ok) {
//       throw new Error('Failed to fetch user info');
//     }

//     return response.json();
//   };


const fetcher1 = (url: string) => fetch(url).then(res => res.json());
export function useGetUserInfos(userId: number) {
    const URL = `http://localhost:4000/client/${userId}/infos`;

    const { data, isLoading, error, isValidating } = useSWR(URL, fetcher1);

    const memoizedValue = useMemo(() => {
        const connectedClient = data as IClient;
        return {
            connectedClient,
            contactsLoading: isLoading,
            contactsError: error,
            contactsValidating: isValidating,
            contactsEmpty: !isLoading && !data?.contacts?.length,
        };
    }, [data, error, isLoading, isValidating]);

    return memoizedValue;
}
// ----------------------------------------------------------------------

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

export function useGetConversation(conversationId: string) {

    const URL = conversationId ? `http://localhost:4000/conversation/${conversationId}` : '';
    const router = useRouter();

    const { data, isLoading, error, isValidating, } = useSWR(URL, fetcher, options);
    

    const memoizedValue = useMemo(() => {
        const conversation = data as IChatConversationClient;
        const conversationLoading = isLoading;
        const conversationError = error;
        const conversationValidating = isValidating;
        return {
            conversation,
            conversationLoading,
            conversationError,
            conversationValidating,
            mutate,
        };
    }, [data, error, isValidating]);

   

    // useEffect(() => {
    //   if (lastMessage !== null) {
    //     // setMessages((prev) => prev.concat(lastMessage));
    //     mutate(URL, ()=>{})
    //   }
    // }, [lastMessage]);
    // const revalidate = () => {
    //   if (URL) {
    //     mutate(URL);
    //   }
    // };

    // const updateConversation = (updatedData: IChatConversationClient) => {
    //   if (URL) {
    //     mutate(URL, updatedData, false); // Le troisième argument `false` empêche la révalidation automatique
    //   }
    // };

    // return { ...memoizedValue, revalidate, updateConversation };
    return memoizedValue;
}

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

// export async function sendMessage(conversationId: string, messageData: IChatMessage) {
//   const CONVERSATIONS_URL = [endpoints.chat, { params: { endpoint: 'conversations' } }];

//   const CONVERSATION_URL = [
//     endpoints.chat,
//     {
//       params: { conversationId, endpoint: 'conversation' },
//     },
//   ];

//   /**
//    * Work on server
//    */
//   // const data = { conversationId, messageData };
//   // await axios.put(endpoints.chat, data);

//   /**
//    * Work in local
//    */
//   mutate(
//     CONVERSATION_URL,
//     (currentData: any) => {
//       const { conversation: currentConversation } = currentData;

//       const conversation = {
//         ...currentConversation,
//         messages: [...currentConversation.messages, messageData],
//       };

//       return {
//         conversation,
//       };
//     },
//     false
//   );

//   /**
//    * Work in local
//    */
//   mutate(
//     CONVERSATIONS_URL,
//     (currentData: any) => {
//       const { conversations: currentConversations } = currentData;

//       const conversations: IChatConversation[] = currentConversations.map(
//         (conversation: IChatConversation) =>
//           conversation.id === conversationId
//             ? {
//               ...conversation,
//               messages: [...conversation.messages, messageData],
//             }
//             : conversation
//       );

//       return {
//         conversations,
//       };
//     },
//     false
//   );
// }

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

export async function createConversation(conversationData: IChatConversation) {
    const URL = [endpoints.chat, { params: { endpoint: 'conversations' } }];

    /**
     * Work on server
     */
    const data = { conversationData };
    const res = await axios.post(endpoints.chat, data);

    /**
     * Work in local
     */
    mutate(
        URL,
        (currentData: any) => {
            const conversations: IChatConversation[] = [...currentData.conversations, conversationData];
            return {
                ...currentData,
                conversations,
            };
        },
        false
    );

    return res.data;
}

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

export async function clickConversation(conversationId: string) {
    const URL = endpoints.chat;

    /**
     * Work on server
     */
    // await axios.get(URL, { params: { conversationId, endpoint: 'mark-as-seen' } });

    /**
     * Work in local
     */
    mutate(
        [
            URL,
            {
                params: { endpoint: 'conversations' },
            },
        ],
        (currentData: any) => {
            const conversations: IChatConversations = currentData.conversations.map(
                (conversation: IChatConversation) =>
                    conversation.id === conversationId ? { ...conversation, unreadCount: 0 } : conversation
            );

            return {
                ...currentData,
                conversations,
            };
        },
        false
    );
}


export function useGetConversations() {
    const { user1 } = useMockedUser();
    const URL = `http://localhost:4000/conversations/${user1.id}`;

    const { data, isLoading, error, isValidating, mutate } = useSWR(URL, fetcher, options);

    const memoizedValue = useMemo(() => {
        if (!data || !Array.isArray(data)) {
            return {
                conversations: {
                    byId: {},
                    allIds: [],
                } as IChatConversations,
                conversationsLoading: isLoading,
                conversationsError: error,
                conversationsValidating: isValidating,
                conversationsEmpty: !isLoading,
                mutate,
            };
        }

        // Ajouter la date du dernier message et trier les conversations par cette date
        const conversationsWithLastMessageDate = data.map((conversation: IChatConversationClient) => {
            const lastMessageDate = conversation.messages.length > 0
                ? new Date(conversation.messages[conversation.messages.length - 1].date).getTime()
                : 0; // Utiliser 0 si aucune message, ce qui mettra cette conversation en bas de la liste

            return {
                ...conversation,
                name: `#${conversation.id}`, // Utilisez une convention de nommage de votre choix
                lastMessageDate,
            };
        });

        const sortedConversations = conversationsWithLastMessageDate.sort((a, b) => b.lastMessageDate - a.lastMessageDate);

        const byId = keyBy(sortedConversations, 'uuid');
        const allIds = Object.keys(byId);

        return {
            conversations: {
                byId,
                allIds,
            } as IChatConversations,
            conversationsLoading: isLoading,
            conversationsError: error,
            conversationsValidating: isValidating,
            conversationsEmpty: !isLoading && allIds.length === 0,
            mutate,
        };
    }, [data, error, isLoading, isValidating]);

    return memoizedValue;
}


//****************************************WEB SOCKET****************************************************** */




