'use client'

import { useEffect, useMemo, useState } from 'react'
import { X, Mail, Users, Send, Loader2 } from 'lucide-react'
import { useTranslations } from 'next-intl'

type Affiliate = {
  id: number
  name: string
  country: string
  verified: number
  created_at: string
  updated_at: string
}

type InviteUserModalProps = {
  isOpen: boolean
  onClose: () => void
  onConversationCreated?: (opts: { conversationId: string; existing: boolean }) => void
  isAffiliate?: boolean // contrôle d'affichage de l'onglet affiliés
}

export function InviteUserModal({ isOpen, onClose, onConversationCreated, isAffiliate = false }: InviteUserModalProps) {
  const t = useTranslations('chat.invite')
  const [activeTab, setActiveTab] = useState<'email' | 'affiliates'>(isAffiliate ? 'affiliates' : 'email')
  const [email, setEmail] = useState('')
  const [message, setMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [savingDefault, setSavingDefault] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState<string | null>(null)

  // Affiliés
  const [affiliates, setAffiliates] = useState<Affiliate[]>([])
  const [affiliatesLoading, setAffiliatesLoading] = useState(false)
  const [affiliatesError, setAffiliatesError] = useState<string | null>(null)
  const [selectedAffiliateId, setSelectedAffiliateId] = useState<number | null>(null)

  // Charger les affiliés au besoin
  useEffect(() => {
    if (!isOpen) return
    if (!isAffiliate) return
    if (activeTab !== 'affiliates') return

    let cancelled = false
    const load = async () => {
      try {
        setAffiliatesLoading(true)
        setAffiliatesError(null)
        const res = await fetch('/api/my-affiliates?page=1', { credentials: 'include' })
        const data = await res.json()
        if (!res.ok) {
          throw new Error(data?.error || 'Failed to load affiliates')
        }
        if (!cancelled) {
          setAffiliates(Array.isArray(data?.data) ? data.data : [])
        }
      } catch (e) {
        if (!cancelled) {
          setAffiliatesError(e instanceof Error ? e.message : 'Unknown error')
        }
      } finally {
        if (!cancelled) setAffiliatesLoading(false)
      }
    }
    load()
    return () => {
      cancelled = true
    }
  }, [isOpen, isAffiliate, activeTab])

  // Reset à l'ouverture
  useEffect(() => {
    if (isOpen) {
      setError(null)
      setSuccess(null)
      setLoading(false)
      setSaveSuccess(null)
    }
  }, [isOpen])

  // Charger le template d'invitation par défaut au besoin
  useEffect(() => {
    if (!isOpen) return
    // Ne pas écraser si l'utilisateur a déjà commencé à taper
    if (message && message.trim().length > 0) return
    let cancelled = false
    const loadTemplate = async () => {
      try {
        const res = await fetch('/api/chat/invitation-template', { credentials: 'include' })
        const data = await res.json()
        if (!cancelled && res.ok && data?.template?.content) {
          setMessage(data.template.content as string)
        }
      } catch {}
    }
    loadTemplate()
    return () => { cancelled = true }
  }, [isOpen])

  const canSendByEmail = useMemo(() => {
    return email.trim().length > 0 && email.includes('@') && message.trim().length > 0
  }, [email, message])

  const canSendByAffiliate = useMemo(() => typeof selectedAffiliateId === 'number', [selectedAffiliateId])
  const canSendByAffiliateWithMsg = useMemo(() => typeof selectedAffiliateId === 'number' && message.trim().length > 0, [selectedAffiliateId, message])

  const handleInviteByEmail = async () => {
    if (!email.trim() || !email.includes('@')) {
      setError(t('emailPlaceholder'))
      return
    }
    if (!message.trim()) {
      setError(t('messageRequired'))
      return
    }
    try {
      setLoading(true)
      setError(null)
      setSuccess(null)
      const res = await fetch('/api/chat/invite-by-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, invitationMessage: message || undefined }),
        credentials: 'include',
      })
      const data = await res.json()
      if (!res.ok) {
        throw new Error(data?.error || 'Failed to send invitation')
      }
      // Toujours afficher un message de succès générique provenant des traductions
      setSuccess(t('success'))
      if (data?.conversationCreated && data?.conversationId && onConversationCreated) {
        onConversationCreated({ conversationId: data.conversationId, existing: !!data?.existingConversation })
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unknown error')
    } finally {
      setLoading(false)
    }
  }

  const handleInviteByAffiliate = async () => {
    if (!canSendByAffiliate) return
    if (!message.trim()) {
      setError(t('messageRequired'))
      return
    }
    try {
      setLoading(true)
      setError(null)
      setSuccess(null)
      const res = await fetch('/api/invitations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ invited_user_id: selectedAffiliateId, invitationMessage: message || undefined }),
        credentials: 'include',
      })
      const data = await res.json()
      if (!res.ok) {
        throw new Error(data?.error || 'Failed to send invitation')
      }
      // La route /api/invitations crée aussi la conversation si Laravel retourne invited_user
      setSuccess(data?.message || t('success'))
      if (data?.conversationCreated && data?.conversationId && onConversationCreated) {
        onConversationCreated({ conversationId: data.conversationId, existing: !!data?.existingConversation })
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unknown error')
    } finally {
      setLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <>
      {/* Overlay */}
      <div className="fixed inset-0 bg-black/50 z-50" onClick={onClose} />

      {/* Modal */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-xl animate-in fade-in zoom-in duration-200">
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              {t('title')}
            </h2>
            <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-xl transition-colors" aria-label={t('close')}>
              <X className="w-5 h-5 text-gray-500 dark:text-gray-400" />
            </button>
          </div>

          {/* Tabs */}
          <div className="px-6 pt-4">
            <div className="flex gap-2 mb-4">
              <button
                onClick={() => setActiveTab('email')}
                className={`px-3 py-2 rounded-xl text-sm flex items-center gap-2 ${
                  activeTab === 'email' ? 'bg-teal-500 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                }`}
              >
                <Mail className="w-4 h-4" /> {t('byEmailTab')}
              </button>

              {isAffiliate && (
                <button
                  onClick={() => setActiveTab('affiliates')}
                  className={`px-3 py-2 rounded-xl text-sm flex items-center gap-2 ${
                    activeTab === 'affiliates' ? 'bg-teal-500 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                  }`}
                >
                  <Users className="w-4 h-4" /> {t('byAffiliatesTab')}
                </button>
              )}
            </div>
          </div>

          {/* Content */}
          <div className="px-6 pb-6">
            {error && (
              <div className="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-4 text-sm text-red-700 dark:text-red-300">
                {error}
              </div>
            )}

            {success && (
              <div className="mb-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-xl p-4 text-sm text-green-700 dark:text-green-300">
                {success}
              </div>
            )}

            {activeTab === 'email' && (
              <div className="space-y-3">
                <div>
                  <label className="block text-sm mb-1 text-gray-700 dark:text-gray-300">{t('emailLabel')}</label>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder={t('emailPlaceholder')}
                    className="w-full px-3 py-2 border-0 rounded-xl bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-teal-500"
                  />
                </div>
                <div>
                  <label className="block text-sm mb-1 text-gray-700 dark:text-gray-300">{t('messageLabel')}</label>
                  <textarea
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    rows={3}
                    placeholder={t('messagePlaceholder')}
                    className="w-full px-3 py-2 border-0 rounded-xl bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-teal-500"
                  />
                </div>
                <div>
                  <button
                  disabled={!canSendByEmail || loading}
                    onClick={handleInviteByEmail}
                    className="w-full px-4 py-3 rounded-xl bg-teal-500 text-white hover:bg-teal-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                  >
                    {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                    {loading ? t('sending') : t('sendButton')}
                  </button>
                <div className="mt-2 text-right">
                  <button
                    disabled={savingDefault || !message.trim()}
                    onClick={async () => {
                      try {
                        setSavingDefault(true)
                        setSaveSuccess(null)
                        await fetch('/api/chat/invitation-template', {
                          method: 'PUT',
                          headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify({ content: message }),
                          credentials: 'include'
                        })
                        setSaveSuccess(t('savedDefault'))
                      } finally {
                        setSavingDefault(false)
                        setTimeout(() => setSaveSuccess(null), 2000)
                      }
                    }}
                    className="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 underline disabled:no-underline disabled:opacity-50"
                  >
                    {savingDefault ? t('savingDefault') : t('saveAsDefault')}
                  </button>
                </div>
                {saveSuccess && (
                  <div className="mt-2 text-xs text-green-600 dark:text-green-400 text-right">{saveSuccess}</div>
                )}
                </div>
              </div>
            )}

            {activeTab === 'affiliates' && (
              <div className="space-y-3">
                <div>
                  <label className="block text-sm mb-1 text-gray-700 dark:text-gray-300">{t('selectAffiliateLabel')}</label>
                  <div className="rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div className="max-h-56 overflow-y-auto divide-y divide-gray-200 dark:divide-gray-700">
                      {affiliatesLoading && (
                        <div className="p-4 text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2">
                          <Loader2 className="w-4 h-4 animate-spin" /> {t('affiliatesLoading')}
                        </div>
                      )}

                      {affiliatesError && (
                        <div className="p-4 text-sm text-red-600 dark:text-red-400">
                          {affiliatesError}
                        </div>
                      )}

                      {!affiliatesLoading && !affiliatesError && affiliates.length === 0 && (
                        <div className="p-4 text-sm text-gray-500 dark:text-gray-400">
                          {t('noAffiliates')}
                        </div>
                      )}

                      {!affiliatesLoading && !affiliatesError && affiliates.map((a) => (
                        <label key={a.id} className="flex items-center p-3 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer">
                          <div className="flex items-center gap-3">
                            <input
                              type="radio"
                              name="affiliate"
                              checked={selectedAffiliateId === a.id}
                              onChange={() => setSelectedAffiliateId(a.id)}
                              className="accent-teal-500"
                            />
                            <div className="font-medium text-gray-900 dark:text-white">{a.name}</div>
                          </div>
                        </label>
                      ))}
                    </div>
                  </div>
                </div>
                <div>
                  <label className="block text-sm mb-1 text-gray-700 dark:text-gray-300">{t('messageLabel')}</label>
                  <textarea
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    rows={3}
                    placeholder={t('messagePlaceholder')}
                    className="w-full px-3 py-2 border-0 rounded-xl bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-teal-500"
                  />
                </div>
                <div>
                  <button
                    disabled={!canSendByAffiliateWithMsg || loading}
                    onClick={handleInviteByAffiliate}
                    className="w-full px-4 py-3 rounded-xl bg-teal-500 text-white hover:bg-teal-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                  >
                    {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                    {loading ? t('sending') : t('sendButton')}
                  </button>
                  <div className="mt-2 text-right">
                    <button
                      disabled={savingDefault || !message.trim()}
                      onClick={async () => {
                        try {
                          setSavingDefault(true)
                          setSaveSuccess(null)
                          await fetch('/api/chat/invitation-template', {
                            method: 'PUT',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ content: message }),
                            credentials: 'include'
                          })
                          setSaveSuccess(t('savedDefault'))
                        } finally {
                          setSavingDefault(false)
                          setTimeout(() => setSaveSuccess(null), 2000)
                        }
                      }}
                      className="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 underline disabled:no-underline disabled:opacity-50"
                    >
                      {savingDefault ? t('savingDefault') : t('saveAsDefault')}
                    </button>
                  </div>
                  {saveSuccess && (
                    <div className="mt-2 text-xs text-green-600 dark:text-green-400 text-right">{saveSuccess}</div>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  )
}


