import { Button } from '@/components/ui/button'
import { Share2, Copy, Check } from 'lucide-react'
import { useState } from 'react'
import { trackReferralShared } from '@/lib/analytics'
import { useAuth } from '@/context/AuthContext'

interface ShareResultsProps {
  sortedCount: number
  referralCode?: string
}

export function ShareResults({ sortedCount, referralCode }: ShareResultsProps) {
  const [copied, setCopied] = useState(false)
  const { user } = useAuth()

  const shareText = `I cleaned up ${sortedCount} emails with MailFlow${referralCode ? `! Use code ${referralCode} for a bonus.` : '!'}`
  const shareUrl = referralCode 
    ? `${window.location.origin}?ref=${referralCode}`
    : window.location.origin

  const handleCopy = async () => {
    const text = `${shareText}\n${shareUrl}`
    try {
      await navigator.clipboard.writeText(text)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error('Failed to copy:', err)
    }
  }

  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: 'MailFlow - Clean Inbox',
          text: shareText,
          url: shareUrl,
        })
        if (user?.$id && referralCode) {
          trackReferralShared(user.$id, referralCode)
        }
      } catch (err) {
        // User cancelled or error
        console.error('Share failed:', err)
      }
    } else {
      // Fallback to copy
      handleCopy()
    }
  }

  if (sortedCount < 10) {
    return null // Don't show for small results
  }

  return (
    <div className="bg-gradient-to-r from-primary-50 to-accent-50 border border-primary-200 rounded-lg p-4">
      <div className="flex items-start gap-3 mb-3">
        <div className="w-10 h-10 rounded-lg bg-primary-500 flex items-center justify-center flex-shrink-0">
          <Share2 className="w-5 h-5 text-white" />
        </div>
        <div className="flex-1">
          <h3 className="font-semibold text-slate-900 mb-1">Share your success!</h3>
          <p className="text-sm text-slate-600">
            {shareText}
          </p>
        </div>
      </div>
      <div className="flex gap-2">
        {typeof navigator !== 'undefined' && 'share' in navigator && typeof navigator.share === 'function' && (
          <Button
            onClick={handleShare}
            variant="outline"
            className="flex-1 border-primary-300 text-primary-700 hover:bg-primary-50"
          >
            <Share2 className="w-4 h-4 mr-2" />
            Share
          </Button>
        )}
        <Button
          onClick={handleCopy}
          variant="outline"
          className="flex-1 border-primary-300 text-primary-700 hover:bg-primary-50"
        >
          {copied ? (
            <>
              <Check className="w-4 h-4 mr-2" />
              Copied!
            </>
          ) : (
            <>
              <Copy className="w-4 h-4 mr-2" />
              Copy
            </>
          )}
        </Button>
      </div>
    </div>
  )
}
