import React, { useState, useEffect } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Button,
  Box,
  IconButton,
  Radio,
  RadioGroup,
  FormControlLabel,
  FormControl,
  FormLabel,
  Slide,
  Divider
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import CookieIcon from '@mui/icons-material/Cookie';
import consentService, { CONSENT_LEVELS } from '../services/consentService';

/**
 * Cookie consent popup component
 * Shows a popup for cookie consent on first visit and manages Clarity tracking
 */
const CookieConsentPopup = () => {
  const [open, setOpen] = useState(false);
  const [consentLevel, setConsentLevel] = useState(CONSENT_LEVELS.NECESSARY);

  useEffect(() => {
    // Check if user has already set cookie preferences
    const storedConsent = consentService.getStoredConsent();
    
    if (!storedConsent) {
      // First visit, show the popup
      setOpen(true);
    } else {
      // Apply stored consent settings
      setConsentLevel(storedConsent.level);
      consentService.applyConsentSettings(storedConsent.level);
    }
  }, []);

  // Handle consent level change
  const handleConsentLevelChange = (event) => {
    setConsentLevel(event.target.value);
  };

  // Save user preferences and close popup
  const handleSave = () => {
    consentService.saveConsent(consentLevel);
    setOpen(false);
  };

  // Accept all cookies
  const handleAcceptAll = () => {
    const allConsent = CONSENT_LEVELS.ALL;
    setConsentLevel(allConsent);
    consentService.saveConsent(allConsent);
    setOpen(false);
  };

  // Accept only necessary cookies
  const handleNecessaryOnly = () => {
    const necessaryOnly = CONSENT_LEVELS.NECESSARY;
    setConsentLevel(necessaryOnly);
    consentService.saveConsent(necessaryOnly);
    setOpen(false);
  };

  // Reopen the consent popup (for testing or if user wants to change settings)
  // This function can be exposed via a preferences button somewhere in your app
  const reopenConsentPopup = () => {
    setOpen(true);
  };

  if (!open) return null;

  return (
    <Slide direction="up" in={open} mountOnEnter unmountOnExit>
      <Card 
        sx={{ 
          position: 'fixed', 
          bottom: 20, 
          right: 20, 
          maxWidth: 400,
          boxShadow: 4,
          zIndex: 9999
        }}
      >
        <CardContent>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <CookieIcon color="primary" fontSize="small" sx={{ mr: 1 }} />
              <Typography variant="h6">Cookie Settings</Typography>
            </Box>
            <IconButton size="small" onClick={() => setOpen(false)}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </Box>
          
          <Typography variant="body2" color="text.secondary" paragraph>
            We use cookies to enhance your browsing experience, provide personalized content, 
            and analyze our traffic. Please choose your privacy settings below.
          </Typography>
          
          <FormControl component="fieldset" sx={{ my: 2 }}>
            <FormLabel component="legend">Privacy Settings</FormLabel>
            <RadioGroup
              value={consentLevel}
              onChange={handleConsentLevelChange}
            >
              <FormControlLabel 
                value={CONSENT_LEVELS.NECESSARY} 
                control={<Radio />} 
                label={
                  <Typography variant="body2">
                    <strong>Necessary Cookies Only</strong> - Essential for website functionality
                  </Typography>
                } 
              />
              <FormControlLabel 
                value={CONSENT_LEVELS.FUNCTIONAL} 
                control={<Radio />} 
                label={
                  <Typography variant="body2">
                    <strong>Functional Cookies</strong> - For enhanced functionality and preferences
                  </Typography>
                } 
              />
              <FormControlLabel 
                value={CONSENT_LEVELS.ANALYTICS} 
                control={<Radio />} 
                label={
                  <Typography variant="body2">
                    <strong>Analytics Cookies</strong> - To understand how you use our website
                  </Typography>
                } 
              />
              <FormControlLabel 
                value={CONSENT_LEVELS.ALL} 
                control={<Radio />} 
                label={
                  <Typography variant="body2">
                    <strong>All Cookies</strong> - Accept all cookies for the best experience
                  </Typography>
                } 
              />
            </RadioGroup>
          </FormControl>
          
          <Divider sx={{ my: 2 }} />
          
          <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
            <Button 
              variant="outlined" 
              onClick={handleNecessaryOnly}
              size="small"
            >
              Necessary Only
            </Button>
            <Box>
              <Button 
                variant="outlined" 
                onClick={handleSave}
                sx={{ mr: 1 }}
                size="small"
              >
                Save Preferences
              </Button>
              <Button 
                variant="contained" 
                onClick={handleAcceptAll}
                size="small"
              >
                Accept All
              </Button>
            </Box>
          </Box>
        </CardContent>
      </Card>
    </Slide>
  );
};

// Expose reopen function for others to use
export const reopenCookieConsent = () => {
  const consentElement = document.getElementById('cookie-consent-reopen');
  if (consentElement) {
    consentElement.click();
  }
};

export default CookieConsentPopup;