import { useEffect, useState } from 'react';
import AdminLayout from '../../components/AdminLayout';
import { getAboutCards, createAboutCard, updateAboutCard, deleteAboutCard } from '../../utils/api';

const AdminAbout = () => {
  const [cards, setCards] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState(null);
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    order: 0
  });

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

  const loadCards = async () => {
    try {
      const response = await getAboutCards();
      setCards(response.data);
    } catch (error) {
      console.error('Error loading about cards:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await updateAboutCard(editingId, formData);
      } else {
        await createAboutCard(formData);
      }
      await loadCards();
      resetForm();
    } catch (error) {
      alert('Failed to save about card');
    }
  };

  const handleEdit = (card) => {
    setEditingId(card.id);
    setFormData({
      title: card.title,
      description: card.description,
      order: card.order
    });
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this card?')) return;
    try {
      await deleteAboutCard(id);
      await loadCards();
    } catch (error) {
      alert('Failed to delete card');
    }
  };

  const resetForm = () => {
    setEditingId(null);
    setFormData({ title: '', description: '', order: 0 });
  };

  if (loading) {
    return <AdminLayout><div className="text-center py-20">Loading...</div></AdminLayout>;
  }

  return (
    <AdminLayout>
      <h1 className="text-3xl font-extrabold text-gray-900 mb-8">Manage About Section</h1>

      <div className="grid md:grid-cols-2 gap-8">
        {/* Form */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-bold mb-6">{editingId ? 'Edit Card' : 'Add New Card'}</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Title</label>
              <input 
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({...formData, title: e.target.value})}
                className="w-full px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
                required
              />
            </div>
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Description</label>
              <textarea 
                value={formData.description}
                onChange={(e) => setFormData({...formData, description: e.target.value})}
                className="w-full px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
                rows="4"
                required
              />
            </div>
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Order</label>
              <input 
                type="number"
                value={formData.order}
                onChange={(e) => setFormData({...formData, order: parseInt(e.target.value)})}
                className="w-full px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div className="flex gap-3">
              <button type="submit" className="bg-blue-600 text-white px-6 py-3 rounded-xl font-bold hover:bg-blue-700 transition">
                {editingId ? 'Update' : 'Add'}
              </button>
              {editingId && (
                <button type="button" onClick={resetForm} className="bg-gray-200 px-6 py-3 rounded-xl font-bold hover:bg-gray-300 transition">
                  Cancel
                </button>
              )}
            </div>
          </form>
        </div>

        {/* List */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-bold mb-6">Current Cards</h2>
          <div className="space-y-3">
            {cards.map((card) => (
              <div key={card.id} className="border border-gray-200 rounded-xl p-4">
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="font-bold text-gray-900">{card.title}</h3>
                    <p className="text-sm text-gray-600 mt-1">{card.description}</p>
                    <p className="text-xs text-gray-400 mt-2">Order: {card.order}</p>
                  </div>
                  <div className="flex gap-2">
                    <button onClick={() => handleEdit(card)} className="text-blue-600 hover:text-blue-700 font-semibold">
                      Edit
                    </button>
                    <button onClick={() => handleDelete(card.id)} className="text-red-600 hover:text-red-700 font-semibold">
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
};

export default AdminAbout;
