import React, { useState, useEffect } from 'react';
import { Plus, Trash2, Edit2, Save, X, Search } from 'lucide-react';

const TodoApp = () => {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState('');
  const [searchTitle, setSearchTitle] = useState('');
  const [editingItem, setEditingItem] = useState(null);
  const [editTitle, setEditTitle] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  
  const API_BASE_URL = 'http://localhost:8080/api/todos';

 
  const fetchTodos = async () => {
    setLoading(true);
    setError('');
    try {
      const response = await fetch(API_BASE_URL);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      setTodos(data);
    } catch (err) {
      setError('Failed to fetch todos. Make sure your backend is running.');
      console.error('Error fetching todos:', err);
    } finally {
      setLoading(false);
    }
  };

  
  const addTodo = async () => {
    if (!newTodo.trim()) return;
    
    setLoading(true);
    setError('');
    try {
      const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ title: newTodo.trim() }),
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const updatedTodos = await response.json();
      setTodos(updatedTodos);
      setNewTodo('');
    } catch (err) {
      setError('Failed to add todo item.');
      console.error('Error adding todo:', err);
    } finally {
      setLoading(false);
    }
  };

  // Delete todo by title
  const deleteTodo = async (title) => {
    setLoading(true);
    setError('');
    try {
      const response = await fetch(`${API_BASE_URL}/${encodeURIComponent(title)}`, {
        method: 'DELETE',
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      // Refresh the todo list after deletion
      await fetchTodos();
    } catch (err) {
      setError('Failed to delete todo item.');
      console.error('Error deleting todo:', err);
    } finally {
      setLoading(false);
    }
  };

  // Update todo title
  const updateTodo = async (oldTitle, newTitle) => {
    if (!newTitle.trim()) return;
    
    setLoading(true);
    setError('');
    try {
      const response = await fetch(`${API_BASE_URL}?oldTitle=${encodeURIComponent(oldTitle)}&newTitle=${encodeURIComponent(newTitle)}`, {
        method: 'PUT',
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const updatedTodos = await response.json();
      setTodos(updatedTodos);
      setEditingItem(null);
      setEditTitle('');
    } catch (err) {
      setError('Failed to update todo item.');
      console.error('Error updating todo:', err);
    } finally {
      setLoading(false);
    }
  };

  // Search todos by title
  const searchTodos = async () => {
    if (!searchTitle.trim()) {
      fetchTodos();
      return;
    }
    
    setLoading(true);
    setError('');
    try {
      const response = await fetch(`${API_BASE_URL}/title/${encodeURIComponent(searchTitle)}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      setTodos(data);
    } catch (err) {
      setError('Failed to search todos.');
      console.error('Error searching todos:', err);
    } finally {
      setLoading(false);
    }
  };

  // Start editing a todo
  const startEdit = (todo) => {
    setEditingItem(todo.title);
    setEditTitle(todo.title);
  };

  // Cancel editing
  const cancelEdit = () => {
    setEditingItem(null);
    setEditTitle('');
  };

  // Handle key press for adding todos
  const handleAddKeyPress = (e) => {
    if (e.key === 'Enter') {
      addTodo();
    }
  };

  // Handle key press for editing todos
  const handleEditKeyPress = (e, oldTitle) => {
    if (e.key === 'Enter') {
      updateTodo(oldTitle, editTitle);
    } else if (e.key === 'Escape') {
      cancelEdit();
    }
  };

  // Handle key press for search
  const handleSearchKeyPress = (e) => {
    if (e.key === 'Enter') {
      searchTodos();
    }
  };

  // Load todos on component mount
  useEffect(() => {
    fetchTodos();
  }, []);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
      <div className="max-w-2xl mx-auto">
        <div className="bg-white rounded-lg shadow-lg p-6">
          <h1 className="text-3xl font-bold text-gray-800 mb-6 text-center">
            Todo List
          </h1>
          
          {/* Error Message */}
          {error && (
            <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
              {error}
            </div>
          )}
          
          {/* Add Todo Section */}
          <div className="mb-6">
            <div className="flex gap-2">
              <input
                type="text"
                value={newTodo}
                onChange={(e) => setNewTodo(e.target.value)}
                onKeyPress={handleAddKeyPress}
                placeholder="Add a new todo item..."
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                disabled={loading}
              />
              <button
                onClick={addTodo}
                disabled={loading || !newTodo.trim()}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <Plus size={16} />
                Add
              </button>
            </div>
          </div>

          {/* Search Section */}
          <div className="mb-6">
            <div className="flex gap-2">
              <input
                type="text"
                value={searchTitle}
                onChange={(e) => setSearchTitle(e.target.value)}
                onKeyPress={handleSearchKeyPress}
                placeholder="Search todos by title..."
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
                disabled={loading}
              />
              <button
                onClick={searchTodos}
                disabled={loading}
                className="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <Search size={16} />
                Search
              </button>
              <button
                onClick={fetchTodos}
                disabled={loading}
                className="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                All
              </button>
            </div>
          </div>

          {/* Loading State */}
          {loading && (
            <div className="text-center py-4">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
            </div>
          )}

          {/* Todo List */}
          <div className="space-y-2">
            {todos.length === 0 && !loading ? (
              <div className="text-center py-8 text-gray-500">
                No todos found. Add one above!
              </div>
            ) : (
              todos.map((todo, index) => (
                <div
                  key={index}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors"
                >
                  {editingItem === todo.title ? (
                    <div className="flex-1 flex items-center gap-2">
                      <input
                        type="text"
                        value={editTitle}
                        onChange={(e) => setEditTitle(e.target.value)}
                        onKeyPress={(e) => handleEditKeyPress(e, todo.title)}
                        className="flex-1 px-3 py-1 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                        autoFocus
                      />
                      <button
                        onClick={() => updateTodo(todo.title, editTitle)}
                        className="p-1 text-green-600 hover:text-green-800"
                        title="Save"
                      >
                        <Save size={16} />
                      </button>
                      <button
                        onClick={cancelEdit}
                        className="p-1 text-gray-600 hover:text-gray-800"
                        title="Cancel"
                      >
                        <X size={16} />
                      </button>
                    </div>
                  ) : (
                    <>
                      <span className="flex-1 text-gray-800">{todo.title}</span>
                      <div className="flex gap-2">
                        <button
                          onClick={() => startEdit(todo)}
                          className="p-1 text-blue-600 hover:text-blue-800"
                          title="Edit"
                        >
                          <Edit2 size={16} />
                        </button>
                        <button
                          onClick={() => deleteTodo(todo.title)}
                          className="p-1 text-red-600 hover:text-red-800"
                          title="Delete"
                        >
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </>
                  )}
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default TodoApp;    please change this from tailwind css to an acceptable styling format that react can use, perhaps just style:{}