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

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.28 } },
};

const rings = [
  { size: 320, dur: 22, color: 'rgba(14,166,120,0.28)', dot: '#0EA678', ccw: false },
  { size: 228, dur: 15, color: 'rgba(56,189,248,0.22)', dot: '#38BDF8', ccw: true  },
  { size: 148, dur: 34, color: 'rgba(139,92,246,0.20)', dot: '#818CF8', ccw: false },
] as const;

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.94
               M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19
               m-6.72-1.07a3 3 0 11-4.24-4.24"/>
      <line x1="1" y1="1" x2="23" y2="23"/>
    </svg>
  );
}

export default function Login() {
  const form = useForm({ username: '', password: '', remember: false });
  const [showPass, setShowPass] = useState(false);

  return (
    <div className="al">
      <Head title="ورود">
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
        <link
          href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800&display=swap"
          rel="stylesheet"
        />
      </Head>

      {/* Ambient glows */}
      <div className="al-orb al-orb--1" />
      <div className="al-orb al-orb--2" />
      <div className="al-orb al-orb--3" />

      {/* ══════════════════ RIGHT — Visual panel (RTL: first = rightmost) ══════════════════ */}
      <motion.section
        className="al-right"
        initial={{ opacity: 0, x: -60 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ duration: 0.8, ease: eO, delay: 0.12 }}
        aria-hidden="true"
      >
        <div className="al-grid-bg" />

        {/* Orbital system */}
        <div className="al-solar">
          {rings.map((r, i) => (
            <motion.div
              key={i}
              className="al-ring"
              style={{ width: r.size, height: r.size, borderColor: r.color }}
              animate={{ rotate: r.ccw ? -360 : 360 }}
              transition={{ duration: r.dur, repeat: Infinity, ease: 'linear' }}
            >
              <span
                className="al-ring-dot"
                style={{ background: r.dot, boxShadow: `0 0 14px 3px ${r.dot}` }}
              />
            </motion.div>
          ))}

          {/* Core */}
          <motion.div
            className="al-core"
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ duration: 0.9, delay: 0.55, ease: [0.34, 1.56, 0.64, 1] as const }}
          >
            <motion.div
              className="al-core-inner"
              animate={{
                boxShadow: [
                  '0 0 40px rgba(14,166,120,0.45)',
                  '0 0 85px rgba(14,166,120,0.78)',
                  '0 0 40px rgba(14,166,120,0.45)',
                ],
              }}
              transition={{ duration: 3.2, repeat: Infinity, ease: 'easeInOut' }}
            >
              <span>د</span>
            </motion.div>
          </motion.div>
        </div>

        {/* Headline */}
        <motion.div
          className="al-right-brand"
          initial={{ opacity: 0, y: 22 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.65, delay: 0.78, ease: eO }}
        >
          <h2>دانشیار من</h2>
          <p>هوشمندترین پنل مدیریت مدارس ایران</p>
        </motion.div>

        {/* Feature chips */}
        <div className="al-feats">
          {[
            { icon: 'bi-mortarboard-fill',  label: 'مدیریت کامل مدرسه', delay: 0.95 },
            { icon: 'bi-shield-fill-check', label: 'امنیت و رمزنگاری',  delay: 1.10 },
            { icon: 'bi-headset',           label: 'پشتیبانی ۲۴/۷',    delay: 1.25 },
          ].map(({ icon, label, delay }) => (
            <motion.div
              key={label}
              className="al-feat"
              initial={{ opacity: 0, x: -22 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay, ease: eO }}
            >
              <span className="al-feat-icon"><i className={`bi ${icon}`} /></span>
              <span>{label}</span>
            </motion.div>
          ))}
        </div>
      </motion.section>

      {/* ══════════════════ LEFT — Form panel (RTL: second = leftmost) ══════════════════ */}
      <motion.section
        className="al-left"
        initial={{ opacity: 0, x: 60 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ duration: 0.65, ease: eO }}
      >
        <motion.a
          href="/"
          className="al-brand"
          initial={{ opacity: 0, y: -16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.12, ease: eO }}
        >
          <span className="al-brand-icon">د</span>
          <span className="al-brand-name">
            <strong>دانشیار من</strong>
            <small>اتوماسیون مدارس</small>
          </span>
        </motion.a>

        <motion.div className="al-form-wrap" variants={stagger} initial="hidden" animate="show">
          <motion.div variants={fadeUp} transition={{ duration: 0.5 }}>
            <span className="al-eyebrow">به سامانه خوش آمدید</span>
            <h1 className="al-title">ورود به حساب</h1>
            <p className="al-sub">اطلاعات کاربری خود را وارد کنید</p>
          </motion.div>

          <form
            className="al-form"
            onSubmit={(e) => { e.preventDefault(); form.post('/login'); }}
          >
            {/* Username */}
            <motion.div variants={fadeUp} transition={{ duration: 0.45 }} className="al-field">
              <div className="al-field-inner">
                <input
                  id="al-un"
                  className="al-input"
                  type="text"
                  placeholder=" "
                  value={form.data.username}
                  onChange={(e) => form.setData('username', e.target.value)}
                  autoComplete="username"
                />
                <label htmlFor="al-un" className="al-label">نام کاربری</label>
              </div>
              <AnimatePresence>
                {form.errors.username && (
                  <motion.p
                    className="al-error"
                    initial={{ opacity: 0, y: -4 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.2 }}
                  >
                    {form.errors.username}
                  </motion.p>
                )}
              </AnimatePresence>
            </motion.div>

            {/* Password */}
            <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={form.data.password}
                  onChange={(e) => form.setData('password', e.target.value)}
                  autoComplete="current-password"
                />
                <label htmlFor="al-pw" className="al-label">رمز عبور</label>
                <button
                  type="button"
                  className="al-eye"
                  onClick={() => setShowPass((s) => !s)}
                  tabIndex={-1}
                  aria-label={showPass ? 'مخفی کردن رمز' : 'نمایش رمز'}
                >
                  <AnimatePresence mode="wait">
                    {showPass ? (
                      <motion.span
                        key="open"
                        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="closed"
                        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>
                {form.errors.password && (
                  <motion.p
                    className="al-error"
                    initial={{ opacity: 0, y: -4 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.2 }}
                  >
                    {form.errors.password}
                  </motion.p>
                )}
              </AnimatePresence>
            </motion.div>

            {/* Remember + Forgot */}
            <motion.div variants={fadeUp} transition={{ duration: 0.4 }} className="al-row">
              <label className="al-check">
                <input
                  type="checkbox"
                  checked={form.data.remember}
                  onChange={(e) => form.setData('remember', e.target.checked)}
                />
                <span className="al-check-box" />
                <span className="al-check-label">مرا به خاطر بسپار</span>
              </label>
              <Link href="/forgot-password" className="al-forgot">فراموشی رمز</Link>
            </motion.div>

            {/* Submit */}
            <motion.div variants={fadeUp} transition={{ duration: 0.4 }}>
              <motion.button
                className="al-submit"
                type="submit"
                disabled={form.processing}
                whileHover={!form.processing ? { scale: 1.016, boxShadow: '0 20px 56px rgba(14,166,120,0.62)' } : {}}
                whileTap={!form.processing ? { scale: 0.984 } : {}}
              >
                <AnimatePresence mode="wait">
                  {form.processing ? (
                    <motion.span
                      key="spin"
                      className="al-spin"
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      exit={{ opacity: 0 }}
                    />
                  ) : (
                    <motion.span
                      key="txt"
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      exit={{ opacity: 0 }}
                      transition={{ duration: 0.15 }}
                    >
                      ورود به سامانه
                    </motion.span>
                  )}
                </AnimatePresence>
              </motion.button>
            </motion.div>
          </form>

          <motion.div variants={fadeUp} transition={{ duration: 0.4 }} className="al-foot">
            <Link href="/" className="al-back">
              <i className="bi bi-arrow-right" />
              بازگشت به صفحه اصلی
            </Link>
          </motion.div>
        </motion.div>
      </motion.section>
    </div>
  );
}
