import React, { useState } from 'react';
import { useChatHistory } from '../hooks/useChatHistory';

const History: React.FC = () => {
  const [chatHistory, setSelectedIndex] = useChatHistory()
  const [isEditing, setIsEditing] = useState(false);
  const [inputValue, setInputValue] = useState<string>('');


  const handleEditButtonClick = () => {
    setIsEditing(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleSaveButtonClick = () => {
    setIsEditing(false);
    chatHistory.chats.push({ name: inputValue, messages: [], timestamp: 5 })
    setInputValue("")
  };

  const handleHistoryClick = (index: number) => {
    setSelectedIndex(index)
    console.log("index",index);
    
  }


  return (
    <div className="history-background">
      <div className="history">
        <ul>
          {/* Populate with history items */}
          {chatHistory.chats.map((chats, index) => (
            <li key={index}>
              <a href="#" onClick={() => handleHistoryClick(index)}>
                {chatHistory.chats[index].name}
              </a>
            </li>
          ))}
          <li>
            {isEditing ? (
              <div className="input-container">
                <input
                  type="text"
                  value={inputValue}
                  onChange={handleInputChange}
                  placeholder="Enter text"
                  className="chat-input"
                />
                <button onClick={handleSaveButtonClick} className="save-btn">
                  Save
                </button>
              </div>
            ) : (
              <button onClick={handleEditButtonClick} className="newChat-btn">
                New Chat
              </button>
            )}
          </li>
        </ul>
      </div>
    </div>
  );  
};

export default History;
