import { useEffect, useState } from 'react';
import axios from 'axios';

function Items() {
  const [items, setItems] = useState([]);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [editId, setEditId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  const getAuthHeaders = () => ({
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  });

  const handleRetrieve = async () => {
    try {
      const response = await axios.get('http://localhost:5000/api/items', {
        headers: getAuthHeaders(),
      });
      setItems(response.data.items);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load items');
      console.error('Server Error:', err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    handleRetrieve();
  }, []);

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this item?')) return;

    setError('');
    try {
      await axios.delete(`http://localhost:5000/api/items/${id}`, {
        headers: getAuthHeaders(),
      });
      setMessage('Item deleted successfully');
      if (editId === id) {
        setTitle('');
        setDescription('');
        setEditId(null);
      }
      handleRetrieve();
    } catch (err) {
      setError(err.response?.data?.message || 'Delete failed');
      console.error('Server Error:', err.response?.data || err.message);
    }
  };

  const handleEdit = (item) => {
    setEditId(item._id);
    setTitle(item.title);
    setDescription(item.description || '');
    setMessage('');
    setError('');
  };

  const handleUpdate = async (e) => {
    e.preventDefault();
    if (!editId) return;

    setSubmitting(true);
    setError('');
    try {
      await axios.put(
        `http://localhost:5000/api/items/${editId}`,
        { title, description },
        { headers: getAuthHeaders() },
      );
      setMessage('Item updated successfully');
      setTitle('');
      setDescription('');
      setEditId(null);
      handleRetrieve();
    } catch (err) {
      setError(err.response?.data?.message || 'Update failed');
      console.error('Server Error:', err.response?.data || err.message);
    } finally {
      setSubmitting(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setMessage('');

    if (editId) {
      await handleUpdate(e);
      return;
    }

    setSubmitting(true);
    try {
      await axios.post(
        'http://localhost:5000/api/items',
        { title, description },
        { headers: getAuthHeaders() },
      );
      setMessage('Item added successfully');
      setTitle('');
      setDescription('');
      handleRetrieve();
    } catch (err) {
      setError(err.response?.data?.message || 'Adding item failed');
      console.error('Server Error:', err.response?.data || err.message);
    } finally {
      setSubmitting(false);
    }
  };

  const handleCancelEdit = () => {
    setTitle('');
    setDescription('');
    setEditId(null);
    setError('');
    setMessage('');
  };

  return (
    <div className="max-w-3xl">
      <h1 className="text-2xl font-bold text-slate-800 mb-6">Items</h1>

      {message && (
        <p className="mb-4 text-sm text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2">
          {message}
        </p>
      )}

      {error && (
        <p className="mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">
          {error}
        </p>
      )}

      <section className="bg-white rounded-lg shadow-md p-6 mb-8">
        <h2 className="text-lg font-semibold text-slate-800 mb-4">
          {editId ? 'Edit item' : 'New item'}
        </h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="title" className="block text-sm font-medium text-slate-700 mb-1">
              Title
            </label>
            <input
              id="title"
              name="title"
              type="text"
              required
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full border border-slate-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label
              htmlFor="description"
              className="block text-sm font-medium text-slate-700 mb-1"
            >
              Description
            </label>
            <textarea
              id="description"
              name="description"
              rows={3}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="w-full border border-slate-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div className="flex gap-2">
            <button
              type="submit"
              disabled={submitting}
              className="bg-blue-600 text-white font-medium px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
            >
              {submitting ? 'Saving...' : editId ? 'Update' : 'Create'}
            </button>
            {editId && (
              <button
                type="button"
                onClick={handleCancelEdit}
                className="border border-slate-300 text-slate-700 font-medium px-4 py-2 rounded hover:bg-slate-50"
              >
                Cancel
              </button>
            )}
          </div>
        </form>
      </section>

      <section>
        <h2 className="text-lg font-semibold text-slate-800 mb-4">Your items</h2>
        {loading ? (
          <p className="text-slate-500">Loading...</p>
        ) : items.length === 0 ? (
          <p className="text-slate-500">No items yet. Create one above.</p>
        ) : (
          <ul className="space-y-3">
            {items.map((item) => (
              <li
                key={item._id}
                className="bg-white rounded-lg shadow-sm border border-slate-200 p-4 flex justify-between gap-4"
              >
                <div>
                  <h3 className="font-medium text-slate-800">{item.title}</h3>
                  {item.description && (
                    <p className="text-sm text-slate-600 mt-1">{item.description}</p>
                  )}
                </div>
                <div className="flex gap-2 shrink-0">
                  <button
                    type="button"
                    onClick={() => handleEdit(item)}
                    className="text-sm text-blue-600 hover:underline"
                  >
                    Edit
                  </button>
                  <button
                    type="button"
                    onClick={() => handleDelete(item._id)}
                    className="text-sm text-red-600 hover:underline"
                  >
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}

export default Items;
