'use client';
import React, { useState, useEffect, useRef, useCallback, memo } from 'react';
import { useAtom } from 'jotai';
import Image from 'next/image';
import {
  ArrowLeft,
  Send,
  Mic,
  Smile,
  Info,
  Phone,
  Video,
  X,
  Image as ImageIcon,
  BotMessageSquare,
} from 'lucide-react';
import { cn } from './utils';
import { ChatMessage, ChatUser } from './types';
import { isMobileAtom, chatDetailOpenAtom } from './store';

// Mock messages for demonstration
const mockMessages: ChatMessage[] = [
  {
    id: '1',
    content: 'Hello, how are you doing today?',
    senderId: 'other',
    timestamp: '10:30 AM',
  },
  {
    id: '2',
    content: "I'm doing well, thanks for asking! How about you?",
    senderId: 'me',
    timestamp: '10:31 AM',
  },
  {
    id: '3',
    content:
      'Pretty good. I was wondering if you had time to catch up on the project later today?',
    senderId: 'other',
    timestamp: '10:32 AM',
  },
  {
    id: '4',
    content: "Sure, I'm free after 3 PM. Would that work for you?",
    senderId: 'me',
    timestamp: '10:33 AM',
  },
  {
    id: '5',
    content: "That sounds perfect. Let's meet at the usual place?",
    senderId: 'other',
    timestamp: '10:35 AM',
  },
];

// Memoized individual message component
const MessageItem = memo(
  ({ message, user }: { message: ChatMessage; user: ChatUser }) => {
    const isFromMe = message.senderId === 'me';

    return (
      <div
        className={cn('flex mb-4', isFromMe ? 'justify-end' : 'justify-start')}
      >
        {!isFromMe && (
          <div className="h-8 w-8 rounded-full overflow-hidden flex-shrink-0 mr-2">
            {user.avatar ? (
              <div className="relative w-full h-full">
                <Image
                  src={user.avatar}
                  alt={user.name}
                  fill
                  className="object-cover"
                  sizes="32px"
                />
              </div>
            ) : (
              <div className="bg-gray-400 h-full w-full flex items-center justify-center text-white">
                {user.name.charAt(0)}
              </div>
            )}
          </div>
        )}
        <div
          className={cn(
            'max-w-[75%] px-4 py-2 rounded-lg',
            isFromMe
              ? 'bg-blue-500 text-white rounded-br-none'
              : 'bg-gray-200 text-gray-800 rounded-tl-none'
          )}
        >
          <p className="break-words">{message.content}</p>
          <div
            className={cn(
              'text-xs mt-1',
              isFromMe ? 'text-blue-100' : 'text-gray-500'
            )}
          >
            {message.timestamp}
          </div>
        </div>
      </div>
    );
  }
);

MessageItem.displayName = 'MessageItem';

// Chat details sidebar component
const ChatDetailsSidebar = memo(
  ({ user, onClose }: { user: ChatUser; onClose: () => void }) => {
    return (
      <div className="w-full h-full flex flex-col bg-white text-gray-800 overflow-y-auto shadow-lg">
        <div className="p-4 border-b border-gray-200 flex justify-between items-center">
          <h2 className="font-medium text-lg">Details</h2>
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-100 rounded-full transition-colors"
            aria-label="Close details"
          >
            <X size={18} />
          </button>
        </div>

        <div className="px-4 py-5 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <span className="font-medium">Mute messages</span>
            <div className="relative inline-block w-12 h-6 transition duration-200 ease-in-out rounded-full">
              <input
                type="checkbox"
                id="muteToggle"
                className="absolute w-0 h-0 opacity-0"
              />
              <label
                htmlFor="muteToggle"
                className="block h-6 overflow-hidden rounded-full cursor-pointer bg-gray-300"
              >
                <span className="absolute left-1 top-1 block w-4 h-4 rounded-full bg-white transition-transform duration-200 shadow"></span>
              </label>
            </div>
          </div>
        </div>

        <div className="p-4 border-b border-gray-200">
          <h3 className="font-medium mb-3">Members</h3>
          <div className="flex items-center space-x-3 mb-2">
            <div className="relative w-10 h-10 rounded-full overflow-hidden shadow">
              {user.avatar ? (
                <Image
                  src={user.avatar}
                  alt={user.name}
                  fill
                  className="object-cover"
                  sizes="40px"
                />
              ) : (
                <div className="bg-gray-400 h-full w-full flex items-center justify-center text-white">
                  {user.name.charAt(0)}
                </div>
              )}
            </div>
            <div className="flex-1">
              <div className="font-medium">{user.name}</div>
              <div className="text-sm text-gray-500">
                {user.name.toLowerCase().replace(/\s/g, '')}
              </div>
            </div>
          </div>
        </div>

        <div className="mt-auto border-t border-gray-200">
          <button className="w-full py-3 text-red-500 hover:bg-gray-100 transition-colors flex items-center justify-center font-medium">
            Report
          </button>
          <button className="w-full py-3 text-red-500 hover:bg-gray-100 transition-colors flex items-center justify-center font-medium">
            Block
          </button>
          <button className="w-full py-3 text-red-500 hover:bg-gray-100 transition-colors flex items-center justify-center font-medium">
            Delete chat
          </button>
        </div>
      </div>
    );
  }
);

ChatDetailsSidebar.displayName = 'ChatDetailsSidebar';

interface ChatDetailProps {
  user: ChatUser;
  onBack: () => void;
}

const ChatDetail: React.FC<ChatDetailProps> = ({ user, onBack }) => {
  const [isMobile] = useAtom(isMobileAtom);
  const [, setChatDetailOpen] = useAtom(chatDetailOpenAtom);

  const [messages, setMessages] = useState<ChatMessage[]>(mockMessages);
  const [inputValue, setInputValue] = useState('');
  const [isDetailSidebarOpen, setIsDetailSidebarOpen] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messageContainerRef = useRef<HTMLDivElement>(null);

  // Scroll to bottom when messages change
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]);

  // Add message handler
  const addMessage = useCallback((message: ChatMessage) => {
    setMessages((prev) => [...prev, message]);
  }, []);

  // Send message handler
  const handleSend = useCallback(() => {
    if (inputValue.trim()) {
      const newMessage: ChatMessage = {
        id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        content: inputValue,
        senderId: 'me',
        timestamp: new Date().toLocaleTimeString([], {
          hour: '2-digit',
          minute: '2-digit',
        }),
      };
      addMessage(newMessage);
      setInputValue('');

      // Simulate response after a delay
      setTimeout(() => {
        const responseMessage: ChatMessage = {
          id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
          content: "Thanks for your message. I'll get back to you soon!",
          senderId: 'other',
          timestamp: new Date().toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit',
          }),
        };
        addMessage(responseMessage);
      }, 1000);
    }
  }, [inputValue, addMessage]);

  // Back button handler
  const handleBack = useCallback(() => {
    setChatDetailOpen(false);
    onBack();
  }, [setChatDetailOpen, onBack]);

  // Handle enter key press in input field
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        handleSend();
      }
    },
    [handleSend]
  );

  // Toggle details sidebar
  const toggleDetailSidebar = useCallback(() => {
    setIsDetailSidebarOpen((prev) => !prev);
  }, []);

  return (
    <div className="flex h-full bg-white text-gray-800">
      {/* Main Chat Area */}
      <div
        className={cn(
          'flex flex-col h-full transition-all duration-300',
          isDetailSidebarOpen
            ? 'w-0 md:w-2/3 lg:w-3/4 opacity-0 md:opacity-100'
            : 'w-full'
        )}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-3 border-b border-gray-200 bg-white shadow-sm">
          <div className="flex items-center space-x-3">
            <button
              onClick={handleBack}
              className="p-1 hover:bg-gray-100 rounded-full transition-colors"
              aria-label="Go back"
            >
              <ArrowLeft size={20} className="text-gray-600" />
            </button>

            <div className="flex items-center space-x-3">
              <div className="relative w-10 h-10 rounded-full overflow-hidden shadow">
                {user.avatar ? (
                  <Image
                    src={user.avatar}
                    alt={user.name}
                    fill
                    className="object-cover"
                    sizes="40px"
                  />
                ) : (
                  <div className="bg-gray-400 h-full w-full flex items-center justify-center text-white">
                    {user.name.charAt(0)}
                  </div>
                )}
              </div>
              <div>
                <h2 className="font-medium text-gray-900">{user.name}</h2>
                <p className="text-xs text-gray-500">Active 5h ago</p>
              </div>
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <button className="p-2 hover:bg-gray-100 rounded-full transition-colors">
              <Phone size={20} className="text-gray-600" />
            </button>
            <button className="p-2 hover:bg-gray-100 rounded-full transition-colors">
              <Video size={20} className="text-gray-600" />
            </button>
            <button
              className="p-2 hover:bg-gray-100 rounded-full transition-colors"
              onClick={toggleDetailSidebar}
            >
              <Info size={20} className="text-gray-600" />
            </button>
          </div>
        </div>

        {/* Messages */}
        <div
          ref={messageContainerRef}
          className="flex-1 overflow-y-auto p-4 bg-white"
          style={{
            display: isDetailSidebarOpen && isMobile ? 'none' : 'block',
          }}
        >
          {messages.map((message) => (
            <MessageItem key={message.id} message={message} user={user} />
          ))}
          <div ref={messagesEndRef} />
        </div>

        {/* Input */}
        <div className="border-t border-gray-200 p-3 bg-white">
          <div className="flex items-center bg-gray-100 rounded-full px-4 py-2 shadow-sm">
            <button className="p-2 text-gray-500 hover:text-gray-700 transition-colors">
              <Smile size={20} />
            </button>
            <input
              type="text"
              placeholder="Message..."
              value={inputValue}
              onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}
              onKeyDown={handleKeyDown}
              className="flex-1 bg-transparent mx-2 outline-none text-gray-800"
            />
            <div className="flex items-center space-x-2">
              <button className="p-2 text-gray-500 hover:text-gray-700 transition-colors">
                <BotMessageSquare size={20} />
              </button>
              <button className="p-2 text-gray-500 hover:text-gray-700 transition-colors">
                <ImageIcon size={20} />
              </button>
              <button className="p-2 text-gray-500 hover:text-gray-700 transition-colors">
                <Mic size={20} />
              </button>
              <button
                onClick={handleSend}
                className={cn(
                  'p-2 rounded-full',
                  inputValue.trim()
                    ? 'bg-blue-500 text-white hover:bg-blue-600'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                )}
                disabled={!inputValue.trim()}
                aria-label="Send message"
              >
                <Send size={18} />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Detail Sidebar */}
      <div
        className={cn(
          'h-full transition-all duration-300 overflow-hidden border-l border-gray-200',
          isDetailSidebarOpen ? 'w-full md:w-1/3 lg:w-1/4' : 'w-0'
        )}
      >
        {isDetailSidebarOpen && (
          <ChatDetailsSidebar user={user} onClose={toggleDetailSidebar} />
        )}
      </div>
    </div>
  );
};

export default memo(ChatDetail);
