"use client";

import { Suspense, useState } from "react";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";

import {
  Anchor,
  Calendar,
  CheckCircle2,
  Eye,
  EyeOff,
  Lock,
  Ship,
  Shield,
  User,
  UserPlus,
  Users,
  Wallet,
} from "lucide-react";

import {
  AuthGlassShell,
  authGlassDemoCard,
  authGlassInputClass,
  authGlassLabelClass,
  authOceanButtonClass,
  authReturnBannerClass,
} from "@/components/auth/auth-glass-shell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { login, MOCK_CREDENTIALS, ROLE_LABELS, type AuthUser, type Role } from "@/lib/auth";
import { getBookingsByGuest, getGuestByEmail, getGuestByUserId } from "@/lib/cruise-store";

const demoAccounts = [
  {
    role: "super_admin" as Role,
    username: "admin",
    password: "admin123",
    icon: Shield,
    color: "bg-violet-600/90 ring-1 ring-violet-400/40",
    badgeClass: "border-violet-400/40 bg-violet-500/25 text-violet-100",
  },
  {
    role: "staff" as Role,
    username: "staff",
    password: "staff123",
    icon: Users,
    color: "bg-teal-600/90 ring-1 ring-teal-400/30",
    badgeClass: "border-teal-400/40 bg-teal-500/25 text-teal-100",
  },
  {
    role: "client" as Role,
    username: "client",
    password: "client123",
    icon: User,
    color: "bg-cyan-500/90 ring-1 ring-cyan-300/30",
    badgeClass: "border-cyan-400/40 bg-cyan-500/25 text-cyan-100",
  },
];

const FEATURES = [
  { icon: Ship, text: "Browse themed group sailings & events" },
  { icon: Calendar, text: "7-step booking wizard with cabin selection" },
  { icon: Wallet, text: "Payment plans, promos & referral tracking" },
  { icon: Anchor, text: "Guest portal for bookings & payments" },
  { icon: Users, text: "Staff dashboard for inventory & operations" },
];

function getPostLoginPath(user: AuthUser, returnUrl?: string | null): string {
  if (returnUrl?.startsWith("/")) return returnUrl;
  if (user.role === "client") {
    const guest = getGuestByUserId(user.id) ?? getGuestByEmail(user.email);
    if (guest && getBookingsByGuest(guest.id).length > 0) return "/portal";
    return "/events";
  }
  return "/dashboard";
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <div className="flex min-h-screen items-center justify-center bg-[#001428] text-cyan-200/50 text-sm">
          Loading…
        </div>
      }
    >
      <LoginForm />
    </Suspense>
  );
}

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const returnUrl = searchParams.get("return");
  const emailParam = searchParams.get("email");
  const [username, setUsername] = useState(emailParam ?? "");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [activeRole, setActiveRole] = useState("");

  const fillDemo = (u: string, p: string, role: string) => {
    setUsername(u);
    setPassword(p);
    setActiveRole(role);
    setError("");
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");
    setTimeout(() => {
      const user = login(username.trim(), password);
      if (!user) {
        setError("Invalid credentials. Try a demo account or your registered email.");
        setLoading(false);
        return;
      }
      router.replace(getPostLoginPath(user, returnUrl));
    }, 400);
  };

  return (
    <AuthGlassShell
      title={
        <>
          Themed group sailings,{" "}
          <span className="text-white/40">from cabin to checkout.</span>
        </>
      }
      subtitle="Guests book sailings and track payments. Staff manage inventory, bookings, and automations."
      features={FEATURES}
      banner={
        returnUrl ? (
          <div className={authReturnBannerClass}>Sign in to continue where you left off</div>
        ) : null
      }
    >
      <div className="space-y-5 sm:space-y-6 [@media(max-height:780px)]:space-y-3">
        <div>
          <h2 className="font-semibold text-xl tracking-tight sm:text-2xl">Sign in</h2>
          <p className="mt-1 text-cyan-100/45 text-sm leading-snug">Demo accounts or your registered email</p>
        </div>

        <div className="space-y-2">
          <p className="font-medium text-[10px] text-cyan-300/50 uppercase tracking-[0.18em]">Quick demo</p>
          <div className="space-y-2">
            {demoAccounts.map((acc) => {
              const Icon = acc.icon;
              const cred = MOCK_CREDENTIALS.find((c) => c.username === acc.username);
              const isActive = activeRole === acc.role;
              return (
                <button
                  key={acc.role}
                  type="button"
                  onClick={() => fillDemo(acc.username, acc.password, acc.role)}
                  className={authGlassDemoCard(isActive)}
                >
                  <div className={`flex size-9 shrink-0 items-center justify-center rounded-xl ${acc.color}`}>
                    <Icon className="size-4 text-white" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex min-w-0 flex-col items-start gap-0.5 [@media(min-height:781px)]:flex-row [@media(min-height:781px)]:flex-wrap [@media(min-height:781px)]:items-center [@media(min-height:781px)]:gap-x-2 [@media(min-height:781px)]:gap-y-0.5">
                      <span className="max-w-full truncate font-medium text-sm text-white/90">{cred?.user.name}</span>
                      <span
                        className={`shrink-0 rounded-md border px-1.5 py-px text-[10px] font-medium leading-tight ${acc.badgeClass}`}
                      >
                        {ROLE_LABELS[acc.role]}
                      </span>
                    </div>
                    <p className="mt-0.5 truncate text-white/40 text-xs">
                      {acc.username} · {acc.password}
                    </p>
                  </div>
                  <CheckCircle2
                    className={`size-4 shrink-0 text-white transition-opacity ${isActive ? "opacity-100" : "opacity-0"}`}
                  />
                </button>
              );
            })}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <div className="h-px min-w-3 flex-1 bg-cyan-400/15" />
          <span className="shrink-0 px-0.5 text-center text-[10px] text-cyan-200/35 leading-snug sm:text-xs">
            <span className="sm:hidden">or sign in</span>
            <span className="hidden sm:inline">or email / username</span>
          </span>
          <div className="h-px min-w-3 flex-1 bg-cyan-400/15" />
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="username" className={authGlassLabelClass}>
              Email or username
            </Label>
            <div className="relative">
              <User className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-white/35" />
              <Input
                id="username"
                placeholder="client or you@email.com"
                value={username}
                onChange={(e) => {
                  setUsername(e.target.value);
                  setActiveRole("");
                  setError("");
                }}
                className={`pl-9 ${authGlassInputClass}`}
                autoComplete="username"
              />
            </div>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="password" className={authGlassLabelClass}>
              Password
            </Label>
            <div className="relative">
              <Lock className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-white/35" />
              <Input
                id="password"
                type={showPassword ? "text" : "password"}
                placeholder="••••••••"
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value);
                  setError("");
                }}
                className={`pl-9 pr-10 ${authGlassInputClass}`}
                autoComplete="current-password"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute top-1/2 right-3 -translate-y-1/2 text-white/35 hover:text-white/70"
                tabIndex={-1}
              >
                {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
              </button>
            </div>
          </div>

          {error && (
            <p className="rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2.5 text-red-200 text-sm backdrop-blur-sm">
              {error}
            </p>
          )}

          <Button
            type="submit"
            className={authOceanButtonClass}
            disabled={loading || !username || !password}
          >
            {loading ? "Signing in…" : "Sign in"}
          </Button>
        </form>

        <div className="space-y-3 text-center text-sm [@media(max-height:780px)]:space-y-2 [@media(max-height:780px)]:text-xs">
          <p className="text-cyan-100/45">New guest?{" "}
            <Link
              href={returnUrl ? `/register?return=${encodeURIComponent(returnUrl)}` : "/register"}
              className="inline-flex items-center gap-1 font-medium text-cyan-200 underline-offset-4 hover:text-cyan-100 hover:underline"
            >
              <UserPlus className="size-3.5" />
              Create account
            </Link>
          </p>
          <Link href="/lookup" className="block text-cyan-200/35 text-xs hover:text-cyan-200/70">
            Find my booking →
          </Link>
          <Link href="/events" className="block text-cyan-200/35 text-xs hover:text-cyan-200/70">
            Browse events without signing in →
          </Link>
        </div>
      </div>
    </AuthGlassShell>
  );
}
