'use client';

import { useState, useEffect } from 'react';
import { adminService } from '@/services/admin.service';
import { Prize, CreatePrizeData, UpdatePrizeData } from '@/types';

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);
  };

  if (loading) {
    return <div className="text-center py-8">Chargement des prix...</div>;
  }

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">Gestion des Prix</h1>
      </div>

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          {error}
        </div>
      )}

      {/* Liste des prix */}
      {prizes.length === 0 ? (
        <div className="text-center py-12 text-gray-500">
          Aucun prix trouvé. Cliquez sur "Ajouter un prix" pour commencer.
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {prizes.map((prize) => (
          <div
            key={prize.id}
            className="border rounded-lg p-4 shadow-sm hover:shadow-md transition"
          >
            <div className="flex justify-between items-start mb-3">
              <h3 className="font-semibold text-lg">{prize.name}</h3>
              <span
                className={`px-2 py-1 rounded text-xs ${
                  prize.isActive
                    ? 'bg-green-100 text-green-800'
                    : 'bg-gray-100 text-gray-800'
                }`}
              >
                {prize.isActive ? 'Actif' : 'Inactif'}
              </span>
            </div>

            <p className="text-sm text-gray-600 mb-2">{prize.description}</p>

            <div className="space-y-1 text-sm mb-3">
              <p><strong>Type:</strong> {prize.type}</p>
              <p><strong>Valeur:</strong> {prize.value}€</p>

              {/* Affichage spécial pour le Grand Prix (tirage au sort) */}
              {prize.type === 'GRAND_PRIZE' ? (
                <>
                  <p><strong>Probabilité:</strong> N/A (Tirage au sort)</p>
                  <div className="mt-2 p-2 bg-purple-50 border border-purple-200 rounded">
                    <p className="text-purple-800 font-semibold text-xs">
                      🎯 TIRAGE AU SORT
                    </p>
                    <p className="text-purple-700 text-xs mt-1">
                      Attribué lors du tirage final parmi les participants éligibles
                    </p>
                  </div>
                </>
              ) : (
                <>
                  <p><strong>Probabilité:</strong> {(prize.probability * 100).toFixed(1)}%</p>
                  <p>
                    <strong>Stock généré:</strong> {prize.initialStock !== undefined ? prize.initialStock : prize.stock}
                  </p>
                  <p>
                    <strong>Stock restant:</strong>{' '}
                    <span className={((prize.initialStock || 0) - (prize.ticketsUsed || 0)) === 0 ? 'text-red-600 font-semibold' : 'text-green-600 font-semibold'}>
                      {(prize.initialStock || 0) - (prize.ticketsUsed || 0)}
                    </span>
                  </p>
                  {prize.ticketsUsed !== undefined && prize.ticketsUsed > 0 && (
                    <p><strong>Tickets utilisés:</strong> {prize.ticketsUsed}</p>
                  )}
                </>
              )}
            </div>
          </div>
        ))}
        </div>
      )}
    </div>
  );
}
