import { useState, useEffect } from "react";
import { useNavigate, Link, useSearchParams } from "react-router-dom";
import { AlertCircle, Eye, EyeOff, Loader2 } 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 { useOnlineStatus } from "@/hooks/useOnlineStatus";
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: "Sign in",
    lead: "Welcome back. Let's get",
    italic: "back to it.",
    sub: "Your weak topics, last MCQ set, and that one biology chapter you keep avoiding — all still here.",
  },
};

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 isOnline = useOnlineStatus();
  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,
    // so awaiting them sequentially used to add ~400-800ms of perceived delay
    // after submitting the password.
    const [role, profileRes] = await Promise.all([
      checkUserRole(),
      db.from("profiles").select("grade,onboarding_completed").eq("id", userId).maybeSingle(),
    ]);
    const profile = profileRes.data ?? undefined;

    // On dedicated portal subdomains, routes are root-level (no /school-admin, /teacher prefix)
    switch (role) {
      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, role, 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;
    }
    if (typeof navigator !== "undefined" && !navigator.onLine) {
      toast({ title: "You're offline", description: "Sign-in needs a network connection. We'll let you in as soon as you're back online.", 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-background">

      {/* 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-foreground/30" />
            <p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-muted-foreground">
              <span className="font-mono text-primary">01</span>
              <span className="mx-2 text-foreground/30">—</span>
              {ctx.label}
            </p>
          </div>

          {/* Heading */}
          <h1 className="mt-8 text-5xl font-black leading-[1.05] tracking-[-0.04em] text-foreground lg:text-6xl">
            {ctx.lead}{" "}
            <span
              className="text-foreground/70"
              style={{ fontFamily: "'Playfair Display', serif", fontStyle: "italic", fontWeight: 500 }}
            >
              {ctx.italic}
            </span>
          </h1>

          <p className="mt-8 max-w-md text-lg leading-[1.7] text-foreground/80">{ctx.sub}</p>

          {/* Editorial pull-quote / school principal card */}
          {schoolName && branding ? (
            <div className="mt-12 max-w-md overflow-hidden rounded-3xl border border-border bg-card shadow-[0_20px_60px_-30px_hsl(var(--primary)/0.2)]">
              {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-lg leading-[1.4] tracking-tight text-foreground"
                    style={{ fontFamily: "'Playfair Display', serif", fontStyle: "italic", fontWeight: 500 }}
                  >
                    &ldquo;{branding.principal_message}&rdquo;
                  </p>
                )}
                <div className="mt-5 flex items-center gap-3 border-t border-border 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-sm font-semibold text-foreground">{branding.principal_name}</span>
                    )}
                    <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                      Principal · {schoolName}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className="mt-12 max-w-md rounded-3xl border border-border bg-card p-7 shadow-[0_20px_60px_-30px_hsl(var(--primary)/0.2)]">
              <p
                className="text-xl leading-[1.35] tracking-tight text-foreground"
                style={{ fontFamily: "'Playfair Display', serif", fontStyle: "italic", fontWeight: 500 }}
              >
                &ldquo;I used to copy answers from class notes the morning before the exam. Now I actually understand the chapter the night before — and still sleep.&rdquo;
              </p>
              <div className="mt-5 flex items-center gap-3 border-t border-border pt-4">
                <div className="grid h-10 w-10 place-items-center rounded-full bg-primary/10 text-sm font-bold text-primary">
                  SP
                </div>
                <div className="flex flex-col">
                  <span className="text-sm font-semibold text-foreground">Sneha P.</span>
                  <span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                    Class 12 Science · Pokhara
                  </span>
                </div>
              </div>
            </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-foreground/30" />
            <p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-muted-foreground">
              <span className="font-mono text-primary">01</span>
              <span className="mx-2 text-foreground/30">—</span>
              {ctx.label}
            </p>
          </div>

          <div className="rounded-3xl border border-border bg-card p-8 shadow-[0_20px_60px_-30px_hsl(var(--primary)/0.2)] md:p-10">
            <h2 className="text-3xl font-black leading-[1.1] tracking-[-0.03em] text-foreground">
              Sign in
            </h2>
            <p className="mt-2 text-sm 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 className="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                  Email or Username
                </label>
                <input
                  type="text"
                  autoComplete="username"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com or your username"
                  className="h-12 w-full rounded-xl border border-border bg-background px-4 text-sm text-foreground placeholder:text-muted-foreground/40 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all"
                  required
                />
              </div>

              <div>
                <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                  Password
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? "text" : "password"}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="Enter your password"
                    className="h-12 w-full rounded-xl border border-border bg-background px-4 pr-12 text-sm text-foreground placeholder:text-muted-foreground/40 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    aria-label={showPassword ? "Hide password" : "Show password"}
                    className="absolute right-3 top-1/2 -translate-y-1/2 p-1 text-muted-foreground transition-colors hover:text-foreground"
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </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 || !isOnline}
                className="relative w-full overflow-hidden rounded-full bg-primary py-3.5 text-sm font-semibold text-primary-foreground shadow-[0_2px_12px_hsl(var(--primary)/0.3)] transition-all hover:brightness-110 active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50"
              >
                {loading ? <Loader2 className="mx-auto h-5 w-5 animate-spin" /> : !isOnline ? "Offline — waiting for connection" : "Continue studying"}
              </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/40 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 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;
