import { useEffect, useState } from 'react';
import AdminLayout from '../../components/AdminLayout';
import { getBrands, createBrand, updateBrand, deleteBrand } from '../../utils/api';

const AdminBrands = () => {
  const [brands, setBrands] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    logo_url: '',
    alt_text: '',
    order: 0
  });

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

  const loadBrands = async () => {
    try {
      const response = await getBrands();
      setBrands(response.data);
    } catch (error) {
      console.error('Error loading brands:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await updateBrand(editingId, formData);
      } else {
        await createBrand(formData);
      }
      await loadBrands();
      resetForm();
    } catch (error) {
      alert('Failed to save brand');
    }
  };

  const handleEdit = (brand) => {
    setEditingId(brand.id);
    setFormData({
      name: brand.name,
      logo_url: brand.logo_url,
      alt_text: brand.alt_text,
      order: brand.order
    });
  };

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

  const resetForm = () => {
    setEditingId(null);
    setFormData({ name: '', logo_url: '', alt_text: '', 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 Brand Partners</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 Brand' : 'Add New Brand'}</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Brand Name</label>
              <input 
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({...formData, name: 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">Logo URL (relative path)</label>
              <input 
                type="text"
                value={formData.logo_url}
                onChange={(e) => setFormData({...formData, logo_url: e.target.value})}
                className="w-full px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
                placeholder="assets/img/clients/brand.png"
                required
              />
            </div>
            <div>
              <label className="block text-gray-700 font-semibold mb-2">Alt Text</label>
              <input 
                type="text"
                value={formData.alt_text}
                onChange={(e) => setFormData({...formData, alt_text: e.target.value})}
                className="w-full px-4 py-3 border rounded-xl focus:ring-2 focus:ring-blue-500"
                placeholder="Service Resmi Brand"
                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 Brands</h2>
          <div className="space-y-3">
            {brands.map((brand) => (
              <div key={brand.id} className="border border-gray-200 rounded-xl p-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <img src={`/${brand.logo_url}`} alt={brand.alt_text} className="w-20 h-12 object-contain" />
                    <div>
                      <h3 className="font-bold text-gray-900">{brand.name}</h3>
                      <p className="text-xs text-gray-400">Order: {brand.order}</p>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button onClick={() => handleEdit(brand)} className="text-blue-600 hover:text-blue-700 font-semibold">
                      Edit
                    </button>
                    <button onClick={() => handleDelete(brand.id)} className="text-red-600 hover:text-red-700 font-semibold">
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
};

export default AdminBrands;
