"use client";

import { useEffect, useState } from "react";
import { Gift, Mail, Check, Clock, XCircle, Send, AlertCircle, Building2, User, Sparkles } from "lucide-react";

interface Referral {
  id: string;
  referee_name: string;
  referee_email: string;
  status: string;
  personal_message: string | null;
  referrer_credit_amount: number;
  referee_discount_amount: number;
  email_sent_at: string | null;
  contract_signed_at: string | null;
  invoice_paid_at: string | null;
  validated_at: string | null;
  created_at: string;
}

interface Organization {
  id: string;
  name: string;
}

interface ParrainageClientProps {
  isStaff: boolean;
  organizations: Organization[];
  initialOrgId: string | null;
}

const STATUS_CONFIG = {
  pending: {
    label: "En attente",
    color: "bg-slate-100 text-slate-700",
    icon: Clock,
    description: "Email pas encore envoyé",
  },
  email_sent: {
    label: "Email envoyé",
    color: "bg-blue-100 text-blue-700",
    icon: Mail,
    description: "En attente de signature",
  },
  signed: {
    label: "Contrat signé",
    color: "bg-purple-100 text-purple-700",
    icon: Check,
    description: "En attente de paiement",
  },
  validated: {
    label: "Validé",
    color: "bg-green-100 text-green-700",
    icon: Check,
    description: "Crédit de 30€ HT disponible",
  },
  cancelled: {
    label: "Annulé",
    color: "bg-red-100 text-red-700",
    icon: XCircle,
    description: "Parrainage annulé",
  },
};

export default function ParrainageClient({ 
  isStaff, 
  organizations, 
  initialOrgId 
}: ParrainageClientProps) {
  const [referrals, setReferrals] = useState<Referral[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [sending, setSending] = useState(false);
  const [selectedOrgId, setSelectedOrgId] = useState<string | null>(initialOrgId);
  
  // Form state
  const [formData, setFormData] = useState({
    referrer_name: "",
    referee_name: "",
    referee_email: "",
    personal_message: "",
  });
  
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const fetchReferrals = async (orgId: string | null = selectedOrgId) => {
    if (!orgId) {
      setLoading(false);
      return;
    }
    
    try {
      const url = isStaff 
        ? `/api/referrals?org_id=${orgId}` 
        : "/api/referrals";
      
      const res = await fetch(url, {
        credentials: "include",
        cache: "no-store",
      });
      
      if (!res.ok) throw new Error("Erreur fetch");
      
      const data = await res.json();
      setReferrals(data.referrals || []);
    } catch (err) {
      console.error("Erreur lors du chargement des parrainages:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchReferrals();
  }, [selectedOrgId]);

  const handleOrgChange = async (orgId: string) => {
    setSelectedOrgId(orgId);
    setLoading(true);
    
    // Mettre à jour le cookie pour le staff
    if (isStaff) {
      document.cookie = `active_org_id=${orgId}; path=/; max-age=31536000`;
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    
    // Vérifier que le staff a bien sélectionné une organisation
    if (isStaff && !selectedOrgId) {
      setError("Veuillez sélectionner une organisation");
      return;
    }
    
    setSending(true);
    
    try {
      // Pour le staff, ajouter l'org_id en paramètre
      const url = isStaff && selectedOrgId 
        ? `/api/referrals?org_id=${selectedOrgId}`
        : "/api/referrals";
      
      console.log('[Parrainage] Envoi invitation:', {
        isStaff,
        selectedOrgId,
        url,
        formData
      });
        
      const res = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify(formData),
      });
      
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.error || "Erreur lors de l'envoi");
      }
      
      setSuccess(true);
      setFormData({
        referrer_name: "",
        referee_name: "",
        referee_email: "",
        personal_message: "",
      });
      
      await fetchReferrals();
      
      setTimeout(() => {
        setSuccess(false);
        setShowForm(false);
      }, 3000);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSending(false);
    }
  };

  const totalCredits = referrals
    .filter((r) => r.status === "validated")
    .reduce((sum, r) => sum + r.referrer_credit_amount, 0);

  if (loading) {
    return (
      <div className="p-6">
        <p className="text-sm text-slate-600">Chargement...</p>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Sélecteur d'organisation (Staff uniquement) */}
      {isStaff && organizations.length > 0 && (
        <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-4">
          <div className="flex items-center gap-3">
            <Building2 className="w-5 h-5 text-indigo-600" />
            <div className="flex-1">
              <label className="block text-sm font-medium text-indigo-900 mb-1">
                Organisation sélectionnée (mode Staff)
              </label>
              <select
                value={selectedOrgId || ""}
                onChange={(e) => handleOrgChange(e.target.value)}
                className="w-full px-3 py-2 border border-indigo-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white"
              >
                <option value="">-- Sélectionner une organisation --</option>
                {organizations.map((org) => (
                  <option key={org.id} value={org.id}>
                    {org.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
      )}

      {/* Header */}
      <div className="flex items-start justify-between gap-6">
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-slate-900">Programme de parrainage</h1>
          <p className="text-sm text-slate-600 mt-1">
            Recommandez Odentas et profitez ensemble de 50 € HT de réduction*
          </p>
        </div>
        
        {!showForm && (
          <button
            onClick={() => setShowForm(true)}
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-indigo-200 via-purple-200 to-pink-200 text-slate-900 rounded-lg hover:from-indigo-300 hover:via-purple-300 hover:to-pink-300 transition font-medium shadow-sm"
          >
            <Gift className="w-4 h-4" />
            Inviter un ami
          </button>
        )}
      </div>

      {/* Carte des avantages */}
      <div className="bg-white border border-slate-200 rounded-lg p-6">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center">
            <Gift className="w-5 h-5 text-slate-700" />
          </div>
          <div>
            <h2 className="text-base font-semibold text-slate-900">Parrainez et gagnez 30 € HT</h2>
            <p className="text-sm text-slate-600">Votre filleul reçoit 20 € HT de réduction</p>
          </div>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-slate-50 rounded-lg p-4 border border-slate-200">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center border border-slate-200">
                <User className="w-4 h-4 text-slate-700" />
              </div>
              <div>
                <p className="text-xs text-slate-500 font-medium">Vous gagnez</p>
                <p className="text-lg font-semibold text-slate-900">30 € HT</p>
              </div>
            </div>
            <p className="text-xs text-slate-600">Crédit automatique sur votre prochaine facture</p>
          </div>
          
          <div className="bg-slate-50 rounded-lg p-4 border border-slate-200">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center border border-slate-200">
                <Sparkles className="w-4 h-4 text-slate-700" />
              </div>
              <div>
                <p className="text-xs text-slate-500 font-medium">Votre filleul gagne</p>
                <p className="text-lg font-semibold text-slate-900">20 € HT</p>
              </div>
            </div>
            <p className="text-xs text-slate-600">Réduction à l'ouverture du compte</p>
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-slate-600">Total de parrainages</p>
              <p className="text-3xl font-bold text-slate-900 mt-1">{referrals.length}</p>
            </div>
            <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
              <Mail className="w-6 h-6 text-blue-600" />
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-xl border p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-slate-600">Parrainages validés</p>
              <p className="text-3xl font-bold text-green-600 mt-1">
                {referrals.filter((r) => r.status === "validated").length}
              </p>
            </div>
            <div className="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
              <Check className="w-6 h-6 text-green-600" />
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-xl border p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-slate-600">Crédits obtenus</p>
              <p className="text-3xl font-bold text-orange-600 mt-1">{totalCredits.toFixed(2)} €</p>
            </div>
            <div className="w-12 h-12 bg-orange-100 rounded-xl flex items-center justify-center">
              <Gift className="w-6 h-6 text-orange-600" />
            </div>
          </div>
        </div>
      </div>

      {/* Modal Formulaire */}
      {showForm && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            {/* Header du modal */}
            <div className="sticky top-0 bg-gradient-to-r from-indigo-200 via-purple-200 to-pink-200 p-5 rounded-t-lg border-b border-slate-200">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-white/50 rounded-lg flex items-center justify-center">
                    <Gift className="w-5 h-5 text-slate-900" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-slate-900">Inviter un ami</h2>
                    <p className="text-slate-700 text-sm">Partagez les avantages du parrainage</p>
                  </div>
                </div>
                <button
                  onClick={() => {
                    setShowForm(false);
                    setError(null);
                    setSuccess(false);
                  }}
                  className="text-slate-600 hover:text-slate-900 transition"
                >
                  <XCircle className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* Contenu du modal */}
            <div className="p-6">
              {success && (
                <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-start gap-3">
                  <Check className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="text-sm font-medium text-green-900">Invitation envoyée</p>
                    <p className="text-sm text-green-700 mt-1">
                      Votre ami va recevoir un email avec votre recommandation.
                    </p>
                  </div>
                </div>
              )}

              {error && (
                <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
                  <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
                  <p className="text-sm text-red-700">{error}</p>
                </div>
              )}

              <form onSubmit={handleSubmit} className="space-y-5">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-2">
                    Votre nom <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.referrer_name}
                    onChange={(e) => setFormData({ ...formData, referrer_name: e.target.value })}
                    required
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-slate-500 transition"
                    placeholder="Ex: Jean Dupont"
                  />
                  <p className="text-xs text-slate-500 mt-1">Votre nom apparaîtra dans l'email</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      Nom de votre ami <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={formData.referee_name}
                      onChange={(e) => setFormData({ ...formData, referee_name: e.target.value })}
                      required
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-slate-500 transition"
                      placeholder="Ex: Marie Martin"
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      Email de votre ami <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="email"
                      value={formData.referee_email}
                      onChange={(e) => setFormData({ ...formData, referee_email: e.target.value })}
                      required
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-slate-500 transition"
                      placeholder="ami@email.com"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-2">
                    Message personnalisé (optionnel)
                  </label>
                  <textarea
                    value={formData.personal_message}
                    onChange={(e) => setFormData({ ...formData, personal_message: e.target.value })}
                    rows={4}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-slate-500 transition resize-none"
                    placeholder="Ajoutez un message personnel..."
                  />
                  <p className="text-xs text-slate-500 mt-1">
                    Ce message sera inclus dans l'email d'invitation
                  </p>
                </div>

                <div className="flex items-center gap-3 pt-4 border-t">
                  <button
                    type="submit"
                    disabled={sending}
                    className="flex-1 inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-gradient-to-r from-indigo-200 via-purple-200 to-pink-200 text-slate-900 rounded-lg hover:from-indigo-300 hover:via-purple-300 hover:to-pink-300 transition disabled:opacity-50 disabled:cursor-not-allowed font-medium shadow-sm"
                  >
                    {sending ? (
                      <>
                        <div className="w-4 h-4 border-2 border-slate-900 border-t-transparent rounded-full animate-spin" />
                        Envoi en cours...
                      </>
                    ) : (
                      <>
                        <Send className="w-4 h-4" />
                        Envoyer l'invitation
                      </>
                    )}
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setShowForm(false);
                      setError(null);
                      setSuccess(false);
                    }}
                    className="px-6 py-3 border border-slate-300 rounded-xl hover:bg-slate-50 transition font-medium"
                  >
                    Annuler
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Liste des parrainages */}
      <div className="bg-white rounded-xl border">
        <div className="p-6 border-b">
          <h2 className="text-lg font-semibold text-slate-900">Mes parrainages</h2>
        </div>
        
        <div className="divide-y">
          {referrals.length === 0 ? (
            <div className="p-8 text-center">
              <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <Gift className="w-8 h-8 text-slate-400" />
              </div>
              <p className="text-sm text-slate-600">Aucun parrainage pour le moment</p>
              <p className="text-xs text-slate-500 mt-1">
                Commencez à parrainer pour gagner des crédits !
              </p>
            </div>
          ) : (
            referrals.map((referral) => {
              const statusConfig = STATUS_CONFIG[referral.status as keyof typeof STATUS_CONFIG] || STATUS_CONFIG.pending;
              const StatusIcon = statusConfig.icon;
              
              return (
                <div key={referral.id} className="p-6">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <h3 className="font-medium text-slate-900">{referral.referee_name}</h3>
                        <span className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full ${statusConfig.color}`}>
                          <StatusIcon className="w-3 h-3" />
                          {statusConfig.label}
                        </span>
                      </div>
                      
                      <p className="text-sm text-slate-600 mb-1">{referral.referee_email}</p>
                      <p className="text-xs text-slate-500">{statusConfig.description}</p>
                      
                      {referral.personal_message && (
                        <div className="mt-3 p-3 bg-amber-50 border border-amber-200 rounded-lg">
                          <p className="text-xs text-amber-900 italic">"{referral.personal_message}"</p>
                        </div>
                      )}
                    </div>
                    
                    <div className="text-right">
                      <p className="text-xs text-slate-500">Créé le</p>
                      <p className="text-sm font-medium text-slate-900">
                        {new Date(referral.created_at).toLocaleDateString("fr-FR")}
                      </p>
                      {referral.status === "validated" && (
                        <p className="text-sm font-semibold text-green-600 mt-2">
                          +{referral.referrer_credit_amount} € HT
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>

      {/* Conditions générales */}
      <div className="bg-slate-50 rounded-xl border p-6">
        <h3 className="text-sm font-semibold text-slate-900 mb-3">
          Conditions de l'offre de parrainage Odentas
        </h3>
        <div className="text-xs text-slate-600 space-y-2 leading-relaxed">
          <p>• Le programme de parrainage est ouvert à tout client Odentas disposant d'un contrat de gestion de la paie actif.</p>
          <p>• Il n'y a aucune limite au nombre de filleuls pouvant être parrainés.</p>
          <p>• Le parrain bénéficie d'une réduction de 30 € HT sur ses prochaines factures, une fois le parrainage validé.</p>
          <p>• Le filleul bénéficie d'une réduction de 20 € HT sur sa facture d'ouverture de compte (49,99 € HT ou 99,99 € HT selon le cas).</p>
          <p>• Le parrainage est considéré comme validé lorsque :</p>
          <p className="pl-4">◦ le filleul a signé son contrat Odentas, et</p>
          <p className="pl-4">◦ la facture d'ouverture de compte du filleul a été intégralement réglée.</p>
          <p>• La réduction du parrain est déduite automatiquement de la prochaine facture émise après validation du parrainage.</p>
          <p>• Si le montant de la facture est inférieur à la réduction disponible, le solde restant est reporté sur les factures suivantes, jusqu'à épuisement du crédit.</p>
          <p>• Les réductions obtenues ne sont ni échangeables, ni remboursables, ni convertibles en numéraire.</p>
          <p>• Odentas Media SAS se réserve le droit de modifier ou suspendre le programme de parrainage à tout moment, sans effet rétroactif sur les parrainages déjà validés.</p>
        </div>
      </div>
    </div>
  );
}
