import React, { useState, useEffect } from 'react';
import { Button, SxProps, Theme, Snackbar, Alert } from '@mui/material';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';

interface CopyLinkButtonProps {
  linkToCopy: string;
  sx?: SxProps<Theme>;
}

const CopyLinkButton: React.FC<CopyLinkButtonProps> = ({ linkToCopy, sx }) => {
  const [copied, setCopied] = useState(false);
  const [alertOpen, setAlertOpen] = useState(false);
  const [alertMessage, setAlertMessage] = useState('');
  const [alertSeverity, setAlertSeverity] = useState<'error' | 'warning' | 'info' | 'success'>('error');

  const handleCopy = async () => {
    if (!navigator.clipboard || !navigator.clipboard.writeText) {
      setAlertMessage('Clipboard API not supported in this browser. Please copy the link manually.');
      setAlertSeverity('warning');
      setAlertOpen(true);
      console.warn('Clipboard API not supported.');
      return;
    }

    try {
      await navigator.clipboard.writeText(linkToCopy);
      setCopied(true);
      setAlertMessage('Link copied to clipboard!');
      setAlertSeverity('success');
      setAlertOpen(true);
      console.log('Link copied to clipboard:', linkToCopy);
    } catch (err) {
      console.error('Failed to copy link:', err);
      setAlertMessage('Failed to copy the link. Please try again or copy manually.');
      setAlertSeverity('error');
      setAlertOpen(true);
    }
  };

  const handleCloseAlert = (event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === 'clickaway') {
      return;
    }
    setAlertOpen(false);
  };

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (copied) {
      timer = setTimeout(() => {
        setCopied(false);
      }, 3000); // Revert after 3 seconds
    }
    return () => clearTimeout(timer);
  }, [copied]);

  return (
    <>
      <Button
        variant="outlined"
        onClick={handleCopy}
        startIcon={copied ? <CheckCircleOutlineIcon color="success" /> : <ContentCopyIcon />}
        color={copied ? "success" : "primary"}
        sx={{
          minWidth: 120,
          textTransform: 'none',
          ...(sx ? sx : {}),
        }}
      >
        {copied ? 'Copied!' : 'Copy Link'}
      </Button>
      <Snackbar open={alertOpen} autoHideDuration={6000} onClose={handleCloseAlert} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} sx={{ mt: 8 }}>
        <Alert onClose={handleCloseAlert} severity={alertSeverity} sx={{ width: '100%' }}>
          {alertMessage}
        </Alert>
      </Snackbar>
    </>
  );
};

export default CopyLinkButton;
