import { useEffect, useState } from 'react'
import { api } from '../api/client'
import type { Invitation } from '../api/types'

export function Invitations() {
  const [invitations, setInvitations] = useState<Invitation[]>([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(false)
  const [copied, setCopied] = useState<string | null>(null)

  const fetchInvitations = async () => {
    setLoading(true)
    try {
      const data = await api.listInvitations()
      setInvitations(data)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchInvitations()
  }, [])

  const handleCreate = async () => {
    setCreating(true)
    try {
      const inv = await api.createInvitation()
      setInvitations((prev) => [inv, ...prev])
    } finally {
      setCreating(false)
    }
  }

  const copyLink = (token: string) => {
    const url = `${window.location.origin}/register?token=${token}`
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(url)
    } else {
      const ta = document.createElement('textarea')
      ta.value = url
      ta.style.position = 'fixed'
      ta.style.left = '-9999px'
      document.body.appendChild(ta)
      ta.select()
      document.execCommand('copy')
      document.body.removeChild(ta)
    }
    setCopied(token)
    setTimeout(() => setCopied(null), 2000)
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="font-display text-3xl font-bold text-cellar-cream">Invitations</h2>
          <p className="text-cellar-muted text-sm mt-1">
            Invitez de nouvelles personnes à rejoindre votre cave
          </p>
        </div>
        <button onClick={handleCreate} disabled={creating} className="btn-primary">
          {creating ? 'Création...' : '+ Nouvelle invitation'}
        </button>
      </div>

      {loading ? (
        <div className="space-y-3">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="card p-4 animate-pulse">
              <div className="h-4 bg-cellar-surface rounded w-2/3" />
            </div>
          ))}
        </div>
      ) : invitations.length === 0 ? (
        <div className="card p-8 text-center">
          <span className="text-4xl opacity-30">📨</span>
          <p className="text-cellar-muted mt-2">Aucune invitation pour l'instant</p>
        </div>
      ) : (
        <div className="space-y-3">
          {invitations.map((inv) => (
            <div key={inv.id} className="card p-4">
              <div className="flex items-center justify-between gap-4">
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    {inv.used_by ? (
                      <span className="inline-block w-2 h-2 rounded-full bg-green-500" />
                    ) : (
                      <span className="inline-block w-2 h-2 rounded-full bg-cellar-gold" />
                    )}
                    <span className="text-sm font-mono text-cellar-cream truncate">
                      {inv.token.slice(0, 20)}...
                    </span>
                  </div>
                  <p className="text-xs text-cellar-muted mt-1">
                    Créée le {new Date(inv.created_at).toLocaleDateString('fr-FR')}
                    {inv.used_at && ` — Utilisée le ${new Date(inv.used_at).toLocaleDateString('fr-FR')}`}
                  </p>
                </div>

                {!inv.used_by && (
                  <button
                    onClick={() => copyLink(inv.token)}
                    className={`shrink-0 px-3 py-1.5 rounded-lg text-sm font-medium border transition-all ${
                      copied === inv.token
                        ? 'bg-green-900/30 border-green-700 text-green-300'
                        : 'bg-cellar-surface border-cellar-border text-cellar-muted hover:text-cellar-cream hover:border-cellar-muted'
                    }`}
                  >
                    {copied === inv.token ? '✓ Copié' : '📋 Copier'}
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
