import React, { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { X, Lock, Mail, User, Phone, ShieldCheck, Zap, ArrowLeft } from 'lucide-react';
import { useAuth } from '../context/AuthContext';

export const AuthModal: React.FC = () => {
  const {
    isAuthModalOpen,
    closeAuthModal,
    authModalMode,
    openAuthModal,
    login,
    register,
  } = useAuth();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [mobile, setMobile] = useState('');
  const [loading, setLoading] = useState(false);

  if (!isAuthModalOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      if (authModalMode === 'login') {
        await login(email, password);
      } else {
        await register(name, email, mobile, password);
      }
    } catch {
      // Error handled in AuthContext with toast
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
      {/* Backdrop */}
      <div onClick={closeAuthModal} className="fixed inset-0 bg-black/80 backdrop-blur-md" />

      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        className="relative w-full max-w-md bg-[#110926] border border-purple-500/30 rounded-3xl p-6 sm:p-8 shadow-2xl z-10 text-right overflow-hidden"
      >
        {/* Close Button */}
        <button
          onClick={closeAuthModal}
          className="absolute left-4 top-4 p-2 text-zinc-400 hover:text-white rounded-xl bg-[#1a0f35] border border-purple-500/20"
        >
          <X className="w-5 h-5" />
        </button>

        {/* Header */}
        <div className="text-center mb-6">
          <div className="w-12 h-12 rounded-2xl bg-purple-600/30 border border-purple-500/40 text-purple-300 mx-auto flex items-center justify-center mb-3">
            <Lock className="w-6 h-6" />
          </div>
          <h2 className="text-xl font-black text-white">
            {authModalMode === 'login' ? 'ورود به حساب کاربری ZaccShop' : 'ایجاد حساب کاربری جدید'}
          </h2>
          <p className="text-xs text-zinc-400 mt-1">
            {authModalMode === 'login'
              ? 'برای دسترسی به سفارش‌ها و لایسنس‌های خود وارد شوید.'
              : 'عضویت سریع در فروشگاه با شماره موبایل و ایمیل.'}
          </p>
        </div>

        {/* Auth Form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          {authModalMode === 'register' && (
            <div>
              <label className="block text-xs font-bold text-zinc-300 mb-1">
                نام و نام خانوادگی <span className="text-rose-400">*</span>
              </label>
              <div className="relative">
                <input
                  type="text"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="علی رضایی"
                  className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 pr-9 pl-3 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none"
                />
                <User className="w-4 h-4 text-purple-400 absolute right-3 top-1/2 -translate-y-1/2" />
              </div>
            </div>
          )}

          <div>
            <label className="block text-xs font-bold text-zinc-300 mb-1">
              ایمیل <span className="text-rose-400">*</span>
            </label>
            <div className="relative">
              <input
                type="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="name@example.com"
                className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 pr-9 pl-3 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none text-left font-mono"
                dir="ltr"
              />
              <Mail className="w-4 h-4 text-purple-400 absolute right-3 top-1/2 -translate-y-1/2" />
            </div>
          </div>

          {authModalMode === 'register' && (
            <div>
              <label className="block text-xs font-bold text-zinc-300 mb-1">
                شماره موبایل
              </label>
              <div className="relative">
                <input
                  type="tel"
                  value={mobile}
                  onChange={(e) => setMobile(e.target.value)}
                  placeholder="09120000000"
                  className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 pr-9 pl-3 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none text-left font-mono"
                  dir="ltr"
                />
                <Phone className="w-4 h-4 text-purple-400 absolute right-3 top-1/2 -translate-y-1/2" />
              </div>
            </div>
          )}

          <div>
            <label className="block text-xs font-bold text-zinc-300 mb-1">
              رمز عبور <span className="text-rose-400">*</span>
            </label>
            <div className="relative">
              <input
                type="password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="حداقل ۶ کاراکتر"
                className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 pr-9 pl-3 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none text-left font-mono"
                dir="ltr"
              />
              <Lock className="w-4 h-4 text-purple-400 absolute right-3 top-1/2 -translate-y-1/2" />
            </div>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full py-3 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white font-bold text-sm shadow-xl shadow-purple-600/30 transition-all hover:scale-[1.01] active:scale-95 disabled:opacity-50 mt-2"
          >
            {loading
              ? 'لطفاً صبر کنید...'
              : authModalMode === 'login'
              ? 'ورود به حساب'
              : 'ثبت‌نام و عضویت'}
          </button>
        </form>

        {/* Switch Mode */}
        <div className="mt-6 text-center text-xs text-zinc-400 border-t border-purple-900/30 pt-4">
          {authModalMode === 'login' ? (
            <span>
              حساب کاربری ندارید؟{' '}
              <button
                onClick={() => openAuthModal('register')}
                className="text-purple-300 hover:text-white font-bold underline mr-1"
              >
                ثبت‌نام کنید
              </button>
            </span>
          ) : (
            <span>
              قبلاً ثبت‌نام کرده‌اید؟{' '}
              <button
                onClick={() => openAuthModal('login')}
                className="text-purple-300 hover:text-white font-bold underline mr-1"
              >
                وارد شوید
              </button>
            </span>
          )}
        </div>

      </motion.div>
    </div>
  );
};
