
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'motion/react';

// UPDATE (Tab-Titel-Umbau): vorheriger Inhalt von app/admin/page.tsx,
// unveraendert hierher verschoben. app/admin/page.tsx ist jetzt ein
// winziger Server-Component-Wrapper, der nur noch "metadata" (Seiten-Titel)
// setzt und diese Komponente rendert.
export function AdminLoginClient() {
  const router = useRouter();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [totpCode, setTotpCode] = useState('');
  const [needsTotp, setNeedsTotp] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/admin/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password, totpCode: totpCode || undefined }),
      });
      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Login fehlgeschlagen');
        return;
      }

      if (data.requiresTotp) {
        setNeedsTotp(true);
        return;
      }

      router.push('/admin/dashboard');
    } catch {
      setError('Verbindungsfehler. Bitte erneut versuchen.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="relative flex flex-col items-center justify-center min-h-dvh-safe p-6 gap-6 overflow-x-hidden overflow-y-auto bg-neutral-950 safe-top safe-bottom">
      <div
        aria-hidden
        className="pointer-events-none absolute -top-1/3 left-1/2 -translate-x-1/2 h-[600px] w-[600px] rounded-full opacity-30 blur-3xl"
        style={{
          background:
            'radial-gradient(circle, rgba(254,60,114,0.5) 0%, rgba(0,194,168,0.25) 45%, transparent 75%)',
        }}
      />

      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5, ease: 'easeOut' }}
        className="relative z-10 flex flex-col items-center gap-2"
      >
        <h1 className="text-3xl font-extrabold tracking-tight bg-gradient-to-r from-yumder-pink to-yumder-teal bg-clip-text text-transparent">
          Yumder Admin
        </h1>
        <p className="text-neutral-400 text-sm">Zugang nur fuer autorisierte Personen.</p>
      </motion.div>

      <motion.form
        layout
        onSubmit={handleSubmit}
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, delay: 0.05 }}
        className="relative z-10 w-full max-w-sm flex flex-col gap-3 rounded-3xl border border-white/10 bg-neutral-900/60 backdrop-blur-xl p-6 shadow-2xl"
      >
        <AnimatePresence mode="popLayout">
          {!needsTotp ? (
            <motion.div
              key="creds"
              layout
              initial={{ opacity: 0, x: -8 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -8 }}
              transition={{ duration: 0.25 }}
              className="flex flex-col gap-3"
            >
              <input
                placeholder="Benutzername"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                autoComplete="username"
                className="bg-neutral-800/70 rounded-xl px-4 py-3 border border-white/5 focus:border-yumder-pink/60 outline-none transition-colors"
              />
              <input
                type="password"
                placeholder="Passwort"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoComplete="current-password"
                className="bg-neutral-800/70 rounded-xl px-4 py-3 border border-white/5 focus:border-yumder-pink/60 outline-none transition-colors"
              />
            </motion.div>
          ) : (
            <motion.div
              key="totp"
              layout
              initial={{ opacity: 0, x: 8 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: 8 }}
              transition={{ duration: 0.25 }}
              className="flex flex-col gap-3"
            >
              <p className="text-sm text-neutral-400">
                Gib den 6-stelligen Code aus deiner Authenticator-App ein.
              </p>
              <input
                placeholder="123456"
                value={totpCode}
                onChange={(e) => setTotpCode(e.target.value)}
                maxLength={6}
                inputMode="numeric"
                autoFocus
                className="bg-neutral-800/70 rounded-xl px-4 py-3 border border-white/5 focus:border-yumder-teal/60 outline-none transition-colors text-center text-lg tracking-widest"
              />
            </motion.div>
          )}
        </AnimatePresence>

        <motion.button
          type="submit"
          disabled={loading}
          whileTap={{ scale: 0.97 }}
          className="relative overflow-hidden bg-gradient-to-r from-yumder-pink to-pink-500 font-semibold rounded-xl px-4 py-3 disabled:opacity-50 shadow-[0_0_25px_rgba(254,60,114,0.4)]"
        >
          {loading ? 'Pruefe...' : needsTotp ? 'Code bestaetigen' : 'Anmelden'}
        </motion.button>

        <AnimatePresence>
          {error && (
            <motion.p
              initial={{ opacity: 0 }}
              animate={{ opacity: 1, x: [0, -6, 6, -4, 4, 0] }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.4 }}
              className="text-red-400 text-sm text-center"
            >
              {error}
            </motion.p>
          )}
        </AnimatePresence>
      </motion.form>
    </main>
  );
}
