import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { AuthBackground } from '@/Components/Auth/AuthBackground';

type Step = 'identifier' | 'code' | 'password';

const eO = 'easeOut' as const;
const fadeUp = { hidden: { opacity: 0, y: 22 }, show: { opacity: 1, y: 0 } };
const stagger = {
  hidden: {},
  show: { transition: { staggerChildren: 0.09, delayChildren: 0.2 } },
};

function EyeOpen() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
    </svg>
  );
}
function EyeClosed() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
      <line x1="1" y1="1" x2="23" y2="23"/>
    </svg>
  );
}

export default function ForgotPassword({ smsReady }: { smsReady: boolean }) {
  const { props } = usePage<{ flash?: { success?: string; error?: string } }>();
  const [step, setStep] = useState<Step>('identifier');
  const [showPass, setShowPass] = useState(false);

  const identifierForm = useForm({ identifier: '' });
  const codeForm = useForm({ code: '' });
  const passwordForm = useForm({ password: '', password_confirmation: '' });

  const sendCode = (e: React.FormEvent) => {
    e.preventDefault();
    identifierForm.post('/forgot-password/send-code', {
      preserveScroll: true,
      onSuccess: () => setStep('code'),
    });
  };

  const verifyCode = (e: React.FormEvent) => {
    e.preventDefault();
    codeForm.post('/forgot-password/verify', {
      preserveScroll: true,
      onSuccess: () => setStep('password'),
    });
  };

  const resetPassword = (e: React.FormEvent) => {
    e.preventDefault();
    passwordForm.post('/forgot-password/reset', { preserveScroll: true });
  };

  return (
    <div className="al">
      <Head title="بازیابی رمز عبور" />
      <AuthBackground />
      <div className="al-orb al-orb--1" />
      <div className="al-orb al-orb--2" />
      <div className="al-logo-watermark" aria-hidden="true">
        <img src="/assets/images/logo/daneshyar-book-persian.png" alt="" />
      </div>

      <motion.div
        className="al-card"
        initial={{ opacity: 0, y: 30, scale: 0.97 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.7, ease: eO, delay: 0.1 }}
      >
        <motion.a
          href="/"
          className="al-brand"
          initial={{ opacity: 0, y: -12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.3, ease: eO }}
        >
          <img src="/assets/images/logo/logo.png" alt="دانشیار من" className="al-brand-logo" />
          <div className="al-brand-name">
            <strong>دانشیار من</strong>
            <small>اتوماسیون هوشمند مدارس</small>
          </div>
        </motion.a>

        <motion.div variants={stagger} initial="hidden" animate="show">
          <motion.div variants={fadeUp} transition={{ duration: 0.5 }}>
            <span className="al-eyebrow">بازیابی رمز عبور</span>
            <h1 className="al-title">
              {step === 'identifier' && 'بازیابی رمز'}
              {step === 'code' && 'کد تایید'}
              {step === 'password' && 'رمز جدید'}
            </h1>
            <p className="al-sub">
              {step === 'identifier' && 'شماره موبایل یا نام کاربری خود را وارد کنید'}
              {step === 'code' && 'کد ۵ رقمی پیامک‌شده را وارد کنید'}
              {step === 'password' && 'رمز عبور جدید را تعیین کنید'}
            </p>
          </motion.div>

          {props.flash?.success && (
            <motion.div
              variants={fadeUp}
              transition={{ duration: 0.3 }}
              style={{
                background: 'var(--color-primary-soft, #D9F3EA)',
                borderRadius: 10,
                color: 'var(--color-primary-active, #0a7a5a)',
                fontSize: '0.88rem',
                padding: '0.65rem 0.9rem',
                marginBottom: '0.5rem',
              }}
            >
              {props.flash.success}
            </motion.div>
          )}

          {!smsReady ? (
            <motion.div variants={fadeUp} transition={{ duration: 0.4 }}>
              <p className="al-sub" style={{ color: 'var(--color-danger, #e53e3e)' }}>
                سرویس پیامک فعال نیست. برای بازیابی رمز با مدیر مدرسه تماس بگیرید.
              </p>
              <Link href="/login" className="al-submit" style={{ display: 'block', textAlign: 'center', marginTop: '1rem' }}>
                بازگشت به ورود
              </Link>
            </motion.div>
          ) : (
            <>
              {step === 'identifier' && (
                <form className="al-form" onSubmit={sendCode}>
                  <motion.div variants={fadeUp} transition={{ duration: 0.45 }} className="al-field">
                    <div className="al-field-inner">
                      <input
                        id="al-id"
                        className="al-input"
                        type="text"
                        placeholder=" "
                        value={identifierForm.data.identifier}
                        onChange={(e) => identifierForm.setData('identifier', e.target.value)}
                        autoComplete="username"
                        dir="ltr"
                      />
                      <label htmlFor="al-id" className="al-label">موبایل یا نام کاربری</label>
                    </div>
                    <AnimatePresence>
                      {identifierForm.errors.identifier && (
                        <motion.p className="al-error" initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} transition={{ duration: 0.2 }}>
                          {identifierForm.errors.identifier}
                        </motion.p>
                      )}
                    </AnimatePresence>
                  </motion.div>
                  <motion.div variants={fadeUp} transition={{ duration: 0.4 }}>
                    <motion.button
                      className="al-submit"
                      type="submit"
                      disabled={identifierForm.processing}
                      whileHover={!identifierForm.processing ? { scale: 1.016, boxShadow: '0 20px 56px rgba(14,166,120,0.62)' } : {}}
                      whileTap={!identifierForm.processing ? { scale: 0.984 } : {}}
                    >
                      {identifierForm.processing ? <span className="al-spin" /> : 'ارسال کد بازیابی'}
                    </motion.button>
                  </motion.div>
                </form>
              )}

              {step === 'code' && (
                <form className="al-form" onSubmit={verifyCode}>
                  <motion.div variants={fadeUp} transition={{ duration: 0.45 }} className="al-field">
                    <div className="al-field-inner">
                      <input
                        id="al-code"
                        className="al-input"
                        type="text"
                        placeholder=" "
                        value={codeForm.data.code}
                        onChange={(e) => codeForm.setData('code', e.target.value)}
                        maxLength={5}
                        dir="ltr"
                        inputMode="numeric"
                        autoFocus
                      />
                      <label htmlFor="al-code" className="al-label">کد تایید (۵ رقم)</label>
                    </div>
                    <AnimatePresence>
                      {codeForm.errors.code && (
                        <motion.p className="al-error" initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} transition={{ duration: 0.2 }}>
                          {codeForm.errors.code}
                        </motion.p>
                      )}
                    </AnimatePresence>
                  </motion.div>
                  <motion.div variants={fadeUp} transition={{ duration: 0.4 }}>
                    <motion.button
                      className="al-submit"
                      type="submit"
                      disabled={codeForm.processing}
                      whileHover={!codeForm.processing ? { scale: 1.016, boxShadow: '0 20px 56px rgba(14,166,120,0.62)' } : {}}
                      whileTap={!codeForm.processing ? { scale: 0.984 } : {}}
                    >
                      {codeForm.processing ? <span className="al-spin" /> : 'تایید کد'}
                    </motion.button>
                  </motion.div>
                  <motion.div variants={fadeUp} transition={{ duration: 0.35 }} className="al-foot">
                    <button type="button" className="al-back" style={{ background: 'none', border: 'none', cursor: 'pointer' }} onClick={() => setStep('identifier')}>
                      <i className="bi bi-arrow-right" /> ارسال دوباره کد
                    </button>
                  </motion.div>
                </form>
              )}

              {step === 'password' && (
                <form className="al-form" onSubmit={resetPassword}>
                  <motion.div variants={fadeUp} transition={{ duration: 0.45 }} className="al-field">
                    <div className="al-field-inner">
                      <input
                        id="al-pw"
                        className="al-input"
                        type={showPass ? 'text' : 'password'}
                        placeholder=" "
                        value={passwordForm.data.password}
                        onChange={(e) => passwordForm.setData('password', e.target.value)}
                        autoComplete="new-password"
                      />
                      <label htmlFor="al-pw" className="al-label">رمز جدید (حداقل ۸ کاراکتر)</label>
                      <button type="button" className="al-eye" onClick={() => setShowPass(s => !s)} tabIndex={-1}>
                        <AnimatePresence mode="wait">
                          {showPass
                            ? <motion.span key="o" initial={{ opacity: 0, scale: 0.6 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.6 }} transition={{ duration: 0.15 }}><EyeOpen /></motion.span>
                            : <motion.span key="c" initial={{ opacity: 0, scale: 0.6 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.6 }} transition={{ duration: 0.15 }}><EyeClosed /></motion.span>
                          }
                        </AnimatePresence>
                      </button>
                    </div>
                    <AnimatePresence>
                      {passwordForm.errors.password && (
                        <motion.p className="al-error" initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} transition={{ duration: 0.2 }}>
                          {passwordForm.errors.password}
                        </motion.p>
                      )}
                    </AnimatePresence>
                  </motion.div>
                  <motion.div variants={fadeUp} transition={{ duration: 0.43 }} className="al-field">
                    <div className="al-field-inner">
                      <input
                        id="al-pwc"
                        className="al-input"
                        type={showPass ? 'text' : 'password'}
                        placeholder=" "
                        value={passwordForm.data.password_confirmation}
                        onChange={(e) => passwordForm.setData('password_confirmation', e.target.value)}
                        autoComplete="new-password"
                      />
                      <label htmlFor="al-pwc" className="al-label">تکرار رمز جدید</label>
                    </div>
                  </motion.div>
                  <motion.div variants={fadeUp} transition={{ duration: 0.4 }}>
                    <motion.button
                      className="al-submit"
                      type="submit"
                      disabled={passwordForm.processing}
                      whileHover={!passwordForm.processing ? { scale: 1.016, boxShadow: '0 20px 56px rgba(14,166,120,0.62)' } : {}}
                      whileTap={!passwordForm.processing ? { scale: 0.984 } : {}}
                    >
                      {passwordForm.processing ? <span className="al-spin" /> : 'ثبت رمز جدید'}
                    </motion.button>
                  </motion.div>
                </form>
              )}
            </>
          )}

          <motion.div variants={fadeUp} transition={{ duration: 0.35 }} className="al-foot">
            <Link href="/login" className="al-back">
              <i className="bi bi-arrow-right" /> بازگشت به ورود
            </Link>
          </motion.div>
        </motion.div>
      </motion.div>
    </div>
  );
}
