import AuthLayout from "@/components/layout/AuthLayout";
import { motion } from 'framer-motion';
import { useEffect, useMemo, useState } from 'react';
import { resetPassInterface } from '@/types/userInterface';
import { useNavigate, useSearchParams } from "react-router-dom";
import { sageService } from "@/service/sageService";
import { Button } from '@/components/ui/buttonTsx';
import AuthInput from '@/components/ui/AuthInput';
import { 
  ArrowRight, 
  Building2, 
  Loader2, 
  Lock, 
  ShieldCheck, 
  CheckCircle,
  Eye,
  EyeOff,
  AlertCircle
} from "lucide-react";

export default function Reset() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token");

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [resetData, setResetData] = useState<resetPassInterface>({ 
    token: "", 
    new_password: "", 
    verify_password: "" 
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (token) {
      setResetData(prev => ({ ...prev, token }));
    }
  }, [token]);

  const passwordError = resetData.verify_password!.length > 0 && 
                        resetData.new_password !== resetData.verify_password;

  const passwordStrength = useMemo(() => {
    const password = resetData.new_password;
    if (!password) return { strength: 0, label: '', color: '' };
    
    let strength = 0;
    if (password.length >= 8) strength++;
    if (password.length >= 12) strength++;
    if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
    if (/\d/.test(password)) strength++;
    if (/[^a-zA-Z0-9]/.test(password)) strength++;

    const levels = [
      { strength: 0, label: '', color: '' },
      { strength: 1, label: 'Très faible', color: 'bg-red-500' },
      { strength: 2, label: 'Faible', color: 'bg-orange-500' },
      { strength: 3, label: 'Moyen', color: 'bg-yellow-500' },
      { strength: 4, label: 'Fort', color: 'bg-green-500' },
      { strength: 5, label: 'Très fort', color: 'bg-green-600' },
    ];

    return levels[strength];
  }, [resetData.new_password]);

  const canSave = useMemo(() => {
    if (!resetData.new_password || resetData.new_password.length < 8) return false;
    if (!resetData.verify_password) return false;
    if (passwordError) return false;
    return true;
  }, [resetData.new_password, resetData.verify_password, passwordError]);

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

    try {
      const data: resetPassInterface = {
        token: resetData.token,
        new_password: resetData.new_password
      };

      const response = await sageService.resetPass(data);
      const success = response.success;

      if (success) {
        // Show success message briefly before redirect
        setTimeout(() => {
          navigate('/login');
        }, 1500);
      } else {
        setError("Erreur lors de la mise à jour du mot de passe");
      }
    } 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">
            <Lock className="w-8 h-8 text-[#338660]" />
          </div>
          <h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            Nouveau mot de passe
          </h2>
          <p className="text-gray-500 dark:text-gray-400 text-sm">
            Merci de renseigner un nouveau mot de passe afin de compléter la procédure de réinitialisation
          </p>
        </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">
              <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
              <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"
        >
          {/* New Password */}
          <div>
            <AuthInput
              icon={Lock}
              type={showPassword ? "text" : "password"}
              label="Nouveau mot de passe"
              placeholder="••••••••"
              value={resetData.new_password}
              onChange={(e) => setResetData({ ...resetData, new_password: e.target.value })}
              error={resetData.new_password.length > 0 && resetData.new_password.length < 8 ? "Le mot de passe doit contenir au moins 8 caractères" : undefined}
              rightElement={
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="text-gray-400 hover:text-gray-600 focus:outline-none"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              }
            />
            
            {/* Password Strength Indicator */}
            {resetData.new_password && (
              <div className="mt-2">
                <div className="flex gap-1 mb-1">
                  {[1, 2, 3, 4, 5].map((level) => (
                    <div
                      key={level}
                      className={`h-1 flex-1 rounded-full transition-all ${
                        level <= passwordStrength.strength
                          ? passwordStrength.color
                          : 'bg-gray-200 dark:bg-gray-700'
                      }`}
                    />
                  ))}
                </div>
                {passwordStrength.label && (
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    Force: {passwordStrength.label}
                  </p>
                )}
              </div>
            )}
          </div>

          {/* Confirm Password */}
          <div>
            <AuthInput
              icon={Lock}
              type={showConfirmPassword ? "text" : "password"}
              label="Confirmer le mot de passe"
              placeholder="••••••••"
              value={resetData.verify_password}
              onChange={(e) => setResetData({ ...resetData, verify_password: e.target.value })}
              error={passwordError ? "Les mots de passe ne correspondent pas" : undefined}
              rightElement={
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="text-gray-400 hover:text-gray-600 focus:outline-none"
                >
                  {showConfirmPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              }
            />
            
            {/* Password Match Indicator */}
            {resetData.verify_password!.length > 0 && !passwordError && resetData.new_password === resetData.verify_password && (
              <div className="flex items-center gap-2 mt-2 text-green-600 dark:text-green-400">
                <CheckCircle className="w-4 h-4" />
                <p className="text-xs">Les mots de passe correspondent</p>
              </div>
            )}
          </div>

          {/* Password Requirements */}
          <div className="p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <p className="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
              Le mot de passe doit contenir :
            </p>
            <ul className="space-y-1 text-xs text-gray-600 dark:text-gray-400">
              <li className="flex items-center gap-2">
                <span className={resetData.new_password.length >= 8 ? "text-green-600" : "text-gray-400"}>
                  {resetData.new_password.length >= 8 ? "✓" : "○"}
                </span>
                Au moins 8 caractères
              </li>
              <li className="flex items-center gap-2">
                <span className={/[A-Z]/.test(resetData.new_password) ? "text-green-600" : "text-gray-400"}>
                  {/[A-Z]/.test(resetData.new_password) ? "✓" : "○"}
                </span>
                Une lettre majuscule
              </li>
              <li className="flex items-center gap-2">
                <span className={/[a-z]/.test(resetData.new_password) ? "text-green-600" : "text-gray-400"}>
                  {/[a-z]/.test(resetData.new_password) ? "✓" : "○"}
                </span>
                Une lettre minuscule
              </li>
              <li className="flex items-center gap-2">
                <span className={/\d/.test(resetData.new_password) ? "text-green-600" : "text-gray-400"}>
                  {/\d/.test(resetData.new_password) ? "✓" : "○"}
                </span>
                Un chiffre
              </li>
            </ul>
          </div>

          <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" />
                Mise à jour en cours...
              </span>
            ) : (
              <span className="flex items-center gap-2">
                Mettre à jour le mot de passe
                <ArrowRight className="w-5 h-5" />
              </span>
            )}
          </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>
        </motion.div>
      </motion.div>
    </AuthLayout>
  );
}