import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Share2, Copy, QrCode, Twitter, Facebook, Linkedin, Home } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import QRCode from 'qrcode';
import { validateShareData, rateLimiter } from '@/utils/security';

interface SocialShareProps {
  title: string;
  description: string;
  url?: string;
}

const SocialShare: React.FC<SocialShareProps> = ({ 
  title, 
  description, 
  url = window.location.href 
}) => {
  const [qrCodeDataUrl, setQrCodeDataUrl] = useState<string>('');
  const [isOpen, setIsOpen] = useState(false);
  const { toast } = useToast();

  // Validate and sanitize share data
  const shareData = validateShareData(title, description, url);

  useEffect(() => {
    if (isOpen) {
      QRCode.toDataURL(shareData.url, {
        width: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        }
      }).then(setQrCodeDataUrl).catch(() => {
        toast({
          title: "Error",
          description: "Failed to generate QR code",
          variant: "destructive",
        });
      });
    }
  }, [shareData.url, isOpen, toast]);

  const copyToClipboard = async (text: string) => {
    console.log('Copy to clipboard called with text:', text);
    
    if (!rateLimiter.isAllowed('clipboard', 10, 60000)) {
      console.log('Rate limit exceeded for clipboard');
      toast({
        title: "Too many attempts",
        description: "Please wait before copying again",
        variant: "destructive",
      });
      return;
    }

    try {
      console.log('Attempting to copy to clipboard...');
      
      // Check if clipboard API is available
      if (!navigator.clipboard) {
        console.log('Clipboard API not available, using fallback');
        // Fallback for older browsers or insecure contexts
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
          const success = document.execCommand('copy');
          console.log('Fallback copy result:', success);
          if (success) {
            toast({
              title: "Copied!",
              description: "Link copied to clipboard",
            });
          } else {
            throw new Error('Copy command failed');
          }
        } catch (err) {
          console.error('Fallback copy failed:', err);
          toast({
            title: "Error",
            description: "Failed to copy to clipboard",
            variant: "destructive",
          });
        } finally {
          document.body.removeChild(textArea);
        }
        return;
      }

      console.log('Using modern clipboard API');
      await navigator.clipboard.writeText(text);
      console.log('Copy successful');
      toast({
        title: "Copied!",
        description: "Link copied to clipboard",
      });
    } catch (err) {
      console.error('Copy failed:', err);
      toast({
        title: "Error",
        description: "Failed to copy to clipboard. Please copy the URL manually.",
        variant: "destructive",
      });
    }
  };

  const copyQRCode = async () => {
    if (!rateLimiter.isAllowed('qr-copy', 5, 60000)) {
      toast({
        title: "Too many attempts",
        description: "Please wait before copying again",
        variant: "destructive",
      });
      return;
    }

    try {
      const response = await fetch(qrCodeDataUrl);
      const blob = await response.blob();
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': blob })
      ]);
      toast({
        title: "QR Code Copied!",
        description: "QR code image copied to clipboard",
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "Failed to copy QR code",
        variant: "destructive",
      });
    }
  };

  const shareLinks = {
    twitter: `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareData.title)}&url=${encodeURIComponent(shareData.url)}`,
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareData.url)}`,
    linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareData.url)}`
  };

  const handleSocialShare = (platform: string, url: string) => {
    if (!rateLimiter.isAllowed('social-share', 10, 60000)) {
      toast({
        title: "Too many attempts",
        description: "Please wait before sharing again",
        variant: "destructive",
      });
      return;
    }
    
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  return (
    <div className="border-t border-border pt-6 mt-8">
      <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
        
        <div className="flex items-center gap-2">
          {/* Social sharing buttons */}
          <Button
            variant="outline"
            size="sm"
            onClick={() => handleSocialShare('twitter', shareLinks.twitter)}
            className="flex items-center gap-2"
          >
            <Twitter className="w-4 h-4" />
            <span className="hidden sm:inline">Twitter</span>
          </Button>
          
          <Button
            variant="outline"
            size="sm"
            onClick={() => handleSocialShare('facebook', shareLinks.facebook)}
            className="flex items-center gap-2"
          >
            <Facebook className="w-4 h-4" />
            <span className="hidden sm:inline">Facebook</span>
          </Button>
          
          <Button
            variant="outline"
            size="sm"
            onClick={() => handleSocialShare('linkedin', shareLinks.linkedin)}
            className="flex items-center gap-2"
          >
            <Linkedin className="w-4 h-4" />
            <span className="hidden sm:inline">LinkedIn</span>
          </Button>
          
          {/* Copy link button */}
          <Button
            variant="outline"
            size="sm"
            onClick={() => copyToClipboard(shareData.url)}
            className="flex items-center gap-2"
          >
            <Copy className="w-4 h-4" />
            <span className="hidden sm:inline">Copy Link</span>
          </Button>
          
          {/* QR Code dialog */}
          <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogTrigger asChild>
              <Button variant="outline" size="sm" className="flex items-center gap-2">
                <QrCode className="w-4 h-4" />
                <span className="hidden sm:inline">QR Code</span>
              </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-md">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <QrCode className="w-5 h-5" />
                  QR Code
                </DialogTitle>
              </DialogHeader>
              <div className="flex flex-col items-center space-y-4">
                {qrCodeDataUrl && (
                  <Card className="p-4 bg-white">
                    <CardContent className="p-0">
                      <img 
                        src={qrCodeDataUrl} 
                        alt="QR Code for this interactive" 
                        className="w-48 h-48"
                      />
                    </CardContent>
                  </Card>
                )}
                <div className="text-center space-y-2">
                  <p className="text-sm text-muted-foreground">Scan to open this interactive</p>
                  <Button onClick={copyQRCode} variant="outline" size="sm">
                    <Copy className="w-4 h-4 mr-2" />
                    Copy QR Code
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>
      
      {/* Centered Home Icon */}
      <div className="flex justify-center mt-4">
        <Home 
          className="w-6 h-6 text-muted-foreground hover:text-foreground cursor-pointer transition-colors" 
          onClick={() => window.location.href = '/'}
        />
      </div>
    </div>
  );
};

export default SocialShare;