import React, { useState } from 'react';
import { Post } from '../types';
import { XIcon } from './icons/XIcon';

interface SharePostModalProps {
  post: Post;
  onClose: () => void;
}

const SharePostModal: React.FC<SharePostModalProps> = ({ post, onClose }) => {
  const [copied, setCopied] = useState(false);
  // In a real app, this URL would be the actual public URL of the post.
  const postUrl = `${window.location.origin}/post/${post.id}`;
  const shareText = `Check out this post on TagCraze: ${post.caption}`;

  const socialLinks = {
    twitter: `https://twitter.com/intent/tweet?url=${encodeURIComponent(postUrl)}&text=${encodeURIComponent(shareText)}`,
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(postUrl)}`,
    whatsapp: `https://api.whatsapp.com/send?text=${encodeURIComponent(shareText + ' ' + postUrl)}`,
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(postUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000); // Reset after 2 seconds
    });
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-background rounded-lg shadow-xl w-full max-w-sm border border-accent">
        <div className="flex justify-between items-center p-4 border-b border-muted">
          <h2 className="text-lg font-bold">Share Post</h2>
          <button onClick={onClose} className="text-secondary hover:text-foreground">
            <XIcon className="w-6 h-6" />
          </button>
        </div>
        <div className="p-6 space-y-4">
          <a href={socialLinks.facebook} target="_blank" rel="noopener noreferrer" className="block w-full text-center bg-blue-600 text-white font-bold py-2.5 rounded-lg hover:bg-blue-700 transition-colors">
            Share on Facebook
          </a>
          <a href={socialLinks.twitter} target="_blank" rel="noopener noreferrer" className="block w-full text-center bg-black text-white font-bold py-2.5 rounded-lg hover:bg-gray-800 transition-colors">
            Share on X (Twitter)
          </a>
          <a href={socialLinks.whatsapp} target="_blank" rel="noopener noreferrer" className="block w-full text-center bg-green-500 text-white font-bold py-2.5 rounded-lg hover:bg-green-600 transition-colors">
            Share on WhatsApp
          </a>
          <div className="relative">
            <input
              type="text"
              readOnly
              value={postUrl}
              className="w-full bg-muted border border-accent rounded-lg p-2 pr-20 text-sm"
            />
            <button onClick={copyToClipboard} className="absolute right-1 top-1/2 -translate-y-1/2 bg-primary text-primary-foreground text-xs font-semibold px-3 py-1.5 rounded-md hover:opacity-90">
              {copied ? 'Copied!' : 'Copy'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SharePostModal;
