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

'use client';

import * as React from 'react';
import { useEffect, useState, useContext } from 'react';
import { useRouter } from 'next/navigation';
import type { Metadata } from 'next';
import { ChatDots as ChatIcon } from '@phosphor-icons/react/dist/ssr/ChatDots';
import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import { config } from '@/config';
import { UserContext } from '@/contexts/user-context';
import { ChatList } from '@/components/dashboard/chat/chat-list';
import GroupItem from '@/components/dashboard/chat/group-list';
import ChatRoom from '@/components/dashboard/chat/chat-room';
import GroupChatRoom from '@/components/dashboard/chat/group-chatroom';

import UserList from '@/components/dashboard/chat/user-list';
import GroupCreationPanel from '@/components/dashboard/chat/GroupCreationPanel';
import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { Button, Stack, Typography, IconButton } from '@mui/material';


import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';


export const metadata = {
  title: `Chats | Dashboard | ${config.site.name}`
} satisfies Metadata;

export interface Chat {
  id: string;
  name: string;
  lastMessage: string;
  lastMessageTime: string;
  avatar?: string;
  chat_id: string;
  receiver_id: string;
  sender_id: string;

  role: string;
  receiverName:string
  profile:string;
}

interface Group {
    id: string;
    group_name: string;
    last_message?: string;
    last_message_type?: string;
    last_sender_name?: string;
    chat_image?: string;
    member_names?: string;
    last_message_time?: string;
    company_name?: string;
  }
  

export function ChatsPageClient(): React.JSX.Element {
  const [chats, setChats] = useState<Chat[]>([]);
  const [userList, setUserList] = useState<Chat[]>([]);
  const [groups, setGroups] = useState<Group[]>([]);
  const [patientChats, setPatientChats] = useState<Chat[]>([]);


  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const { user: loggedInUser } = useContext(UserContext) ?? {};
  const [tab, setTab] = useState(0);
  const [noChannelsMessage, setNoChannelsMessage] = useState('');
  const [selectedChatId, setSelectedChatId] = useState<string | null>(null);
  const [receiverId, setReceiverId] = useState<string | null>(null);
  const [receiverName, setReceiverName] = useState<string | null>(null);

  const [role, setRole] = useState<string | null>(null);
  const [isNewChat, setIsNewChat] = useState(false);
  const [isGroupChat, setIsGroupChat] = useState(false);
  const [selectedGroupName, setSelectedGroupName] = useState('');
  const [selectedGroupMembers, setSelectedGroupMembers] = useState('');


  
  const [usersLoading, setUsersLoading] = useState(true); // for users loading


  useEffect(() => {
    if (!loggedInUser) return;
    const fetchChats = async () => {
      try {
        const params = new URLSearchParams();
        params.append('userId', loggedInUser.id);
    
        if (loggedInUser.role === 'manager' && loggedInUser.companies.length > 0) {
          const activeCompany = loggedInUser.companies.find(company => company.active);
          if (activeCompany) {
            params.append('companyId', activeCompany.id.toString());
          }
        }
    
        const url = `/admin/api/chats/list?${params.toString()}`;
        const res = await fetch(url);
        const data = await res.json();
    
        const allChats: any[] = [];
        const patientChats: any[] = [];
    
        data.forEach((chat: any, index: number) => {
          const formattedChat = {
            receiver_id: chat.receiver_id || `CHAT-${index + 1}`,
            name: chat.receiver_name || chat.group_name || 'Unknown',
            lastMessage: chat.last_message || 'No messages yet',
            lastMessageTime: chat.last_message_time || chat.timestamp || null,
            avatar: chat.receiver_image 
              ? `https://gohelloprovider.com/app/images/${chat.receiver_image}` 
              : '/assets/Portrait_Placeholder.png',
            chat_id: chat.chat_id,
          };
    
          if (chat.chat_with === 'user') {
            patientChats.push(formattedChat);
          } else {
            allChats.push(formattedChat);
          }
        });
    
        setChats(allChats);     // For chats not with the user
        setPatientChats(patientChats);    // For chats where chat_with === user
      } catch (err) {
        // console.error('Failed to fetch chats', err);
      } finally {
        setLoading(false);
      }
    };
    


    const fetchGroups = async () => {
        try {
          const params = new URLSearchParams();
          params.append('userId', loggedInUser.id);
    
          if (loggedInUser.role === 'manager' && loggedInUser.companies.length > 0) {
            const activeCompany = loggedInUser.companies.find(company => company.active);
            if (activeCompany) {
              params.append('companyId', activeCompany.id.toString());
  
            }
          }
    
          const url = `/admin/api/chats/groups?${params.toString()}`;
          const res = await fetch(url);
          const data = await res.json();
          // console.log(data,'group datatatat')
    
        //   const formatted = data.map((chat: any, index: number) => ({
        //     id: chat.receiver_id || `CHAT-${index + 1}`,
        //     name: chat.receiver_name || chat.group_name || 'Unknown',
        //     lastMessage: chat.last_message || 'No messages yet',
        //     lastMessageTime: chat.last_message_time || chat.timestamp || null,
        //     avatar: chat.receiver_image || chat.group_image || '/assets/avatar-1.png',
        //   }));
    
        if (Array.isArray(data) && data.length === 0) {
            setNoChannelsMessage('No channels found');
          } else {
            setGroups(data);
            setNoChannelsMessage('');
          }
         
        } catch (err) {
          // console.error('Failed to fetch chats', err);
        } finally {
          setLoading(false);
        }
      };


   
  
  
    fetchChats();
    fetchGroups();
  }, [loggedInUser]);

  const getRoleByTab = (tab: number): string => {
    switch (tab) {
      case 0:
        return 'chat';  // or whatever is appropriate
      case 1:
        return 'channel';         // maybe skip channels for new chat
      case 2:
        return 'patient';   // or appropriate role
      default:
        return '';
    }
  };
  
  useEffect(() => {
    if (isNewChat) {
      const role = getRoleByTab(tab);
      fetchNewChatUsers(role);
    }
  }, [isNewChat, tab]);

  const fetchNewChatUsers = async (role: string) => {
    try {
      const currentUserId = loggedInUser?.id;
      const activeCompany = loggedInUser?.companies?.find(company => company.active);
      const companyId = activeCompany?.id;
  
      const url = `/admin/api/new-chat-users?role=${role}&companyId=${companyId}`;
      const res = await fetch(url);
      const data = await res.json();
      // console.log(data,'datadatadata')
  
      setUserList(data.users);

    } catch (err) {
      // console.error('Failed to fetch new chat users', err);
    } finally {
      setLoading(false);
     
        setUsersLoading(false);
      
    }
  };
  const handleUserSelect = (user: { id: string; name: string; role:string }) => {
    // Try to find if chat already exists with this user
    const existingChat = chats.find(
      (chat) => chat.receiver_id === user.id || chat.sender_id === user.id
    );
  
    // console.log(user.role,'existingChat.id')
    if (existingChat) {
      setSelectedChatId(existingChat.chat_id);
    } else {
      setSelectedChatId(null);
      setIsNewChat(true); // new chat mode
    }
  
    setReceiverId(user.id);
    setReceiverName(user.name);
    setRole(user.role);

  };
  
  const handleChatClick = ({ chatId, receiverId, role,receiverName }: { chatId: string; receiverId: string; role: string; receiverName: string }) => {
 

    setSelectedChatId(chatId);
    setReceiverId(receiverId);
    setReceiverName(receiverName);
    setIsGroupChat(false);

    
    setRole(role);
  };

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTab(newValue);
  };
  
  const handleCreateGroup = async (groupName: string, memberIds: string[], groupImage?: File | null) => {
    const formData = new FormData();
    formData.append('name', groupName);
    memberIds.forEach(id => formData.append('members[]', id));
    if (groupImage) {
      formData.append('image', groupImage);
    }
  
    try {
      const res = await fetch('/admin/api/create-group', {
        method: 'POST',
        body: formData
      });
  
      const data = await res.json();
  
      if (res.ok) {
        alert('Group created successfully!');
        setIsNewChat(false); // exit group creation
        // refresh group list if needed
      } else {
        alert(data.error || 'Failed to create group');
      }
    } catch (err) {
      // console.error(err);
      alert('An error occurred');
    }
  };
  
  return (
    <Stack direction="row" spacing={3} sx={{ height: 'calc(100vh - 64px)',  }}>
    {/* Left pane: Chat list with tabs */}
    <Box sx={{ width: '350px', borderRight: '1px solid #ddd', height: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'column' }}>
      {/* Fixed Header */}
      <Stack spacing={3} sx={{ p: 2 }}>
        <Stack direction="row" spacing={3} alignItems="center">
          {isNewChat ? (
            <>
              <IconButton onClick={() => setIsNewChat(false)}>
                <ArrowBackIcon />
              </IconButton>
              <Typography variant="h4" sx={{ flex: '1 1 auto' }}>
                New Chat
              </Typography>
            </>
          ) : (
            <>
              <Typography variant="h4" sx={{ flex: '1 1 auto' }}>
                Messages
              </Typography>
              <Button
                onClick={() => setIsNewChat(true)}
                startIcon={<PlusIcon fontSize="var(--icon-fontSize-md)" />}
                variant="contained"
              >
                New Chat
              </Button>
            </>
          )}
        </Stack>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={tab} onChange={handleTabChange}>
            <Tab label="Chats" />
            <Tab label="Channels" />
            <Tab label="Patients" />
          </Tabs>
        </Box>
      </Stack>

      {/* Scrollable Content */}
      <Box sx={{ flexGrow: 1, overflowY: 'auto' }}>
        {isNewChat ? (
          loading ? (
            <Typography>Loading users...</Typography>
          ) : (
            tab === 1 ? (
              <GroupCreationPanel
                users={userList}
                usersLoading={usersLoading}
                // onCreateGroup={handleCreateGroup}
              />
            ) : (
              <UserList
                users={userList}
                onUserSelect={handleUserSelect}
              />
            )
          )
        ) : (
          <>
            {tab === 0 && (
              loading ? <Typography>Loading chats...</Typography> :
              <ChatList chats={chats} onChatClick={handleChatClick} receiverId={receiverId} role={role} selectedChatId={selectedChatId} />
            )}
            {tab === 1 && (
              loading ? <Typography>Loading channels...</Typography> :
              groups.length === 0 ? (
                <Typography>No channels found</Typography>
              ) : (
                <Stack spacing={2}>
                  {groups.map((group) => (
                    <GroupItem key={group.id} chat={group}
                    onClick={() => {
                      setSelectedChatId(group.id);
                      setSelectedGroupName(group.group_name);
                      setSelectedGroupMembers(group.member_names ?? '');
                      setIsGroupChat(true);
                    }}
                    />
                  ))}
                </Stack>
              )
            )}
             {tab === 2 && (
              loading ? <Typography>Loading chats...</Typography> :
              patientChats.length === 0 ? (
                <Typography>No patient chat found</Typography>
              ):(
              <ChatList chats={patientChats} onChatClick={handleChatClick} receiverId={receiverId} role={role} selectedChatId={selectedChatId} />
            ))}
          </>
        )}
      </Box>
    </Box>
    {/* Right pane: Chat Room */}
    <Box sx={{ flex: 1, height: '100%', display: 'flex', flexDirection: 'column' }}>
    {selectedChatId && isGroupChat ? (
  <GroupChatRoom groupId={selectedChatId}  memberNames={selectedGroupMembers} groupName={selectedGroupName} router={router} />
) : selectedChatId || receiverId ?  (
  <ChatRoom chatId={selectedChatId} receiverId={receiverId} role={role} receiverName={receiverName} router={router} />
) : (
        <Box
        sx={{
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'column',
          textAlign: 'center',
          color: 'text.secondary',
          px: 3,
        }}
      >
        <ChatBubbleOutlineIcon sx={{ fontSize: 100, color: 'grey.400', mb: 2 }} />
    
        <Typography variant="h5" gutterBottom>
          No Chat Selected
        </Typography>
    
        <Typography variant="body1" sx={{ maxWidth: 360 }}>
          Please select a chat from the list on the left to start messaging.
        </Typography>
      </Box>
      )}
    </Box>
  </Stack>
  );
}
