import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Zap, Loader2, Eye, EyeOff, ShieldCheck, Activity, LineChart } from "lucide-react";
import { useAuth } from "@/lib/auth";
import { useAppSettings } from "@/lib/app-settings";
import { API_BASE_URL } from "@/lib/backend-client";
import { toast } from "sonner";

export const Route = createFileRoute("/login")({
  head: () => ({ meta: [{ title: "Sign in · Delta Terminal" }] }),
  component: Login,
});

function GoogleIcon() {
  return (
    <svg viewBox="0 0 24 24" className="h-4 w-4" aria-hidden="true"><path fill="#EA4335" d="M12 10.2v3.9h5.5c-.24 1.4-1.7 4.1-5.5 4.1-3.3 0-6-2.7-6-6.1s2.7-6.1 6-6.1c1.9 0 3.1.8 3.8 1.5l2.6-2.5C16.7 3.5 14.6 2.5 12 2.5 6.8 2.5 2.6 6.7 2.6 12S6.8 21.5 12 21.5c6.9 0 9.5-4.8 9.5-8.4 0-.6-.1-1-.1-1.6H12z"/></svg>
  );
}
function FacebookIcon() {
  return <svg viewBox="0 0 24 24" className="h-4 w-4" aria-hidden="true"><path fill="#1877F2" d="M22 12a10 10 0 1 0-11.6 9.9v-7H8v-2.9h2.4V9.8c0-2.4 1.4-3.7 3.6-3.7 1 0 2.1.2 2.1.2v2.3h-1.2c-1.2 0-1.5.7-1.5 1.5v1.8h2.6l-.4 2.9h-2.2v7A10 10 0 0 0 22 12z"/></svg>;
}
function XIcon() {
  return <svg viewBox="0 0 24 24" className="h-4 w-4" aria-hidden="true"><path fill="currentColor" d="M18.244 2H21l-6.53 7.46L22 22h-6.828l-4.77-6.24L4.9 22H2.144l7-8L2 2h6.914l4.3 5.7L18.244 2zm-2.393 18h1.87L7.24 4h-2.01l10.62 16z"/></svg>;
}

function Login() {
  const nav = useNavigate();
  const { signIn } = useAuth();
  const settings = useAppSettings();
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [busy, setBusy] = useState(false);
  const [socialBusy, setSocialBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      await signIn(email, pw);
      toast.success("Signed in");
      nav({ to: "/dashboard" });
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Sign in failed";
      setError(msg);
      toast.error(msg);
    } finally {
      setBusy(false);
    }
  }

  async function startOAuth(provider: "google" | "facebook" | "x") {
    setSocialBusy(provider);
    try {
      const res = await fetch(`${API_BASE_URL}/auth/oauth/${provider}/start`);
      const body = await res.json().catch(() => ({}));
      if (!res.ok || !body.url) throw new Error(body.error ?? "OAuth unavailable");
      window.location.href = body.url;
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "OAuth failed");
      setSocialBusy(null);
    }
  }

  const anySocial =
    settings.features.google_login_enabled ||
    settings.features.facebook_login_enabled ||
    settings.features.x_login_enabled;

  return (
    <div className="relative grid min-h-dvh lg:grid-cols-2">
      {/* Brand / marketing panel */}
      <aside className="relative hidden overflow-hidden border-r border-border/60 lg:flex lg:flex-col lg:justify-between lg:p-10">
        <div
          aria-hidden="true"
          className="absolute inset-0 -z-10"
          style={{
            background:
              "radial-gradient(700px 400px at 20% 10%, color-mix(in oklab, var(--primary) 25%, transparent), transparent 60%), radial-gradient(600px 400px at 90% 90%, color-mix(in oklab, var(--accent) 22%, transparent), transparent 60%)",
          }}
        />
        <div className="flex items-center gap-3">
          <div className="grid h-11 w-11 place-items-center rounded-xl bg-primary text-primary-foreground shadow-lg shadow-primary/30">
            {settings.branding.logo_url ? (
              <img src={settings.branding.logo_url} alt="" className="h-8 w-8 object-contain" />
            ) : (
              <Zap className="h-6 w-6" />
            )}
          </div>
          <div className="font-display text-xl font-bold tracking-tight">
            {settings.branding.app_title}
          </div>
        </div>

        <div className="max-w-lg">
          <h1 className="font-display text-4xl font-bold leading-tight tracking-tight">
            The <span className="gradient-text">real-time trading terminal</span> built for Delta Exchange.
          </h1>
          <p className="mt-4 text-sm leading-relaxed text-muted-foreground">
            Multi-algo signal engine, live P&amp;L, trailing exits and a full activity ledger — in one glass-morphic terminal.
          </p>
          <ul className="mt-8 grid gap-4 text-sm">
            {[
              { icon: Activity, label: "Live WebSocket tick streaming with reconnect & health" },
              { icon: LineChart, label: "6 parallel strategies with best-match consensus" },
              { icon: ShieldCheck, label: "RSA-256 auth · encrypted API keys · full audit log" },
            ].map(({ icon: Icon, label }) => (
              <li key={label} className="flex items-start gap-3">
                <span className="mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-md bg-primary/15 text-primary">
                  <Icon className="h-4 w-4" />
                </span>
                <span className="text-foreground/90">{label}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="text-xs text-muted-foreground">
          &copy; {new Date().getFullYear()} {settings.branding.app_title}. All rights reserved.
        </div>
      </aside>

      {/* Form panel */}
      <main className="grid place-items-center px-4 py-10 sm:px-8">
        <Card className="glass-strong w-full max-w-md rounded-2xl p-6 sm:p-8">
          <div className="mb-6 flex items-center gap-3 lg:hidden">
            <div className="grid h-10 w-10 place-items-center rounded-xl bg-primary text-primary-foreground">
              {settings.branding.logo_url ? (
                <img src={settings.branding.logo_url} alt="" className="h-7 w-7 object-contain" />
              ) : (
                <Zap className="h-5 w-5" />
              )}
            </div>
            <div className="font-display text-lg font-bold tracking-tight">
              {settings.branding.app_title}
            </div>
          </div>

          <div className="mb-6">
            <h2 className="font-display text-2xl font-bold tracking-tight">Welcome back</h2>
            <p className="mt-1 text-sm text-muted-foreground">Sign in to access your terminal.</p>
          </div>

          {anySocial && (
            <div className="mb-5 grid gap-2">
              {settings.features.google_login_enabled && (
                <Button
                  type="button"
                  variant="outline"
                  className="w-full justify-center gap-2 border-border/70 bg-secondary/50 text-foreground hover:bg-secondary/70"
                  disabled={Boolean(socialBusy)}
                  onClick={() => startOAuth("google")}
                >
                  {socialBusy === "google" ? <Loader2 className="h-4 w-4 animate-spin" /> : <GoogleIcon />}
                  Continue with Google
                </Button>
              )}
              {settings.features.facebook_login_enabled && (
                <Button
                  type="button"
                  variant="outline"
                  className="w-full justify-center gap-2 border-border/70 bg-secondary/50 text-foreground hover:bg-secondary/70"
                  disabled={Boolean(socialBusy)}
                  onClick={() => startOAuth("facebook")}
                >
                  {socialBusy === "facebook" ? <Loader2 className="h-4 w-4 animate-spin" /> : <FacebookIcon />}
                  Continue with Facebook
                </Button>
              )}
              {settings.features.x_login_enabled && (
                <Button
                  type="button"
                  variant="outline"
                  className="w-full justify-center gap-2 border-border/70 bg-secondary/50 text-foreground hover:bg-secondary/70"
                  disabled={Boolean(socialBusy)}
                  onClick={() => startOAuth("x")}
                >
                  {socialBusy === "x" ? <Loader2 className="h-4 w-4 animate-spin" /> : <XIcon />}
                  Continue with X
                </Button>
              )}
              <div className="my-2 flex items-center gap-3 text-[10px] uppercase tracking-widest text-muted-foreground">
                <div className="h-px flex-1 bg-border/60" />or continue with email<div className="h-px flex-1 bg-border/60" />
              </div>
            </div>
          )}

          <form onSubmit={onSubmit} className="grid gap-4" noValidate>
            <div className="grid gap-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                required
                autoComplete="email"
                autoFocus
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@trader.io"
                aria-invalid={error ? true : undefined}
              />
            </div>
            <div className="grid gap-2">
              <div className="flex items-baseline justify-between">
                <Label htmlFor="pw">Password</Label>
                <Link to="/login" className="text-xs text-muted-foreground hover:text-primary hover:underline">
                  Forgot?
                </Link>
              </div>
              <div className="relative">
                <Input
                  id="pw"
                  type={showPw ? "text" : "password"}
                  required
                  autoComplete="current-password"
                  value={pw}
                  onChange={(e) => setPw(e.target.value)}
                  placeholder="••••••••"
                  className="pr-10"
                  aria-invalid={error ? true : undefined}
                />
                <button
                  type="button"
                  onClick={() => setShowPw((v) => !v)}
                  className="absolute inset-y-0 right-0 grid w-10 place-items-center text-muted-foreground hover:text-foreground focus-visible:text-foreground"
                  aria-label={showPw ? "Hide password" : "Show password"}
                  aria-pressed={showPw}
                  tabIndex={0}
                >
                  {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            {error && (
              <div role="alert" aria-live="polite" className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive-foreground">
                {error}
              </div>
            )}

            <Button type="submit" size="lg" className="mt-1 w-full font-bold" disabled={busy}>
              {busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}Enter Terminal
            </Button>
          </form>

          {settings.features.registration_enabled && (
            <p className="mt-6 text-center text-xs text-muted-foreground">
              No account?{" "}
              <Link to="/register" className="font-semibold text-primary hover:underline">
                Create one
              </Link>
            </p>
          )}
        </Card>
      </main>
    </div>
  );
}
