'use client'

import { useState, useEffect } from 'react'
import type { InvitePayload } from '@/hooks/useTeam'
import { useDashboardI18n } from '@/components/I18nProvider'

interface Props {
  open: boolean
  onClose: () => void
  onInvite: (payload: InvitePayload) => Promise<void>
}

const copy = {
  en: {
    title: 'Invite a team member',
    subtitle: "They'll receive an email invitation to join your workspace.",
    firstName: 'First name',
    lastName: 'Last name',
    email: 'Email address',
    role: 'Role',
    cancel: 'Cancel',
    sending: 'Sending…',
    sendInvite: 'Send invite →',
    failedInvite: 'Failed to send invitation',
    more: (n: number) => `+${n} more`,
    roleOptions: [
      {
        value: 'MANAGER' as const,
        label: 'Manager',
        description: 'Full fleet operations, without billing or team settings',
        permissions: ['Vehicles', 'Reservations', 'CRM', 'Offers', 'Reports', 'License approval'],
      },
      {
        value: 'AGENT' as const,
        label: 'Agent',
        description: 'Day-to-day operations only',
        permissions: ['View fleet', 'Reservations', 'Check-in / Check-out', 'View customers'],
      },
    ],
  },
  fr: {
    title: 'Inviter un membre',
    subtitle: "Cette personne recevra un e-mail d'invitation pour rejoindre votre espace de travail.",
    firstName: 'Prénom',
    lastName: 'Nom',
    email: 'Adresse e-mail',
    role: 'Rôle',
    cancel: 'Annuler',
    sending: 'Envoi…',
    sendInvite: "Envoyer l'invitation →",
    failedInvite: "Échec de l'envoi de l'invitation",
    more: (n: number) => `+${n} de plus`,
    roleOptions: [
      {
        value: 'MANAGER' as const,
        label: 'Manager',
        description: 'Opérations complètes, sans accès à la facturation ni aux paramètres de l’équipe',
        permissions: ['Véhicules', 'Réservations', 'CRM', 'Offres', 'Rapports', 'Validation des permis'],
      },
      {
        value: 'AGENT' as const,
        label: 'Agent',
        description: 'Opérations quotidiennes uniquement',
        permissions: ['Voir la flotte', 'Réservations', 'Départ / Retour', 'Voir les clients'],
      },
    ],
  },
  ar: {
    title: 'دعوة عضو في الفريق',
    subtitle: 'سيتلقى رسالة بريد إلكتروني للانضمام إلى مساحة العمل.',
    firstName: 'الاسم الأول',
    lastName: 'اسم العائلة',
    email: 'البريد الإلكتروني',
    role: 'الدور',
    cancel: 'إلغاء',
    sending: 'جارٍ الإرسال…',
    sendInvite: '← إرسال الدعوة',
    failedInvite: 'فشل إرسال الدعوة',
    more: (n: number) => `+${n} أكثر`,
    roleOptions: [
      {
        value: 'MANAGER' as const,
        label: 'مدير',
        description: 'صلاحيات تشغيل كاملة للأسطول، من دون الفوترة أو إعدادات الفريق',
        permissions: ['المركبات', 'الحجوزات', 'CRM', 'العروض', 'التقارير', 'الموافقة على الرخص'],
      },
      {
        value: 'AGENT' as const,
        label: 'وكيل',
        description: 'العمليات اليومية فقط',
        permissions: ['عرض الأسطول', 'الحجوزات', 'الاستلام / الإرجاع', 'عرض العملاء'],
      },
    ],
  },
}

export default function InviteModal({ open, onClose, onInvite }: Props) {
  const { language } = useDashboardI18n()
  const t = copy[language]
  const isRtl = language === 'ar'

  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [email, setEmail] = useState('')
  const [role, setRole] = useState<'MANAGER' | 'AGENT'>('AGENT')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setFirstName('')
        setLastName('')
        setEmail('')
        setRole('AGENT')
        setError(null)
      }, 200)
    }
  }, [open])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    setLoading(true)
    try {
      await onInvite({ firstName: firstName.trim(), lastName: lastName.trim(), email: email.trim(), role })
      onClose()
    } catch (err: any) {
      setError(err.message ?? t.failedInvite)
    } finally {
      setLoading(false)
    }
  }

  if (!open) return null

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-blue-950/30 backdrop-blur-sm"
      onClick={(e) => { if (e.target === e.currentTarget) onClose() }}
    >
      <div
        className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-2xl shadow-xl w-full max-w-md mx-4 p-6"
        dir={isRtl ? 'rtl' : 'ltr'}
      >
        <div className="mb-5">
          <h2 className="text-lg font-medium text-zinc-900 dark:text-white">{t.title}</h2>
          <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">{t.subtitle}</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-zinc-500 dark:text-zinc-400 mb-1.5">
                {t.firstName}
              </label>
              <input
                type="text"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                placeholder="Youssef"
                required
                className="w-full px-3 py-2 text-sm border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-900 dark:focus:ring-white focus:ring-offset-0 focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-zinc-500 dark:text-zinc-400 mb-1.5">
                {t.lastName}
              </label>
              <input
                type="text"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                placeholder="Benali"
                required
                className="w-full px-3 py-2 text-sm border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-900 dark:focus:ring-white focus:border-transparent"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-zinc-500 dark:text-zinc-400 mb-1.5">
              {t.email}
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="youssef@yourcompany.com"
              required
              className="w-full px-3 py-2 text-sm border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-900 dark:focus:ring-white focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-xs font-medium text-zinc-500 dark:text-zinc-400 mb-1.5">
              {t.role}
            </label>
            <div className="grid grid-cols-2 gap-2">
              {t.roleOptions.map((option) => (
                <button
                  key={option.value}
                  type="button"
                  onClick={() => setRole(option.value)}
                  className={[
                    'text-left px-3 py-3 rounded-xl border transition-all',
                    role === option.value
                      ? 'border-zinc-900 dark:border-white bg-zinc-50 dark:bg-zinc-800'
                      : 'border-zinc-200 dark:border-zinc-700 hover:border-zinc-300 dark:hover:border-zinc-600',
                  ].join(' ')}
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm font-medium text-zinc-900 dark:text-white">
                      {option.label}
                    </span>
                    {role === option.value && (
                      <span className="w-4 h-4 rounded-full bg-zinc-900 dark:bg-white flex items-center justify-center">
                        <svg className="w-2.5 h-2.5 text-white dark:text-zinc-900" fill="currentColor" viewBox="0 0 12 12">
                          <path d="M10 3L5 8.5 2 5.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" fill="none" />
                        </svg>
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-zinc-500 dark:text-zinc-400 leading-snug">
                    {option.description}
                  </p>
                  <div className="mt-2 flex flex-wrap gap-1">
                    {option.permissions.slice(0, 3).map((p) => (
                      <span
                        key={p}
                        className="text-[10px] px-1.5 py-0.5 rounded bg-zinc-100 dark:bg-zinc-700 text-zinc-500 dark:text-zinc-400"
                      >
                        {p}
                      </span>
                    ))}
                    {option.permissions.length > 3 && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-zinc-100 dark:bg-zinc-700 text-zinc-500 dark:text-zinc-400">
                        {t.more(option.permissions.length - 3)}
                      </span>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </div>

          {error && (
            <div className="px-3 py-2.5 rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-100 dark:border-red-900/50">
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
          )}

          <div className={`flex gap-2 pt-2 border-t border-zinc-100 dark:border-zinc-800 ${isRtl ? 'flex-row-reverse' : ''}`}>
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 text-sm border border-zinc-200 dark:border-zinc-700 rounded-lg text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
            >
              {t.cancel}
            </button>
            <button
              type="submit"
              disabled={loading}
              className="flex-1 px-4 py-2 text-sm bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 rounded-lg font-medium hover:bg-zinc-800 dark:hover:bg-zinc-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {loading ? t.sending : t.sendInvite}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
