import { useState, useEffect } from "react";
import { useNavigate, Link, useSearchParams } from "react-router-dom";
import { AlertCircle, Eye, EyeOff, Loader2, Lightbulb } from "lucide-react";
import { motion } from "framer-motion";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { login } from "@/lib/auth";
import { toast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { useMetaTags } from "@/hooks/useMetaTags";
import { checkUserRole } from "@/lib/admin";
import { getSubdomain } from "@/lib/subdomain";
import { resolveOnboardingState } from "@/lib/onboarding";
import { useSchoolBranding } from "@/contexts/SchoolBrandingContext";
import { canAccessWhiteLabelStudentApp, rejectWhiteLabelAccess } from "@/lib/white-label-access";
import nepeduaiLogo from "@/assets/nepeduai-logo.png";
import { AppleSignIn } from "@/components/auth/AppleSignIn";
import { OfflineAuthFallback } from "@/components/auth/OfflineAuthFallback";
import { applyRememberPreference, getRememberedIdentifier, getRememberPreference } from "@/lib/remember-me";

import { db } from "@/lib/backend";
/* ──────────────────────────────────────────────────────────────
 Login — editorial business vibe
 Matches landing page: light bg, asymmetric, SectionLabel rhythm,
 Playfair italic accent, soft glows, no shaders.
 ────────────────────────────────────────────────────────────── */

const CONTEXT: Record<string, { label: string; lead: string; italic: string; sub: string }> = {
 teacher: {
 label: "Teacher portal",
 lead: "Back to the",
 italic: "staffroom.",
 sub: "Sign in to mark attendance, post homework, and update marks — without the WhatsApp groups.",
 },
 parent: {
 label: "Parent portal",
 lead: "How was school",
 italic: "today?",
 sub: "Sign in to see attendance, marks, fees and notices the moment they're posted — no need to wait for the parent meeting.",
 },
 main: {
 label: "Welcome back! ",
 lead: "Ready to jump",
 italic: "back in?",
 sub: "Your study streaks, AI insights, and learning progress are waiting for you.",
 },
};

const Login = () => {
 const subdomain = getSubdomain();
 const { branding } = useSchoolBranding();
 const schoolName = branding?.display_name?? null;
 const ctx = schoolName
? {
 label: `${schoolName} portal`,
 lead: "Welcome back to",
 italic: schoolName,
 sub: branding?.principal_message ||
 branding?.tagline ||
 `Sign in to access ${schoolName}'s notices, marks, attendance and more.`,
 }
 : (CONTEXT[subdomain] || CONTEXT.main);
 useMetaTags({
 title: schoolName? `Sign in — ${schoolName}` : "Sign In",
 description: schoolName
? `Sign in to ${schoolName}'s student & parent portal.`
 : "Sign in to NepEduAI — Nepal's Smart Education Operating System.",
 });
 const [showPassword, setShowPassword] = useState(false);
 const [email, setEmail] = useState(() => getRememberedIdentifier());
 const [password, setPassword] = useState("");
 const [remember, setRemember] = useState(() => getRememberPreference());
 const [loading, setLoading] = useState(false);
 const [forgotOpen, setForgotOpen] = useState(false);
 const [resetEmail, setResetEmail] = useState("");
 const [resetLoading, setResetLoading] = useState(false);
 const [searchParams, setSearchParams] = useSearchParams();
 const errorCode = searchParams.get("error");
 const inlineError =
 errorCode === "wrong_school"
? schoolName
? `Invalid user. This account is not registered with ${schoolName}.`
 : "Invalid user. This account is not registered with this school."
 : null;
 const navigate = useNavigate();

 const redirectByRole = async (userId: string) => {
 const sub = getSubdomain();
 const hostname = window.location.hostname.toLowerCase();
 const isProdHost = hostname === "nepeduai.com" || hostname.endsWith(".nepeduai.com");

 // Bulk-created accounts must change their password before going anywhere else.
 try {
 const { data: forcedProfile } = await (db.from("profiles") as any)
.select("must_change_password")
.eq("id", userId)
.maybeSingle();
 if (forcedProfile?.must_change_password) {
 navigate("/change-password", { replace: true });
 return;
 }
 } catch {
 // non-fatal — fall through to normal redirect
 }

 if (branding?.school_id) {
 const allowed = await canAccessWhiteLabelStudentApp(userId, branding.school_id);
 if (!allowed) {
 await rejectWhiteLabelAccess();
 return;
 }

 // Skip the extra profile fetch + onboarding round-trip on white-label
 // schools: school students are pre-onboarded by their school admin,
 // so go straight to the dashboard. (If a real onboarding is required
 // later, Dashboard's own guard will kick in — we just stop blocking
 // the perceived login latency here.)
 navigate("/dashboard", { replace: true });
 return;
 }

    // Fetch role + profile IN PARALLEL — these are independent network calls.
    // Instead of using getUserRoles() which re-fetches auth.getUser(), we query the DB directly
    // since we already have the authenticated userId from the session. This cuts login time in half.
    const [rolesRes, profileRes] = await Promise.all([
      db.from("user_roles").select("role").eq("user_id", userId),
      db.from("profiles").select("grade,onboarding_completed").eq("id", userId).maybeSingle(),
    ]);
    const roles = rolesRes.data ? rolesRes.data.map(r => r.role as string) : ["user"];
    const profile = profileRes.data ?? undefined;

    // Check if the user is authorized for the current subdomain portal
    if (sub === "school" && roles.includes("school_admin")) {
      navigate("/dashboard", { replace: true });
      return;
    }
 if (sub === "teacher" && roles.includes("teacher")) {
 navigate("/dashboard", { replace: true });
 return;
 }
 if (sub === "parent" && roles.includes("parent")) {
 navigate("/dashboard", { replace: true });
 return;
 }
 if (sub === "admin" && roles.includes("admin")) {
 navigate("/dashboard", { replace: true });
 return;
 }

 // If they aren't explicitly signing into a portal they have access to,
 // fall back to their primary role logic to redirect them to their main home.
 const primaryRole = roles.includes("admin") ? "admin"
 : roles.includes("school_admin") ? "school_admin"
 : roles.includes("teacher") ? "teacher"
 : roles.includes("parent") ? "parent"
 : "user";

 // On dedicated portal subdomains, routes are root-level (no /school-admin, /teacher prefix)
 switch (primaryRole) {
 case "admin":
 // Admins MUST use the admin subdomain. If they signed in anywhere else
 // in production, sign them out and bounce them to adminmanager.nepeduai.com.
 if (sub!== "admin") {
 if (isProdHost) {
 await supabase.auth.signOut();
 toast({
 title: "Wrong portal",
 description: "Admins must sign in at adminmanager.nepeduai.com",
 variant: "destructive",
 });
 window.location.href = "https://adminmanager.nepeduai.com/login";
 return;
 }
 // In dev/preview: send to the admin login route
 navigate("/admin/login", { replace: true });
 return;
 }
 navigate("/dashboard", { replace: true });
 return;
 case "school_admin":
 if (isProdHost && sub!== "school" && sub!== "admin") {
 window.location.href = "https://school.nepeduai.com/login";
 return;
 }
 navigate(sub === "school"? "/dashboard" : "/school-admin/dashboard", { replace: true });
 return;
 case "teacher":
 if (isProdHost && sub!== "teacher" && sub!== "admin") {
 window.location.href = "https://teacher.nepeduai.com/login";
 return;
 }
 navigate(sub === "teacher"? "/dashboard" : "/teacher/dashboard", { replace: true });
 return;
 case "parent":
 if (isProdHost && sub!== "parent" && sub!== "admin") {
 window.location.href = "https://parent.nepeduai.com/login";
 return;
 }
 navigate(sub === "parent"? "/dashboard" : "/parent/dashboard", { replace: true });
 return;
 default: {
 // Students should never land on portal subdomains
 if (sub === "school" || sub === "teacher" || sub === "parent" || sub === "admin") {
 window.location.href = "https://nepeduai.com/dashboard";
 return;
 }
 const onboarding = await resolveOnboardingState(userId, primaryRole, profile);
 navigate(onboarding.requiresOnboarding? "/onboarding" : "/dashboard", { replace: true });
 }
 }
 };

 useEffect(() => {
 const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => {
 if (event === "SIGNED_IN" && session) redirectByRole(session.user.id);
 });
 return () => subscription.unsubscribe();
 }, [branding?.school_id, navigate]);

 const handleSubmit = async (e: React.FormEvent) => {
 e.preventDefault();
 if (!email.trim() ||!password.trim()) {
 toast({ title: "Missing fields", description: "Please enter your email/username and password.", variant: "destructive" });
 return;
 }
 setLoading(true);
 applyRememberPreference(email.trim(), remember);
 const result = await login(email, password);
 if (result.error) {
 const msg = result.error.includes("Invalid login")
? "Incorrect email/username or password. Please try again."
 : result.error;
 toast({ title: "Sign in failed", description: msg, variant: "destructive" });
 }
 setLoading(false);
 };

 const handleForgotPassword = async () => {
 if (!resetEmail.trim()) {
 toast({ title: "Enter your email", description: "Please enter the email you signed up with.", variant: "destructive" });
 return;
 }
 setResetLoading(true);
 const { error } = await supabase.auth.resetPasswordForEmail(resetEmail, {
 redirectTo: `${window.location.origin}/settings`,
 });
 if (error) toast({ title: "Error", description: "Could not send reset email. Please check the address and try again.", variant: "destructive" });
 else {
 toast({ title: "Check your inbox", description: "We've sent a password reset link to your email." });
 setForgotOpen(false);
 }
 setResetLoading(false);
 };

 return (
 <div className="relative min-h-dvh overflow-hidden bg-gradient-to-br from-primary/5 via-white to-primary/10 dark:from-background dark:via-background/95 dark:to-background/90 text-foreground">
 {/* Soft floating background blobs for glassmorphic depth */}
 <div className="absolute -top-[20%] -left-[10%] w-[50%] h-[50%] rounded-full bg-primary/20 blur-[120px] pointer-events-none" />
 <div className="absolute top-[40%] -right-[10%] w-[40%] h-[60%] rounded-full bg-secondary/10 blur-[140px] pointer-events-none" />

 {/* Top bar — minimal */}
 <header className="relative z-10 mx-auto flex max-w-[1200px] items-center justify-between px-6 pt-8">
 <Link to="/" className="inline-flex items-center gap-2.5">
 <img
 src={branding?.logo_url || nepeduaiLogo}
 alt={schoolName || "NepEduAI"}
 className="h-9 w-9 rounded-xl object-cover"
 loading="lazy"
 width={36}
 height={36}
 />
 <span className="text-xl font-black tracking-tight">
 {schoolName? (
 <span className="text-foreground">{schoolName}</span>
 ) : (
 <>
 <span className="text-primary">Nep</span>
 <span className="text-foreground">EduAI</span>
 </>
 )}
 </span>
 </Link>
 {!schoolName && (
 <Link
 to="/signup"
 className="hidden text-sm font-semibold text-muted-foreground transition-colors hover:text-foreground sm:inline-flex"
 >
 Create account →
 </Link>
 )}
 </header>

 {/* MAIN */}
 <main className="relative z-10 mx-auto grid max-w-[1200px] items-center gap-16 px-6 py-16 md:py-24 lg:grid-cols-[1.15fr_0.85fr] lg:gap-20">
 {/* LEFT — editorial copy */}
 <motion.div
 initial={{ opacity: 0, y: 24 }}
 animate={{ opacity: 1, y: 0 }}
 transition={{ duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
 className="hidden lg:block"
 >
 {/* Overline — SectionLabel rhythm */}
 <div className="flex items-center gap-3">
 <span className="h-px w-10 bg-primary/30" />
 <p className="text-[12px] font-bold uppercase tracking-[0.2em] text-primary/80">
 {ctx.label}
 </p>
 </div>

 {/* Heading */}
 <h1 className="mt-8 text-5xl font-extrabold leading-[1.1] tracking-tight text-foreground lg:text-6xl">
 {ctx.lead}{" "}
 <span className="text-primary">
 {ctx.italic}
 </span>
 </h1>

 <p className="mt-6 max-w-md text-[17px] font-medium leading-relaxed text-muted-foreground">{ctx.sub}</p>

 {/* Editorial pull-quote / school principal card */}
 {schoolName && branding? (
 <div className="mt-12 max-w-md overflow-hidden rounded-3xl border border-white/40 dark:border-zinc-800 bg-white/60 dark:bg-zinc-900/60 backdrop-blur-md shadow-sm">
 {branding.cover_image_url && (
 <div
 className="h-32 w-full bg-cover bg-center"
 style={{ backgroundImage: `url(${branding.cover_image_url})` }}
 />
 )}
 <div className="p-7">
 {branding.principal_message && (
 <p className="text-[16px] font-medium leading-relaxed text-foreground italic">
 &ldquo;{branding.principal_message}&rdquo;
 </p>
 )}
 <div className="mt-5 flex items-center gap-3 border-t border-black/5 pt-4">
 {branding.principal_photo_url && (
 <img
 src={branding.principal_photo_url}
 alt={branding.principal_name || "Principal"}
 className="h-10 w-10 rounded-full object-cover"
 />
 )}
 <div className="flex flex-col">
 {branding.principal_name && (
 <span className="text-[14px] font-bold text-foreground">{branding.principal_name}</span>
 )}
 <span className="text-[11px] font-bold uppercase tracking-[0.15em] text-muted-foreground">
 Principal · {schoolName}
 </span>
 </div>
 </div>
 </div>
 </div>
 ) : (
 <div className="mt-12 max-w-md rounded-3xl border border-white/60 dark:border-zinc-800 bg-white/70 dark:bg-zinc-900/60 backdrop-blur-xl p-7 shadow-sm">
 <div className="flex items-center gap-3 mb-4">
 <div className="grid h-10 w-10 place-items-center rounded-2xl bg-secondary/15 text-secondary">
 <Lightbulb className="h-5 w-5" />
 </div>
 <h3 className="text-[16px] font-bold text-foreground">Daily Success Tip</h3>
 </div>
 <p className="text-[15px] font-medium leading-relaxed text-muted-foreground">
 "Consistent small steps lead to big results. Reviewing just one chapter today keeps your streak alive and your brain sharp! "
 </p>
 </div>
 )}
 </motion.div>

 {/* RIGHT — form */}
 <motion.div
 initial={{ opacity: 0, y: 24 }}
 animate={{ opacity: 1, y: 0 }}
 transition={{ duration: 0.7, delay: 0.15, ease: [0.22, 1, 0.36, 1] }}
 className="w-full"
 >
 {/* Mobile-only overline */}
 <div className="mb-6 flex items-center gap-3 lg:hidden">
 <span className="h-px w-10 bg-primary/30" />
 <p className="text-[12px] font-bold uppercase tracking-[0.2em] text-primary/80">
 {ctx.label}
 </p>
 </div>

 <div className="rounded-[32px] border border-white/60 dark:border-zinc-800 bg-white/70 dark:bg-zinc-900/80 backdrop-blur-xl p-8 shadow-[0_8px_40px_-12px_rgba(5,150,105,0.08)] dark:shadow-[0_8px_40px_-12px_rgba(0,0,0,0.5)] md:p-12 relative overflow-hidden">
 <h2 className="text-[32px] font-extrabold leading-[1.1] tracking-tight text-foreground">
 Sign In
 </h2>
 <p className="mt-3 text-[15px] font-medium text-muted-foreground">
 For students at any school in Nepal — or studying on your own.
 </p>

 {inlineError && (
 <div
 role="alert"
 className="mt-6 flex items-start gap-3 rounded-2xl border border-destructive/30 bg-destructive/5 p-4"
 >
 <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
 <p className="text-sm leading-relaxed text-destructive">{inlineError}</p>
 </div>
 )}

 <div className="mt-6"><OfflineAuthFallback mode="login" /></div>

 <form
 onSubmit={(e) => {
 if (inlineError) {
 const next = new URLSearchParams(searchParams);
 next.delete("error");
 setSearchParams(next, { replace: true });
 }
 handleSubmit(e);
 }}
 className="mt-8 space-y-5"
 >
 <div>
 <label htmlFor="li-email" className="mb-2 block text-[13px] font-bold text-foreground uppercase tracking-wide">
 Email or Username
 </label>
 <input
 id="li-email"
 type="text"
 autoComplete="username"
 value={email}
 onChange={(e) => setEmail(e.target.value)}
 placeholder="you@example.com or your username"
 className="h-14 w-full rounded-2xl border border-black/5 dark:border-zinc-800 bg-white/50 dark:bg-zinc-950/50 backdrop-blur-sm px-4 text-[15px] text-foreground placeholder:text-muted-foreground/50 focus-visible:border-primary/50 focus-visible:bg-white dark:focus-visible:bg-zinc-950 focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/10 transition-all shadow-sm inset-shadow-sm"
 required
 />
 </div>

 <div>
 <label htmlFor="li-password" className="mb-2 block text-[13px] font-bold text-foreground uppercase tracking-wide">
 Password
 </label>
 <div className="relative">
 <input
 id="li-password"
 type={showPassword? "text" : "password"}
 value={password}
 onChange={(e) => setPassword(e.target.value)}
 placeholder="Enter your password"
 className="h-14 w-full rounded-2xl border border-black/5 dark:border-zinc-800 bg-white/50 dark:bg-zinc-950/50 backdrop-blur-sm px-4 pr-12 text-[15px] text-foreground placeholder:text-muted-foreground/50 focus-visible:border-primary/50 focus-visible:bg-white dark:focus-visible:bg-zinc-950 focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/10 transition-all shadow-sm inset-shadow-sm"
 required
 />
 <button
 type="button"
 onClick={() => setShowPassword(!showPassword)}
 aria-label={showPassword? "Hide password" : "Show password"}
 className="absolute right-4 top-1/2 -translate-y-1/2 p-1 text-muted-foreground transition-colors hover:text-foreground"
 >
 {showPassword? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
 </button>
 </div>
 </div>

 <div className="flex items-center justify-between">
 <label className="inline-flex items-center gap-2 cursor-pointer select-none">
 <input
 type="checkbox"
 checked={remember}
 onChange={(e) => setRemember(e.target.checked)}
 className="h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/30 cursor-pointer"
 />
 <span className="text-[13px] font-medium text-muted-foreground">Remember me</span>
 </label>
 <button
 type="button"
 onClick={() => { setResetEmail(email); setForgotOpen(true); }}
 className="text-[13px] font-semibold text-primary hover:underline"
 >
 Forgot password?
 </button>
 </div>

 <button
 type="submit"
 disabled={loading}
 className="relative w-full overflow-hidden rounded-[20px] bg-foreground py-4 text-[15px] font-bold text-background shadow-[4px_4px_0px_#18181b] transition-all hover:translate-y-1 hover:shadow-[0px_0px_0px_#18181b] active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50 mt-4 border-2 border-foreground"
 >
 {loading? <Loader2 className="mx-auto h-5 w-5 animate-spin" /> : "Sign In"}
 </button>

 {/* Sign in with Apple — iOS native only (renders nothing on web/Android) */}
 <AppleSignIn className="mt-2" />
 </form>

 {!schoolName && (
 <>
 <div className="my-7 flex items-center gap-3">
 <div className="h-px flex-1 bg-border" />
 <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
 or
 </span>
 <div className="h-px flex-1 bg-border" />
 </div>

 <p className="text-center text-sm text-muted-foreground">
 New to NepEduAI?{" "}
 <Link to="/signup" className="font-semibold text-primary hover:underline">
 Create an account
 </Link>
 </p>
 </>
 )}
 {schoolName && (
 <p className="mt-7 text-center text-xs text-muted-foreground">
 Accounts are issued by your school. Contact the school office if
 you can&apos;t sign in.
 </p>
 )}
 </div>

 <p className="mt-6 text-center text-xs text-muted-foreground/70">
 By signing in, you agree to our{" "}
 <Link to="/terms" className="hover:text-foreground hover:underline">Terms</Link>{" "}
 &amp;{" "}
 <Link to="/privacy" className="hover:text-foreground hover:underline">Privacy Policy</Link>.
 </p>
 </motion.div>
 </main>

 {/* Forgot password dialog */}
 <Dialog open={forgotOpen} onOpenChange={setForgotOpen}>
 <DialogContent className="rounded-3xl sm:max-w-md">
 <DialogHeader>
 <DialogTitle className="text-xl font-black tracking-[-0.02em]">Reset your password</DialogTitle>
 <DialogDescription>Enter your email and we&apos;ll send you a reset link.</DialogDescription>
 </DialogHeader>
 <div className="space-y-4 pt-2">
 <input
 type="email"
 value={resetEmail}
 onChange={(e) => setResetEmail(e.target.value)}
 placeholder="you@example.com"
 className="h-12 w-full rounded-xl border border-border bg-background px-4 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background transition-all"
 />
 <button
 onClick={handleForgotPassword}
 disabled={resetLoading}
 className="w-full rounded-full bg-primary py-3 text-sm font-semibold text-primary-foreground transition-all hover:brightness-110 disabled:opacity-50"
 >
 {resetLoading? "Sending..." : "Send reset link"}
 </button>
 </div>
 </DialogContent>
 </Dialog>
 </div>
 );
};

export default Login;
