import React, { useState } from 'react';
import { Search, MoreVertical, Send, Phone, Video, Check, CheckCheck, ArrowLeft, Star, Share2, Flag, Ban, Trash2 } from 'lucide-react';
import ReportModal from '../components/common/ReportModal';

const ChatUI = () => {
  const [selectedChat, setSelectedChat] = useState(null);
  const [message, setMessage] = useState('');
  const [showChatOnMobile, setShowChatOnMobile] = useState(false);
  const [showCallHistory, setShowCallHistory] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const [showChatMenu, setShowChatMenu] = useState(false);
const [openReport, setOpenReport] = useState(false);

  const contacts = [
    {
      id: 1,
      name: 'Kalai',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Kalai',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
    {
      id: 2,
      name: 'Sabitha',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Sabitha',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
    {
      id: 3,
      name: 'Lia',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lia',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
    {
      id: 4,
      name: 'Moi',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Moi',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
    {
      id: 5,
      name: 'Sri',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Sri',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
    {
      id: 6,
      name: 'Lyana',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lyana',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
     {
      id: 7,
      name: 'Lyana',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lyana',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
     {
      id: 8,
      name: 'Lyana',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lyana',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
     {
      id: 9,
      name: 'Lyana',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lyana',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    },
     {
      id: 10,
      name: 'Lyana',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lyana',
      lastMessage: 'Hi bro!n how are you Long time no see',
      time: '10 Nov 2025, 10 : 23 AM',
      online: false
    }
  ];

  const messages = {
    1: [
      {
        id: 1,
        sender: 'other',
        text: 'Let\'s do it! I\'m in a meeting until noon.',
        time: '10 Nov',
        isDate: false
      },
      {
        id: 2,
        sender: 'me',
        text: 'That\'s perfect! There\'s a new place on Main St I\'ve been wanting to check out. I hear their hawaiian pizza is awesome!',
        time: '07:21',
        isDate: false
      },
      {
        id: 3,
        sender: 'date',
        text: 'Today',
        isDate: true
      },
      {
        id: 4,
        sender: 'me',
        text: 'Can\'s get lunch. How about tomorrow?',
        time: '09:42',
        isDate: false
      },
      {
        id: 5,
        sender: 'other',
        text: 'Let\'s do it! I\'m in a meeting until noon.',
        time: '',
        isDate: false
      },
      {
        id: 6,
        sender: 'me',
        text: 'That\'s perfect! There\'s a new place on Main St I\'ve been wanting to check out. I hear their hawaiian pizza is awesome!',
        time: '',
        isDate: false
      }
    ]
  };

  const callHistory = [
    {
      id: 1,
      name: 'Kalai',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Kalai',
      status: 'Incoming call',
      time: '10 : 00 AM',
      date: 'Today'
    },
    {
      id: 2,
      name: 'Lia',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lia',
      status: 'Outgoing',
      time: '10 : 00 AM',
      date: 'Today'
    },
    {
      id: 3,
      name: 'Moi',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Moi',
      status: 'Incoming call',
      time: '10 : 00 AM',
      date: 'Today'
    },
    {
      id: 4,
      name: 'Sri',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Sri',
      status: 'Outgoing',
      time: '10 : 00 AM',
      date: 'Today'
    },
    {
      id: 5,
      name: 'Kalai',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Kalai',
      status: 'Outgoing',
      time: '10 : 00 AM',
      date: 'Today'
    },
     {
      id: 6,
      name: 'Kalai',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Kalai',
      status: 'Outgoing',
      time: '10 : 00 AM',
      date: 'Today'
    },
     {
      id: 7,
      name: 'Kalai',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Kalai',
      status: 'Outgoing',
      time: '10 : 00 AM',
      date: 'Today'
    },
     {
      id: 8,
      name: 'Kalai',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Kalai',
      status: 'Outgoing',
      time: '10 : 00 AM',
      date: 'Today'
    }
  ];

  const [chatMessages, setChatMessages] = useState({
  1: [
    { id: 1, sender: 'other', text: "Let's do it! I'm in a meeting until noon.", time: '10 Nov', isDate: false , read: false },
    { id: 2, sender: 'me', text: "That's perfect! There's a new place...", time: '07:21 am', isDate: false , read: false },
    { id: 3, sender: 'date', text: 'Today', isDate: true, read: true | false  },
    { id: 4, sender: 'me', text: "Can's get lunch. How about tomorrow?", time: '09:42 am', isDate: false , read: true  },
    { id: 5, sender: 'other', text: "Let's do it! I'm in a meeting until noon.", time: '', isDate: false, read: true  },
    { id: 6, sender: 'me', text: "That's perfect! There's a new place...", time: '', isDate: false, read: true  },
  ],
  // 2,3,... if needed
});


  const handleSendMessage = () => {
  if (!message.trim() || !selectedChat) return;

  const now = new Date();
  const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

  setChatMessages(prev => {
    const prevMsgs = prev[selectedChat] || [];
    const newMsg = {
      id: prevMsgs.length ? prevMsgs[prevMsgs.length - 1].id + 1 : 1,
      sender: 'me',
      text: message.trim(),
      time: timeString,
      isDate: false,
    };

    return {
      ...prev,
      [selectedChat]: [...prevMsgs, newMsg],
    };
  });

  setMessage('');
};


  const handleChatSelect = (contactId) => {
    setSelectedChat(contactId);
    setShowChatOnMobile(true);
    setShowCallHistory(false);
  };

  const handleBackToList = () => {
    setShowChatOnMobile(false);
    setShowCallHistory(false);
    setShowChatMenu(false);
  };

  const handleCallHistoryClick = () => {
    setShowCallHistory(true);
    setShowChatOnMobile(false);
    setShowMenu(false);
  };

  return (

    <>
    
    
        <ReportModal open={openReport} onClose={() => setOpenReport(false)} />
    
     <div className="w-full max-w-[1400px] mx-auto flex h-screen gap-[20px] bg-gray-50">
      {/* Sidebar - Chat List */}
      <div className={`w-full md:w-96 bg-white border border-1 border-gray-200 rounded-[10px] flex flex-col ${
        showChatOnMobile || showCallHistory ? 'hidden md:flex' : 'flex'
      }`}>
        {/* Header */}
        <div className="p-4 border-b border-gray-200">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-xl font-semibold">Chat</h1>
            <div className="relative">
              <button 
                onClick={() => setShowMenu(!showMenu)}
                className="p-2 hover:bg-gray-100 rounded"
              >
                <MoreVertical className="w-5 h-5" />
              </button>
              
              {showMenu && (
                <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-50">
                  <button 
                    onClick={handleCallHistoryClick}
                    className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100"
                  >
                    <Phone className="w-4 h-4" />
                    <span className="text-sm">Call History</span>
                  </button>
                  <button className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3">
                    <span className="text-sm">Clear chat</span>
                  </button>
                </div>
              )}
            </div>
          </div>
          
          {/* Search */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search your partner here..."
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            />
          </div>
        </div>

        {/* Contact List */}
        <div className="flex-1 overflow-y-auto">
          {contacts.map((contact) => (
            <div
              key={contact.id}
              onClick={() => handleChatSelect(contact.id)}
              className={`flex items-center gap-3 p-4 cursor-pointer hover:bg-gray-50 border-b border-gray-100 ${
                selectedChat === contact.id ? 'bg-blue-50' : ''
              }`}
            >
              <div className="relative">
                <img
                  src={contact.avatar}
                  alt={contact.name}
                  className="w-12 h-12 rounded-full"
                />
                {contact.online && (
                  <div className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-white"></div>
                )}
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between mb-1">
                  <h3 className="font-medium text-gray-900">{contact.name}</h3>
                  <span className="text-xs text-gray-500">{contact.time}</span>
                </div>
                <p className="text-sm text-gray-600 truncate">
                  {contact.lastMessage}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Call History View */}
      {showCallHistory && (
        <div className={`flex-1 bg-white ${showCallHistory ? 'flex' : 'hidden md:flex'} flex-col`}>
          {/* Call History Header */}
          <div className="p-4 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <button
                  onClick={handleBackToList}
                  className="md:hidden p-2 hover:bg-gray-100 rounded"
                >
                  <ArrowLeft className="w-5 h-5 text-gray-600" />
                </button>
                <div className="flex items-center gap-3">
                  <img
                    src="https://api.dicebear.com/7.x/avataaars/svg?seed=User"
                    alt="User"
                    className="w-10 h-10 rounded-full"
                  />
                  <div>
                    <h2 className="font-semibold">Dalahamanner-Hv</h2>
                    <p className="text-xs text-gray-500">ID: TKS258AA</p>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button className="p-2 hover:bg-gray-100 rounded">
                  <Phone className="w-5 h-5 text-blue-600" />
                </button>
                <button className="p-2 hover:bg-gray-100 rounded">
                  <MoreVertical className="w-5 h-5" />
                </button>
              </div>
            </div>
          </div>

          {/* Filter Tabs */}
          <div className="flex gap-2 p-4 border-b border-gray-200">
            <button className="px-4 py-1.5 bg-red-500 text-white rounded-full text-sm font-medium">
              All
            </button>
            <button className="px-4 py-1.5 bg-gray-100 text-gray-700 rounded-full text-sm font-medium hover:bg-gray-200">
              Incoming Call
            </button>
            <button className="px-4 py-1.5 bg-gray-100 text-gray-700 rounded-full text-sm font-medium hover:bg-gray-200">
              Outgoing
            </button>
          </div>

          {/* Call History List */}
          <div className="flex-1 overflow-y-auto">
            <div className="p-4">
              <h3 className="text-sm font-semibold text-gray-900 mb-3">Today</h3>
              {callHistory.map((call) => (
                <div
                  key={call.id}
                  className="flex items-center gap-3 py-3 border-b border-gray-100"
                >
                  <img
                    src={call.avatar}
                    alt={call.name}
                    className="w-12 h-12 rounded-full"
                  />
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900">{call.name}</h4>
                    <div className="flex items-center gap-2 text-sm text-gray-500">
                      <Phone className="w-3 h-3" />
                      <span>{call.status}</span>
                    </div>
                  </div>
                  <span className="text-xs text-gray-500">{call.time}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Chat Area */}
      {selectedChat && !showCallHistory && (
        <div className={`border border-1 border-gray-200 rounded-[10px] flex-1 flex flex-col bg-white ${
          showChatOnMobile ? 'flex' : 'hidden md:flex'
        }`}>
          {/* Chat Header */}
          <div className="flex items-center justify-between p-4 border-b border-gray-200">
            <div className="flex items-center gap-3">
              <button
                onClick={handleBackToList}
                className="md:hidden p-2 hover:bg-gray-100 rounded"
              >
                <ArrowLeft className="w-5 h-5 text-gray-600" />
              </button>
              <img
                src={contacts.find(c => c.id === selectedChat)?.avatar}
                alt="Avatar"
                className="w-10 h-10 rounded-full"
              />
              <div>
                <h3 className="font-medium text-gray-900">
                  Priya
                </h3>
                <div className="flex items-center gap-1 text-xs text-green-500">
                  <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span>Online</span>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {/* <button className="p-2 hover:bg-gray-100 rounded">
                <Phone className="w-5 h-5 text-blue-600" />
              </button> */}
              <div className="relative">
                <button 
                  onClick={() => setShowChatMenu(!showChatMenu)}
                  className="p-2 hover:bg-gray-100 rounded"
                >
                  <MoreVertical className="w-5 h-5 text-gray-600" />
                </button>
                
                {showChatMenu && (
                  <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-50">
                    <button className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100">
                      <Star className="w-4 h-4" />
                      <span className="text-sm">Shortlisted</span>
                    </button>
                    <button className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100">
                      <Share2 className="w-4 h-4" />
                      <span className="text-sm">Share</span>
                    </button>
                    <button onClick={() => setOpenReport(true)}  className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100">
                      <Flag className="w-4 h-4" />
                      <span className="text-sm">Report</span>
                    </button>
                    <button className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3">
                      <Ban className="w-4 h-4" />
                      <span className="text-sm">Block Profile</span>
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50 md:h-[400px]">
            {chatMessages[selectedChat]?.map((msg) => (
              <div key={msg.id}>
                {msg.isDate ? (
                  <div className="text-center text-xs text-gray-500 my-4">
                    {msg.text}
                  </div>
                ) : (
                  <div
                    className={`flex ${
                      msg.sender === 'me' ? 'justify-end' : 'justify-start'
                    }`}
                  >
                    <div
                      className={`max-w-xs md:max-w-md px-4 py-2 rounded-2xl ${
                        msg.sender === 'me'
                          ? 'bg-[#cbf5ea] text-gray-900 rounded-br-sm'
                          : 'bg-white text-gray-900 rounded-bl-sm'
                      }`}
                    >
                      <p className="text-sm">{msg.text}</p>
                      <div className='flex gap-1 items-center justify-end mt-1'>
                      {msg.time && (
                        <div className="flex items-center justify-end ">
                          <span className={`text-xs ${msg.sender === 'me' ? 'text-gray-900' : 'text-gray-500'}`}>
                            {msg.time}
                          </span>



                        </div>
                      )}


{msg.sender === 'me' && (
  <div className="flex items-center justify-end">
    <span className="text-xs text-blue-100">{msg.time}</span>
    {msg.read ? (
        <CheckCheck className="w-4 h-4 text-[#034E08]" />
    ) : (
      <Check className="w-4 h-4  text-[#034E08]" />
    )}
  </div>
)}




                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Message Input */}
          <div className="p-4 border-t border-gray-200 bg-white sticky bottom-0">
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                placeholder="Start Typing..."
                className="flex-1 px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:border-[#034E08]"
              />
              <button
                onClick={handleSendMessage}
                className="p-2.5 bg-[#034E08] text-white rounded-lg hover:bg-blue-600"
              >
                <Send className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Empty State */}
      {!selectedChat && !showCallHistory && (
        <div className="flex-1 hidden md:flex items-center justify-center bg-gray-50">
          <p className="text-gray-500">Select a conversation to start messaging</p>
        </div>
      )}
    </div>
    </>
   
  );
};

export default ChatUI;