'use client';

import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Share2, X, Copy, Check, QrCode, ExternalLink } from 'lucide-react';
import QRCode from 'qrcode';

interface ProfileShareButtonProps {
  username: string;
  displayName?: string;
  accent?: string;
}

export default function ProfileShareButton({
  username,
  displayName,
  accent = '#f5caca',
}: ProfileShareButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [copied, setCopied] = useState(false);
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  const shareUrl = typeof window !== 'undefined'
    ? `${window.location.origin}/${username}`
    : `https://sinss.lol/${username}`;

  useEffect(() => {
    if (!isOpen) return;
    QRCode.toDataURL(shareUrl, {
      width: 220,
      margin: 1.5,
      color: {
        dark: '#000000',
        light: '#0a0d14',
      },
    })
      .then((url) => setQrDataUrl(url))
      .catch((err) => console.error('Failed to generate QR code:', err));
  }, [isOpen, shareUrl]);

  const handleCopy = async () => {
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(shareUrl);
      } else {
        const input = document.createElement('input');
        input.value = shareUrl;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
      }
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (e) {
      console.error('Failed to copy share URL:', e);
    }
  };

  const handleTwitterShare = () => {
    const text = encodeURIComponent(`Check out ${displayName || ("@" + username)}'s bio link on sinss.lol`);
    const url = encodeURIComponent(shareUrl);
    window.open(`https://twitter.com/intent/tweet?text=${text}&url=${url}`, '_blank', 'noopener,noreferrer');
  };

  const handleTelegramShare = () => {
    const text = encodeURIComponent(`Check out @${username}'s bio link`);
    const url = encodeURIComponent(shareUrl);
    window.open(`https://t.me/share/url?url=${url}&text=${text}`, '_blank', 'noopener,noreferrer');
  };

  const handleWhatsAppShare = () => {
    const text = encodeURIComponent(`Check out my bio link: ${shareUrl}`);
    window.open(`https://api.whatsapp.com/send?text=${text}`, '_blank', 'noopener,noreferrer');
  };

  return (
    <>
      <button
        type="button"
        onClick={() => setIsOpen(true)}
        className="profileShareTrigger"
        title={`Share @${username}`}
        style={{
          background: 'transparent',
          border: 'none',
          color: '#340808',
          fontSize: 12,
          display: 'inline-flex',
          alignItems: 'center',
          gap: 5,
          cursor: 'pointer',
          padding: 0,
          fontFamily: 'inherit',
          transition: 'color 0.15s ease',
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.color = accent;
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.color = '#340808';
        }}
      >
        <Share2 size={13} />
        <span>Share</span>
      </button>

      {isOpen && mounted && createPortal(
        <div
          className="shareModalBackdrop"
          onClick={() => setIsOpen(false)}
          style={{
            position: 'fixed',
            inset: 0,
            zIndex: 99999,
            background: 'rgba(3, 4, 7, 0.75)',
            backdropFilter: 'blur(10px)',
            WebkitBackdropFilter: 'blur(10px)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: 20,
            animation: 'shareFadeIn 0.18s ease-out',
          }}
        >
          <div
            className="shareModalBox"
            onClick={(e) => e.stopPropagation()}
            style={{
              position: 'relative',
              width: '100%',
              maxWidth: 380,
              background: '#0a0d14',
              borderRadius: 18,
              border: '1px solid rgba(0, 0, 0, 0.12)',
              boxShadow: `0 24px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(0, 0, 0, 0.05), 0 8px 30px ${accent}22`,
              padding: '24px 22px',
              color: '#000000',
              display: 'flex',
              flexDirection: 'column',
              gap: 18,
            }}
          >
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: 9,
                    background: `${accent}20`,
                    border: `1px solid ${accent}40`,
                    color: accent,
                    display: 'grid',
                    placeItems: 'center',
                  }}
                >
                  <Share2 size={16} />
                </div>
                <div>
                  <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800, letterSpacing: '-0.01em' }}>
                    Share Profile
                  </h3>
                  <p style={{ margin: 0, fontSize: 12, color: '#240a0a' }}>
                    @{username}
                  </p>
                </div>
              </div>
              <button
                type="button"
                onClick={() => setIsOpen(false)}
                style={{
                  background: 'rgba(0, 0, 0, 0.06)',
                  border: '1px solid rgba(0, 0, 0, 0.08)',
                  borderRadius: 8,
                  width: 30,
                  height: 30,
                  color: '#7e0b0b',
                  cursor: 'pointer',
                  display: 'grid',
                  placeItems: 'center',
                  transition: 'all 0.15s ease',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = 'rgba(0, 0, 0, 0.14)';
                  e.currentTarget.style.color = '#000000';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'rgba(0, 0, 0, 0.06)';
                  e.currentTarget.style.color = '#7e0b0b';
                }}
              >
                <X size={15} />
              </button>
            </div>

            {/* Link Copy Box */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                background: 'rgba(0, 0, 0, 0.04)',
                border: '1px solid rgba(0, 0, 0, 0.09)',
                borderRadius: 12,
                padding: '7px 8px 7px 12px',
              }}
            >
              <span
                style={{
                  flex: 1,
                  fontSize: 12.5,
                  color: '#7e0b0b',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  fontFamily: 'monospace',
                }}
              >
                {shareUrl}
              </span>
              <button
                type="button"
                onClick={handleCopy}
                style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 6,
                  background: copied ? 'rgba(214, 146, 146, 0.2)' : accent,
                  color: copied ? '#de8383' : '#040711',
                  border: copied ? '1px solid rgba(222, 131, 131, 0.4)' : 'none',
                  borderRadius: 8,
                  padding: '7px 12px',
                  fontSize: 12,
                  fontWeight: 700,
                  cursor: 'pointer',
                  fontFamily: 'inherit',
                  transition: 'all 0.15s ease',
                }}
              >
                {copied ? <Check size={14} /> : <Copy size={14} />}
                <span>{copied ? 'Copied' : 'Copy'}</span>
              </button>
            </div>

            {/* QR Code Section */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: 10,
                padding: '16px 12px',
                background: 'rgba(0, 0, 0, 0.02)',
                borderRadius: 14,
                border: '1px solid rgba(0, 0, 0, 0.06)',
              }}
            >
              <div
                style={{
                  width: 170,
                  height: 170,
                  borderRadius: 12,
                  overflow: 'hidden',
                  background: '#0a0d14',
                  border: '1px solid rgba(0, 0, 0, 0.12)',
                  display: 'grid',
                  placeItems: 'center',
                  padding: 8,
                }}
              >
                {qrDataUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={qrDataUrl}
                    alt={`QR Code for @${username}`}
                    style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 6 }}
                  />
                ) : (
                  <QrCode size={32} style={{ color: '#422020' }} />
                )}
              </div>
              <span style={{ fontSize: 11.5, color: '#551212', textAlign: 'center' }}>
                Scan with your camera to open on mobile
              </span>
            </div>

            {/* Social Share Buttons */}
            <div>
              <span
                style={{
                  display: 'block',
                  fontSize: 11,
                  fontWeight: 700,
                  textTransform: 'uppercase',
                  letterSpacing: '0.06em',
                  color: '#3d1616',
                  marginBottom: 8,
                }}
              >
                Share via
              </span>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                <button
                  type="button"
                  onClick={handleTwitterShare}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 6,
                    padding: '8px 6px',
                    borderRadius: 9,
                    background: 'rgba(0, 0, 0, 0.04)',
                    border: '1px solid rgba(0, 0, 0, 0.08)',
                    color: '#9b0707',
                    fontSize: 12,
                    fontWeight: 600,
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    transition: 'all 0.15s ease',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(0, 0, 0, 0.25)';
                    e.currentTarget.style.background = 'rgba(0, 0, 0, 0.08)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(0, 0, 0, 0.08)';
                    e.currentTarget.style.background = 'rgba(0, 0, 0, 0.04)';
                  }}
                >
                  <ExternalLink size={12} />
                  <span>X / Twitter</span>
                </button>
                <button
                  type="button"
                  onClick={handleTelegramShare}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 6,
                    padding: '8px 6px',
                    borderRadius: 9,
                    background: 'rgba(0, 0, 0, 0.04)',
                    border: '1px solid rgba(0, 0, 0, 0.08)',
                    color: '#9b0707',
                    fontSize: 12,
                    fontWeight: 600,
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    transition: 'all 0.15s ease',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(0, 0, 0, 0.25)';
                    e.currentTarget.style.background = 'rgba(0, 0, 0, 0.08)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(0, 0, 0, 0.08)';
                    e.currentTarget.style.background = 'rgba(0, 0, 0, 0.04)';
                  }}
                >
                  <ExternalLink size={12} />
                  <span>Telegram</span>
                </button>
                <button
                  type="button"
                  onClick={handleWhatsAppShare}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 6,
                    padding: '8px 6px',
                    borderRadius: 9,
                    background: 'rgba(0, 0, 0, 0.04)',
                    border: '1px solid rgba(0, 0, 0, 0.08)',
                    color: '#9b0707',
                    fontSize: 12,
                    fontWeight: 600,
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    transition: 'all 0.15s ease',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(0, 0, 0, 0.25)';
                    e.currentTarget.style.background = 'rgba(0, 0, 0, 0.08)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(0, 0, 0, 0.08)';
                    e.currentTarget.style.background = 'rgba(0, 0, 0, 0.04)';
                  }}
                >
                  <ExternalLink size={12} />
                  <span>WhatsApp</span>
                </button>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}

      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes shareFadeIn {
          from { opacity: 0; transform: scale(0.97); }
          to { opacity: 1; transform: scale(1); }
        }
      ` }} />
    </>
  );
}
