'use client';

import { useState } from 'react';
import { Share2, Link, Twitter, Facebook, Mail, Check, Copy, MessageCircle } from 'lucide-react';

interface ShareButtonProps {
  referralLink: string;
  referralCode: string;
}

export function ShareButton({ referralLink, referralCode }: ShareButtonProps) {
  const [copied, setCopied] = useState(false);
  const [showOptions, setShowOptions] = useState(false);

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const shareLinks = [
    {
      name: 'Copy Link',
      icon: Link,
      action: () => copyToClipboard(referralLink),
      color: 'text-blue-400 hover:bg-blue-500/10',
    },
    {
      name: 'Twitter',
      icon: Twitter,
      action: () => window.open(
        `https://twitter.com/intent/tweet?text=${encodeURIComponent(`Join me on this platform! Use my referral code: ${referralCode}\n\n${referralLink}`)}`,
        '_blank',
      ),
      color: 'text-sky-400 hover:bg-sky-500/10',
    },
    {
      name: 'Facebook',
      icon: Facebook,
      action: () => window.open(
        `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(referralLink)}`,
        '_blank',
      ),
      color: 'text-blue-600 hover:bg-blue-600/10',
    },
    {
      name: 'Email',
      icon: Mail,
      action: () => window.open(
        `mailto:?subject=${encodeURIComponent('Join me on this platform')}&body=${encodeURIComponent(`Use my referral code ${referralCode} to sign up: ${referralLink}`)}`,
        '_blank',
      ),
      color: 'text-amber-400 hover:bg-amber-500/10',
    },
    {
      name: 'WhatsApp',
      icon: MessageCircle,
      action: () => window.open(
        `https://wa.me/?text=${encodeURIComponent(`Join me on this platform! Use my referral code: ${referralCode}\n\n${referralLink}`)}`,
        '_blank',
      ),
      color: 'text-emerald-400 hover:bg-emerald-500/10',
    },
  ];

  return (
    <div className="relative">
      <button
        onClick={() => setShowOptions(!showOptions)}
        className="flex items-center gap-2 rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white transition-all hover:bg-blue-600"
        type="button"
      >
        <Share2 className="h-4 w-4" />
        Share Referral Link
      </button>

      {showOptions && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setShowOptions(false)} />
          <div className="absolute right-0 z-20 mt-2 w-64 rounded-xl border border-white/10 bg-slate-900 p-3 shadow-xl">
            <p className="mb-3 text-xs font-medium text-slate-400">Share via</p>
            <div className="space-y-1">
              {shareLinks.map((link) => (
                <button
                  key={link.name}
                  onClick={() => {
                    link.action();
                    if (link.name === 'Copy Link') {
                      setTimeout(() => setShowOptions(false), 500);
                    } else {
                      setShowOptions(false);
                    }
                  }}
                  className={`flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${link.color}`}
                  type="button"
                >
                  <link.icon className="h-4 w-4" />
                  {link.name}
                  {copied && link.name === 'Copy Link' && (
                    <span className="ml-auto flex items-center gap-1 text-xs text-emerald-400">
                      <Check className="h-3 w-3" /> Copied
                    </span>
                  )}
                </button>
              ))}
            </div>

            <div className="mt-3 border-t border-white/10 pt-3">
              <p className="mb-1 text-xs text-slate-500">Or share your code</p>
              <div className="flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2">
                <code className="flex-1 text-sm font-mono text-slate-200">{referralCode}</code>
                <button
                  onClick={() => copyToClipboard(referralCode)}
                  className="rounded p-1 text-slate-400 hover:bg-white/10 hover:text-slate-200"
                  type="button"
                >
                  {copied ? <Check className="h-3.5 w-3.5 text-emerald-400" /> : <Copy className="h-3.5 w-3.5" />}
                </button>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
