import AuthLayout from "@/components/layout/AuthLayout";
import { motion } from 'framer-motion';
import { useState, useMemo } from 'react';
import { Link, useNavigate } from "react-router-dom";
import { sageService } from "@/service/sageService";
import { Button } from '@/components/ui/buttonTsx';
import AuthInput from '@/components/ui/AuthInput';
import { ArrowRight, ArrowLeft, Building2, Loader2, Mail, ShieldCheck, CheckCircle } from "lucide-react";

export default function Forgot() {
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const canSave = useMemo(() => {
    if (!email) return false;
    return /\S+@\S+\.\S+/.test(email);
  }, [email]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (loading || !canSave) return;
    
    setError(null);
    setMessage(null);
    setLoading(true);

    try {
      const response = await sageService.forgotPass(email);
      const success = response.success;
      const responseMessage = response.message;

      if (success) {
        setMessage(responseMessage || "Un email de réinitialisation a été envoyé à votre adresse.");
      } else {
        setError("Email introuvable ou invalide.");
      }
    } catch (err) {
      console.log("Erreur:", err);
      setError("Une erreur est survenue. Veuillez réessayer.");
    } finally {
      setLoading(false);
    }
  };

  // Animation variants
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: { 
      opacity: 1,
      transition: { 
        staggerChildren: 0.1,
        delayChildren: 0.2
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 300, damping: 24 } }
  };

  return (
    <AuthLayout>
      <motion.div 
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="w-full max-w-[420px]"
      >
        {/* Mobile Logo */}
        <div className="lg:hidden flex justify-center mb-8">
          <div className="w-12 h-12 rounded-xl bg-[#338660] flex items-center justify-center shadow-lg shadow-[#338660]/30">
            <Building2 className="w-7 h-7 text-white" />
          </div>
        </div>

        {/* Header */}
        <motion.div variants={itemVariants} className="text-center mb-10">
          <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-[#338660]/10 flex items-center justify-center">
            <Mail className="w-8 h-8 text-[#338660]" />
          </div>
          <h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            Mot de passe oublié ?
          </h2>
          <p className="text-gray-500 dark:text-gray-400">
            Entrez votre email pour recevoir un lien de réinitialisation
          </p>
        </motion.div>

        {/* Success Message */}
        {message && (
          <motion.div 
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-xl"
          >
            <div className="flex items-start gap-3">
              <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <p className="text-sm font-medium text-green-800 dark:text-green-300">
                  Email envoyé avec succès !
                </p>
                <p className="text-xs text-green-700 dark:text-green-400 mt-1">
                  {message}
                </p>
              </div>
            </div>
          </motion.div>
        )}

        {/* Error Message */}
        {error && (
          <motion.div 
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl"
          >
            <div className="flex items-start gap-3">
              <div className="w-5 h-5 rounded-full bg-red-100 dark:bg-red-900/50 flex items-center justify-center flex-shrink-0 mt-0.5">
                <span className="text-red-600 dark:text-red-400 text-xs font-bold">!</span>
              </div>
              <div className="flex-1">
                <p className="text-sm font-medium text-red-800 dark:text-red-300">
                  {error}
                </p>
              </div>
              <button 
                onClick={() => setError(null)}
                className="text-red-400 hover:text-red-600 dark:text-red-500 dark:hover:text-red-300"
              >
                <span className="text-lg leading-none">×</span>
              </button>
            </div>
          </motion.div>
        )}

        {/* Form */}
        <motion.form 
          variants={itemVariants} 
          onSubmit={handleSubmit} 
          className="space-y-6"
        >
          <AuthInput
            icon={Mail}
            type="email"
            label="Adresse email"
            placeholder="nom@entreprise.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            error={!canSave && email ? "Format d'email invalide" : undefined}
            autoFocus
          />

          <Button
            type="submit"
            disabled={!canSave || loading}
            className="w-full h-12 text-base font-bold bg-[#338660] hover:bg-[#2A6F4F] transition-all duration-300 shadow-[0_4px_14px_0_rgba(51,134,96,0.39)] hover:shadow-[0_6px_20px_rgba(51,134,96,0.23)] hover:-translate-y-0.5 rounded-xl disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:transform-none"
          >
            {loading ? (
              <span className="flex items-center gap-2">
                <Loader2 className="w-5 h-5 animate-spin" />
                Envoi en cours...
              </span>
            ) : (
              <span className="flex items-center gap-2">
                Envoyer le lien
                <ArrowRight className="w-5 h-5" />
              </span>
            )}
          </Button>

          {/* Back to Login */}
          <button
            type="button"
            onClick={() => navigate("/login")}
            className="w-full flex items-center justify-center gap-2 text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-[#338660] dark:hover:text-[#338660] transition-colors"
          >
            <ArrowLeft className="w-4 h-4" />
            Retour à la connexion
          </button>
        </motion.form>

        {/* Footer Trust Elements */}
        <motion.div variants={itemVariants} className="mt-12 text-center space-y-4">
          <div className="flex items-center justify-center gap-2 text-xs text-gray-500 bg-gray-50 dark:bg-gray-900/50 py-2 px-4 rounded-full mx-auto">
            <ShieldCheck className="w-3.5 h-3.5 text-[#338660]" />
            <span>Connexion chiffrée SSL • Données sécurisées</span>
          </div>
          
          <p className="text-xs text-gray-400">
            Besoin d'aide ?{' '}
            <Link to="/support" className="text-gray-500 hover:text-[#338660] underline">
              Contactez notre support
            </Link>
          </p>
        </motion.div>
      </motion.div>
    </AuthLayout>
  );
}