import React, { useState, useEffect } from 'react';
import { Container, Button, Typography, Box, TextField, Dialog, IconButton } from '@mui/material';
import { collection, addDoc, getDocs, deleteDoc, doc, updateDoc } from 'firebase/firestore';
import { db, storage } from '../firebase';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import Navbar from '../components/Navbar';
import './ManageAds.css';

const ManageAds = () => {
  const [open, setOpen] = useState(false);
  const [adName, setAdName] = useState('');
  const [adDescription, setAdDescription] = useState('');
  const [file, setFile] = useState(null);
  const [ads, setAds] = useState([]);
  const [editAdId, setEditAdId] = useState(null);

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

    fetchAds();
  }, []);

  const handleAddAd = async () => {
    if (!file) return;

    const storageRef = ref(storage, `ads/${file.name}`);
    await uploadBytes(storageRef, file);
    const fileURL = await getDownloadURL(storageRef);

    if (editAdId) {
      const adRef = doc(db, 'ads', editAdId);
      await updateDoc(adRef, {
        name: adName,
        description: adDescription,
        fileURL,
      });
      setEditAdId(null);
    } else {
      await addDoc(collection(db, 'ads'), {
        name: adName,
        description: adDescription,
        fileURL,
      });
    }

    setOpen(false);
    setAdName('');
    setAdDescription('');
    setFile(null);

    const querySnapshot = await getDocs(collection(db, 'ads'));
    const adsList = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    setAds(adsList);
  };

  const handleDeleteAd = async (id) => {
    await deleteDoc(doc(db, 'ads', id));
    const querySnapshot = await getDocs(collection(db, 'ads'));
    const adsList = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    setAds(adsList);
  };

  const handleEditAd = (ad) => {
    setAdName(ad.name);
    setAdDescription(ad.description);
    setFile(null);
    setEditAdId(ad.id);
    setOpen(true);
  };

  return (
    <div className="manage-ads">
      <Navbar />
      <Container className="manage-ads-container">
        <Typography variant="h4" className="manage-ads-header">Manage Ads</Typography>
        <Button variant="contained" color="primary" className="add-ad-button" onClick={() => setOpen(true)}>Add Ad</Button>
        <Box className="manage-ads-list">
          {ads.map(ad => (
            <Box key={ad.id} className="ad-item">
              {ad.fileURL && (ad.fileURL.includes('.mp4') ? (
                <video src={ad.fileURL} controls className="ad-item-media" />
              ) : (
                <img src={ad.fileURL} alt={ad.name} className="ad-item-media" />
              ))}
              <Box>
                <Typography variant="h6">{ad.name}</Typography>
                <Typography>{ad.description}</Typography>
              </Box>
              <Box className="ad-item-actions">
                <IconButton onClick={() => handleEditAd(ad)}>
                  <EditIcon />
                </IconButton>
                <IconButton onClick={() => handleDeleteAd(ad.id)}>
                  <DeleteIcon />
                </IconButton>
              </Box>
            </Box>
          ))}
        </Box>
        <Dialog open={open} onClose={() => setOpen(false)} className="add-ad-dialog">
          <Box p={2}>
            <Typography variant="h6">{editAdId ? 'Edit Ad' : 'Add New Ad'}</Typography>
            <TextField
              label="Ad Name"
              value={adName}
              onChange={(e) => setAdName(e.target.value)}
              fullWidth
              margin="normal"
            />
            <TextField
              label="Ad Description"
              value={adDescription}
              onChange={(e) => setAdDescription(e.target.value)}
              fullWidth
              margin="normal"
              multiline
              rows={4}
            />
            <input
              type="file"
              onChange={(e) => setFile(e.target.files[0])}
            />
            <Button variant="contained" color="primary" onClick={handleAddAd} fullWidth>
              {editAdId ? 'Update Ad' : 'Add Ad'}
            </Button>
          </Box>
        </Dialog>
      </Container>
    </div>
  );
};

export default ManageAds;
