import React, { useState, useEffect } from 'react';
import { db } from '../firebase';
import { collection, addDoc, getDocs } from 'firebase/firestore';
import './ManageAds.css';
import Navbar from '../components/Navbar';

const ManageAds = () => {
  const [ads, setAds] = useState([]);
  const [newAd, setNewAd] = useState({ title: '', description: '', imageUrl: '' });

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

  const fetchAds = async () => {
    const querySnapshot = await getDocs(collection(db, 'ads'));
    const adsData = querySnapshot.docs.map(doc => doc.data());
    setAds(adsData);
  };

  const handleAddAd = async () => {
    await addDoc(collection(db, 'ads'), newAd);
    fetchAds();
  };

  return (
    <div>
      <Navbar />
      <div className="container mt-5">
        <h4>Manage Ads</h4>
        <div className="mb-4">
          <div className="mb-3">
            <label>Title</label>
            <input
              type="text"
              value={newAd.title}
              onChange={(e) => setNewAd({ ...newAd, title: e.target.value })}
              className="form-control"
            />
          </div>
          <div className="mb-3">
            <label>Description</label>
            <input
              type="text"
              value={newAd.description}
              onChange={(e) => setNewAd({ ...newAd, description: e.target.value })}
              className="form-control"
            />
          </div>
          <div className="mb-3">
            <label>Image URL</label>
            <input
              type="text"
              value={newAd.imageUrl}
              onChange={(e) => setNewAd({ ...newAd, imageUrl: e.target.value })}
              className="form-control"
            />
          </div>
          <button onClick={handleAddAd} className="btn btn-primary">Add Ad</button>
        </div>
        <div>
          {ads.map((ad, index) => (
            <div key={index} className="mb-3">
              <h5>{ad.title}</h5>
              <p>{ad.description}</p>
              <img src={ad.imageUrl} alt={ad.title} className="img-fluid" />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default ManageAds;
