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

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

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>
  );
}

type Props = {
  schoolBrand?: { name: string; code: string; logoUrl: string | null; primaryColor: string } | null;
};

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

  useEffect(() => {
    const username = new URLSearchParams(window.location.search).get('u');
    if (username) {
      form.setData('username', username);
    }
  }, []);

  return (
    <div className="al">
      <Head title="ورود" />
      <IosInstallPrompt />

      <AuthBackground />

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

      {/* Giant logo watermark behind the card */}
      <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 }}
      >
        {/* Brand header */}
        <motion.a
          href="/"
          className="al-brand"
          initial={{ opacity: 0, y: -12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.35, ease: eO }}
        >
          <img src={schoolBrand?.logoUrl ?? '/assets/images/logo/logo.png'} alt={schoolBrand?.name ?? 'دانشیار من'} className="al-brand-logo" />
          <div className="al-brand-name">
            <strong>{schoolBrand?.name ?? 'دانشیار من'}</strong>
            <small>{schoolBrand ? `کد مدرسه: ${schoolBrand.code}` : 'اتوماسیون هوشمند مدارس'}</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">ورود به حساب</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.div>
    </div>
  );
}
