"use client";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAuth } from "@/contexts/AuthContext";
import { useGame } from "@/hooks/useGame";
import { ticketCodeSchema, TicketCodeFormData } from "@/lib/validations";
import { Input } from "@/components/ui/Input";
import Button from "@/components/Button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/Card";
import { Modal } from "@/components/ui/Modal";
import { PRIZE_CONFIG } from "@/utils/constants";
import { PlayGameResponse } from "@/types";
import { useRouter } from "next/navigation";
import { ROUTES } from "@/utils/constants";
import Link from "next/link";

const PRIZES = [
  { type: 'INFUSEUR', name: 'Infuseur à thé', color: 'bg-blue-100 text-blue-800' },
  { type: 'THE_SIGNATURE', name: 'Thé signature 100g', color: 'bg-primary-100 text-primary-800' },
  { type: 'COFFRET_DECOUVERTE', name: 'Coffret découverte 39€', color: 'bg-purple-100 text-purple-800' },
  { type: 'COFFRET_PRESTIGE', name: 'Coffret prestige 69€', color: 'bg-secondary-200 text-secondary-800' },
  { type: 'THE_GRATUIT', name: 'Thé gratuit en magasin', color: 'bg-pink-100 text-pink-800' },
];

export default function JeuxPage() {
  const { user, isAuthenticated } = useAuth();
  const { play, isPlaying } = useGame();
  const router = useRouter();
  const [showResultModal, setShowResultModal] = useState(false);
  const [showRouletteModal, setShowRouletteModal] = useState(false);
  const [gameResult, setGameResult] = useState<PlayGameResponse | null>(null);
  const [errorMessage, setErrorMessage] = useState<string>("");
  const [currentPrizeIndex, setCurrentPrizeIndex] = useState(0);
  const [isSpinning, setIsSpinning] = useState(false);

  // Protection stricte: redirection si non connecté
  useEffect(() => {
    if (!isAuthenticated) {
      router.push(`${ROUTES.LOGIN}?redirect=/jeux`);
    }
  }, [isAuthenticated, router]);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<TicketCodeFormData>({
    resolver: zodResolver(ticketCodeSchema),
  });

  // Animation de la roulette
  useEffect(() => {
    if (isSpinning) {
      const interval = setInterval(() => {
        setCurrentPrizeIndex((prev) => (prev + 1) % PRIZES.length);
      }, 100);

      return () => clearInterval(interval);
    }
  }, [isSpinning]);

  const onSubmit = async (data: TicketCodeFormData) => {
    // Réinitialiser le message d'erreur
    setErrorMessage("");

    // Afficher la modal de roulette et démarrer l'animation
    setShowRouletteModal(true);
    setIsSpinning(true);
    setCurrentPrizeIndex(0);

    const result = await play(data.ticketCode);

    if (result) {
      // Trouver l'index du prix gagné
      const winningIndex = PRIZES.findIndex(p => p.type === result.prize?.type);

      // Continuer à tourner pendant 3 secondes
      setTimeout(() => {
        setIsSpinning(false);
        if (winningIndex !== -1) {
          setCurrentPrizeIndex(winningIndex);
        }

        // Afficher le résultat après 2 secondes (pour montrer le gain)
        setTimeout(() => {
          setShowRouletteModal(false);
          setGameResult(result);
          setShowResultModal(true);
          setErrorMessage("");
          reset();
        }, 2000);
      }, 3000);
    } else {
      // En cas d'erreur, fermer la roulette et afficher l'erreur
      setIsSpinning(false);
      setShowRouletteModal(false);
      setErrorMessage("Ce code a déjà été utilisé ou est invalide. Si vous avez déjà utilisé ce code, consultez vos tickets dans 'Mes lots'.");
    }
  };

  const closeModal = () => {
    setShowResultModal(false);
    setGameResult(null);
  };

  const prizeConfig = gameResult?.prize
    ? PRIZE_CONFIG[gameResult.prize.type as keyof typeof PRIZE_CONFIG]
    : null;

  return (
    <div className="min-h-screen bg-gradient-to-br from-beige-100 via-beige-50 to-beige-100 py-8">
      <div className="container mx-auto px-4">
        {/* Formulaire Section */}
        <section className="mb-16">
          <div className="max-w-2xl mx-auto">
            <div className="bg-white rounded-xl shadow-2xl overflow-hidden border-2 border-beige-300">
              <div className="bg-gradient-to-r from-primary-500 to-primary-600 px-6 py-6 shadow-lg">
                <h1 className="text-center text-3xl md:text-4xl font-bold text-white">
                  Jouez maintenant !
                </h1>
              </div>
              <div className="p-8">
                <div className="mb-6 text-center">
                  <p className="text-beige-800 text-lg">
                    Bonjour <span className="font-bold text-primary-500">{user?.firstName}</span>,
                    entrez le code de 10 caractères présent sur votre ticket de caisse
                  </p>
                </div>

                <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                  <div>
                    <label htmlFor="ticketCode" className="block text-sm font-semibold text-beige-800 mb-2">
                      Code du ticket
                    </label>
                    <input
                      id="ticketCode"
                      type="text"
                      placeholder="TTP2025ABC"
                      {...register("ticketCode")}
                      className="w-full px-6 py-4 text-center text-2xl font-mono font-bold uppercase border-2 border-beige-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 tracking-widest bg-white shadow-inner"
                      maxLength={10}
                    />
                    {errors.ticketCode && (
                      <p className="mt-2 text-sm text-red-600">{errors.ticketCode.message}</p>
                    )}
                    {errorMessage && (
                      <div className="mt-3 p-4 bg-red-50 border-l-4 border-red-500 rounded-lg shadow-md">
                        <p className="text-sm text-red-800 font-medium mb-2">
                          ❌ {errorMessage}
                        </p>
                        <Link
                          href={ROUTES.HISTORY}
                          className="text-sm text-red-600 hover:text-red-800 underline font-medium"
                        >
                          → Voir vos tickets déjà utilisés
                        </Link>
                      </div>
                    )}
                    <p className="mt-2 text-sm text-gray-700 text-center">
                      Format: TTP2025ABC (10 caractères)
                    </p>
                  </div>

                  <div className="flex justify-center">
                    <button
                      type="submit"
                      disabled={isPlaying}
                      className="bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 disabled:from-gray-400 disabled:to-gray-500 text-white font-bold px-12 py-4 text-lg rounded-lg transition-all duration-300 shadow-lg hover:shadow-[0_0_20px_rgba(11,96,41,0.4)] hover:scale-105"
                    >
                      {isPlaying ? "Vérification en cours..." : "Tenter ma chance !"}
                    </button>
                  </div>
                </form>

                <div className="mt-6 p-4 bg-gradient-to-r from-primary-50 to-primary-100 border-l-4 border-primary-500 rounded-lg shadow-md">
                  <p className="text-sm text-beige-800 font-semibold mb-2">
                    Bon à savoir :
                  </p>
                  <ul className="text-sm text-beige-800 space-y-1 list-disc list-inside">
                    <li>Chaque code ne peut être utilisé qu'une seule fois</li>
                    <li>Consultez vos tickets sur la page <Link href={ROUTES.HISTORY} className="underline font-medium hover:text-primary-500 transition-colors">Mes gains</Link></li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Roulette Modal */}
        <Modal
          isOpen={showRouletteModal}
          onClose={() => {}}
          title="🎰 Tirage en cours..."
          size="md"
        >
          <div className="py-12">
            <div className="flex flex-col items-center gap-8">
              {/* Roulette Display */}
              <div className="relative w-full max-w-sm">
                <div className="flex flex-col gap-3">
                  {PRIZES.map((prize, index) => {
                    const getPrizeIcon = (type: string) => {
                      switch(type) {
                        case 'INFUSEUR':
                          return (
                            <svg className="w-8 h-8" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/>
                            </svg>
                          );
                        case 'THE_SIGNATURE':
                          return (
                            <svg className="w-8 h-8" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3z"/>
                            </svg>
                          );
                        case 'COFFRET_DECOUVERTE':
                          return (
                            <svg className="w-8 h-8" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/>
                            </svg>
                          );
                        case 'COFFRET_PRESTIGE':
                          return (
                            <svg className="w-8 h-8" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M12 2L4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zm6 9.09c0 4-2.55 7.7-6 8.83-3.45-1.13-6-4.82-6-8.83v-4.7l6-2.25 6 2.25v4.7zM8 10.5l1.5 1.5L15 6.5 13.5 5z"/>
                            </svg>
                          );
                        case 'THE_GRATUIT':
                          return (
                            <svg className="w-8 h-8" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/>
                            </svg>
                          );
                      }
                    };

                    return (
                      <div
                        key={index}
                        className={`flex items-center gap-4 p-4 rounded-xl transition-all duration-200 ${
                          currentPrizeIndex === index
                            ? `${prize.color} scale-110 shadow-xl border-4 border-current`
                            : 'bg-gray-100 opacity-50 scale-95'
                        }`}
                      >
                        <div className={`w-12 h-12 rounded-full flex items-center justify-center ${prize.color}`}>
                          {getPrizeIcon(prize.type)}
                        </div>
                        <div className="flex-1">
                          <p className={`font-bold ${currentPrizeIndex === index ? 'text-lg' : 'text-sm'}`}>
                            {prize.name}
                          </p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Loading Animation */}
              <div className="flex items-center gap-2 text-beige-800">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-500"></div>
                <span className="font-medium">Tirage en cours...</span>
              </div>
            </div>
          </div>
        </Modal>

        {/* Result Modal */}
        <Modal
          isOpen={showResultModal}
          onClose={closeModal}
          title="Résultat"
          size="md"
        >
          {gameResult && prizeConfig && (
            <div className="text-center py-6">
              <div className="flex justify-center mb-4">
                <div className={`w-24 h-24 rounded-full flex items-center justify-center ${prizeConfig.color}`}>
                  {gameResult.prize?.type === 'INFUSEUR' && (
                    <svg className="w-12 h-12" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/>
                    </svg>
                  )}
                  {gameResult.prize?.type === 'THE_SIGNATURE' && (
                    <svg className="w-12 h-12" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3z"/>
                    </svg>
                  )}
                  {gameResult.prize?.type === 'COFFRET_DECOUVERTE' && (
                    <svg className="w-12 h-12" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/>
                    </svg>
                  )}
                  {gameResult.prize?.type === 'COFFRET_PRESTIGE' && (
                    <svg className="w-12 h-12" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12 2L4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zm6 9.09c0 4-2.55 7.7-6 8.83-3.45-1.13-6-4.82-6-8.83v-4.7l6-2.25 6 2.25v4.7zM8 10.5l1.5 1.5L15 6.5 13.5 5z"/>
                    </svg>
                  )}
                  {gameResult.prize?.type === 'THE_GRATUIT' && (
                    <svg className="w-12 h-12" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/>
                    </svg>
                  )}
                </div>
              </div>
              <h3 className="text-3xl font-bold text-gray-900 mb-2">
                Félicitations ! 🎉
              </h3>
              <p className="text-lg text-gray-700 mb-4">
                Vous avez gagné :
              </p>
              <div
                className={`inline-block px-6 py-3 rounded-full text-lg font-semibold mb-6 ${prizeConfig.color}`}
              >
                {prizeConfig.name}
              </div>
              <p className="text-gray-600 mb-6">
                {gameResult.message || "Présentez-vous en magasin pour récupérer votre lot !"}
              </p>
              <div className="flex gap-3 justify-center">
                <button
                  onClick={closeModal}
                  className="border-2 border-beige-300 hover:bg-beige-100 text-beige-800 font-bold px-6 py-3 rounded-lg transition-all"
                >
                  Fermer
                </button>
                <button
                  onClick={() => router.push(ROUTES.HISTORY)}
                  className="bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 text-white font-bold px-6 py-3 rounded-lg transition-all duration-300 shadow-lg hover:shadow-[0_0_20px_rgba(11,96,41,0.4)]"
                >
                  Voir mes gains
                </button>
              </div>
            </div>
          )}
        </Modal>
      </div>
    </div>
  );
}
