'use client';

import { useState, useEffect, useMemo } from 'react';
import { adminService } from '@/services/admin.service';
import { Prize, CreatePrizeData, UpdatePrizeData } from '@/types';
import { Gift, Package, Trophy, Archive, RefreshCw, X } from 'lucide-react';

export default function PrizeManagement() {
  const [prizes, setPrizes] = useState<Prize[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingPrize, setEditingPrize] = useState<Prize | null>(null);

  // Form state
  const [formData, setFormData] = useState<CreatePrizeData>({
    name: '',
    type: 'PHYSICAL',
    description: '',
    value: '',
    probability: 0,
    stock: 0,
  });

  useEffect(() => {
    loadPrizes();
  }, []);

  const loadPrizes = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await adminService.getAllPrizes();
      setPrizes(data || []);
    } catch (err: any) {
      setError(err.message || 'Erreur lors du chargement des prix');
      setPrizes([]);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingPrize) {
        await adminService.updatePrize(editingPrize.id, formData as UpdatePrizeData);
      } else {
        await adminService.createPrize(formData);
      }
      resetForm();
      loadPrizes();
    } catch (err: any) {
      alert(err.message || 'Erreur lors de la sauvegarde');
    }
  };

  const handleEdit = (prize: Prize) => {
    setEditingPrize(prize);
    setFormData({
      name: prize.name,
      type: prize.type,
      description: prize.description,
      value: prize.value,
      probability: prize.probability,
      stock: prize.stock,
    });
    setIsModalOpen(true);
  };

  const handleDelete = async (prizeId: string) => {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce prix ?')) return;

    try {
      await adminService.deletePrize(prizeId);
      loadPrizes();
    } catch (err: any) {
      alert(err.message || 'Erreur lors de la suppression');
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      type: 'PHYSICAL',
      description: '',
      value: '',
      probability: 0,
      stock: 0,
    });
    setEditingPrize(null);
    setIsModalOpen(false);
  };

  // Calculer les stats
  const prizeStats = useMemo(() => {
    const totalStock = prizes.reduce((acc, p) => acc + Number(p.initialStock || p.stock || 0), 0);
    const totalUsed = prizes.reduce((acc, p) => acc + Number(p.ticketsUsed || 0), 0);
    const activeCount = prizes.filter(p => p.isActive).length;
    return { totalStock, totalUsed, activeCount, totalPrizes: prizes.length };
  }, [prizes]);

  // Fonction pour obtenir l'icône et la couleur selon le type
  const getPrizeStyle = (type: string) => {
    switch (type) {
      case 'GRAND_PRIZE':
        return { bg: 'from-purple-500 to-purple-600', icon: Trophy, color: 'purple' };
      case 'PHYSICAL':
        return { bg: 'from-blue-500 to-blue-600', icon: Package, color: 'blue' };
      default:
        return { bg: 'from-emerald-500 to-emerald-600', icon: Gift, color: 'emerald' };
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-16">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Chargement des lots...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* Stats rapides */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-purple-200 rounded-lg flex items-center justify-center">
              <Gift className="w-5 h-5 text-purple-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-purple-700">{prizeStats.totalPrizes.toLocaleString('fr-FR')}</p>
              <p className="text-xs text-purple-600">Total Lots</p>
            </div>
          </div>
        </div>
        <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-green-200 rounded-lg flex items-center justify-center">
              <Archive className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-green-700">{prizeStats.totalStock.toLocaleString('fr-FR')}</p>
              <p className="text-xs text-green-600">Stock Total</p>
            </div>
          </div>
        </div>
        <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-200 rounded-lg flex items-center justify-center">
              <Package className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-blue-700">{prizeStats.totalUsed.toLocaleString('fr-FR')}</p>
              <p className="text-xs text-blue-600">Distribués</p>
            </div>
          </div>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl mb-6 flex items-center gap-3">
          <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
            <X className="w-5 h-5 text-red-600" />
          </div>
          <span>{error}</span>
        </div>
      )}

      {/* Liste des prix */}
      {prizes.length === 0 ? (
        <div className="text-center py-16 bg-gray-50 rounded-2xl border-2 border-dashed border-gray-200">
          <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <Gift className="w-8 h-8 text-gray-400" />
          </div>
          <p className="text-gray-500 font-medium">Aucun lot trouvé</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {prizes.map((prize) => {
            const style = getPrizeStyle(prize.type);
            const IconComponent = style.icon;
            const stockRemaining = Number(prize.initialStock || 0) - Number(prize.ticketsUsed || 0);

            return (
              <div
                key={prize.id}
                className="bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-lg transition-all overflow-hidden"
              >
                {/* Header avec gradient */}
                <div className={`bg-gradient-to-r ${style.bg} p-4`}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                        <IconComponent className="w-5 h-5 text-white" />
                      </div>
                      <h3 className="font-bold text-white text-lg">{prize.name}</h3>
                    </div>
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-semibold ${
                        prize.isActive
                          ? 'bg-white/20 text-white'
                          : 'bg-gray-800/20 text-white/70'
                      }`}
                    >
                      {prize.isActive ? 'Actif' : 'Inactif'}
                    </span>
                  </div>
                </div>

                {/* Contenu */}
                <div className="p-5">
                  <p className="text-sm text-gray-600 mb-4">{prize.description}</p>

                  {/* Affichage spécial pour le Grand Prix */}
                  {prize.type === 'GRAND_PRIZE' ? (
                    <div className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 rounded-xl border border-purple-100">
                      <div className="flex items-center gap-2 mb-2">
                        <Trophy className="w-5 h-5 text-purple-600" />
                        <span className="font-bold text-purple-800">TIRAGE AU SORT</span>
                      </div>
                      <p className="text-sm text-purple-700">
                        Attribué lors du tirage final parmi les participants éligibles
                      </p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {/* Probabilité */}
                      <div className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                        <span className="text-sm text-gray-600">Probabilité</span>
                        <span className="font-bold text-gray-900">{(prize.probability * 100).toFixed(1)}%</span>
                      </div>

                      {/* Stock */}
                      <div className="p-3 bg-gray-50 rounded-xl">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm text-gray-600">Stock</span>
                          <span className={`font-bold ${stockRemaining === 0 ? 'text-red-600' : 'text-green-600'}`}>
                            {stockRemaining.toLocaleString('fr-FR')} / {(prize.initialStock || prize.stock || 0).toLocaleString('fr-FR')}
                          </span>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2">
                          <div
                            className={`h-2 rounded-full ${stockRemaining === 0 ? 'bg-red-500' : 'bg-green-500'}`}
                            style={{ width: `${((prize.initialStock || prize.stock) > 0 ? (stockRemaining / (prize.initialStock || prize.stock)) * 100 : 0)}%` }}
                          ></div>
                        </div>
                      </div>

                      {/* Tickets utilisés */}
                      {prize.ticketsUsed !== undefined && prize.ticketsUsed > 0 && (
                        <div className="flex items-center justify-between p-3 bg-blue-50 rounded-xl">
                          <span className="text-sm text-blue-700">Distribués</span>
                          <span className="font-bold text-blue-800">{prize.ticketsUsed.toLocaleString('fr-FR')}</span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
