"use client";

import { useEffect, useState } from "react";

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

import {
  Bot,
  Building2,
  CheckCircle2,
  Command,
  Eye,
  EyeOff,
  LayoutDashboard,
  Lock,
  Plug,
  Shield,
  Sparkles,
  User,
  UserPlus,
  Users,
} from "lucide-react";

import { AuthLayout } from "@/components/silisuite/auth-layout";
import { GlassCard } from "@/components/silisuite/glass-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { APP_CONFIG } from "@/config/app-config";
import { login, MOCK_CREDENTIALS, ROLE_COLORS, ROLE_LABELS, type Role } from "@/lib/auth";

const demoAccounts = [
  {
    role: "super_admin" as Role,
    username: "admin",
    password: "admin123",
    icon: Shield,
    color: "ss-glass border border-violet-500/40 text-violet-300",
  },
  {
    role: "staff" as Role,
    username: "staff",
    password: "staff123",
    icon: Users,
    color: "ss-glass border border-blue-500/40 text-blue-300",
  },
  {
    role: "client" as Role,
    username: "client",
    password: "client123",
    icon: User,
    color: "ss-glass border border-emerald-500/40 text-emerald-300",
  },
];

const FEATURES = [
  { icon: Plug, text: "Unified integration library" },
  { icon: Sparkles, text: "AI Director — cross-tool intelligence" },
  { icon: Bot, text: "SiliTalk & website chatbots" },
  { icon: LayoutDashboard, text: "Client portal & staff admin" },
  { icon: Building2, text: "Role-based access for clients & staff" },
];

export default function LoginPage() {
  const router = useRouter();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [activeRole, setActiveRole] = useState<string>("");

  const signInWithCredentials = (u: string, p: string) => {
    setLoading(true);
    setError("");
    setTimeout(() => {
      const user = login(u.trim(), p);
      if (!user) {
        setError("Invalid credentials. Click a demo account or try again.");
        setLoading(false);
        return;
      }
      router.replace(user.role === "client" ? "/portal" : "/dashboard");
    }, 300);
  };

  const selectDemo = (u: string, p: string, role: string) => {
    if (loading) return;
    setUsername(u);
    setPassword(p);
    setActiveRole(role);
    setError("");
    signInWithCredentials(u, p);
  };

  useEffect(() => {
    const el = document.getElementById("username");
    el?.focus();
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    signInWithCredentials(username, password);
  };

  return (
    <AuthLayout>
      <div className="flex min-h-screen items-center justify-center px-6 py-12">
        <div className="grid w-full max-w-[960px] items-stretch gap-8 lg:grid-cols-2 lg:gap-10">
          <aside className="hidden lg:block">
            <GlassCard className="flex h-full min-h-full flex-col p-8">
              <div className="flex items-center gap-3">
                <div className="ss-glass flex size-9 items-center justify-center rounded-xl">
                  <Command className="size-4 text-[var(--ss-accent)]" />
                </div>
                <span className="ss-heading text-base text-foreground">{APP_CONFIG.name}</span>
              </div>

              <div className="flex flex-1 flex-col justify-center gap-8 py-6">
                <div className="space-y-4">
                  <p className="ss-label text-[var(--ss-accent)]">SiliMind · AI Platform</p>
                  <h1 className="ss-heading text-[2rem] leading-tight text-foreground">
                    Unlock AI operations
                    <br />
                    <span className="text-muted-foreground">for your business.</span>
                  </h1>
                  <p className="text-muted-foreground text-sm leading-relaxed">
                    Manage agents, integrations, and insights from one client-facing portal.
                  </p>
                </div>
                <ul className="space-y-3">
                  {FEATURES.map(({ icon: Icon, text }) => (
                    <li key={text} className="flex items-center gap-3">
                      <div className="ss-glass flex size-7 shrink-0 items-center justify-center rounded-lg">
                        <Icon className="size-3.5 text-muted-foreground" />
                      </div>
                      <span className="text-muted-foreground text-sm">{text}</span>
                    </li>
                  ))}
                </ul>
              </div>

              <p className="text-muted-foreground text-xs">{APP_CONFIG.copyright}</p>
            </GlassCard>
          </aside>

          <main className="flex w-full">
            <GlassCard className="flex h-full w-full flex-col p-8">
            <div className="mb-6 flex items-center gap-2.5 lg:hidden">
              <Command className="size-5 text-[var(--ss-accent)]" />
              <span className="ss-heading text-foreground">{APP_CONFIG.name}</span>
            </div>

            <div className="mb-6">
              <h2 className="ss-heading text-2xl text-foreground">Sign in</h2>
              <p className="mt-1 text-muted-foreground text-sm">Click a demo account to sign in, or enter credentials below.</p>
            </div>

            <div className="mb-6 space-y-2">
              <p className="ss-label">Demo accounts</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"
                      disabled={loading}
                      aria-label={`Sign in as ${cred?.user.name ?? acc.role} demo account`}
                      onClick={() => selectDemo(acc.username, acc.password, acc.role)}
                      className={[
                        "flex w-full items-center gap-3 rounded-xl border px-4 py-3 text-left transition-all duration-150 ease-out",
                        isActive
                          ? "border-[var(--ss-accent)]/50 bg-[var(--ss-accent)]/10"
                          : "border-white/10 bg-white/5 hover:border-white/20",
                      ].join(" ")}
                    >
                      <div
                        className={`flex size-9 shrink-0 items-center justify-center rounded-lg ${acc.color}`}
                      >
                        <Icon className="size-4" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-semibold text-foreground text-sm">{cred?.user.name}</span>
                          <span className={`shrink-0 rounded border px-1.5 py-px text-[10px] ${ROLE_COLORS[acc.role]}`}>
                            {ROLE_LABELS[acc.role]}
                          </span>
                        </div>
                        <p className="mt-0.5 text-muted-foreground text-xs">
                          {acc.username} / {acc.password}
                        </p>
                      </div>
                      <CheckCircle2
                        className={`size-4 shrink-0 text-[var(--ss-accent)] transition-opacity ${isActive ? "opacity-100" : "opacity-0"}`}
                      />
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="mb-6 flex items-center gap-3">
              <div className="h-px flex-1 bg-white/10" />
              <span className="text-muted-foreground text-xs">or enter manually</span>
              <div className="h-px flex-1 bg-white/10" />
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-1.5">
                <Label htmlFor="username">Username</Label>
                <div className="relative">
                  <User className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="username"
                    placeholder="Enter username"
                    value={username}
                    onChange={(e) => {
                      setUsername(e.target.value);
                      setActiveRole("");
                      setError("");
                    }}
                    className="pl-9"
                    autoComplete="username"
                    aria-label="Username"
                  />
                </div>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="password">Password</Label>
                <div className="relative">
                  <Lock className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="Enter password"
                    value={password}
                    onChange={(e) => {
                      setPassword(e.target.value);
                      setError("");
                    }}
                    className="pl-9 pr-10"
                    autoComplete="current-password"
                    aria-label="Password"
                    suppressHydrationWarning
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute top-1/2 right-3 -translate-y-1/2 text-muted-foreground"
                    tabIndex={-1}
                  >
                    {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                  </button>
                </div>
              </div>
              {error && (
                <p className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-destructive text-sm">
                  {error}
                </p>
              )}
              <Button type="submit" className="h-10 w-full" disabled={loading || !username || !password}>
                {loading ? "Signing in…" : "Sign in"}
              </Button>
            </form>

            <p className="mt-6 text-center text-muted-foreground text-sm">
              <Link
                href="/register"
                className="inline-flex items-center font-semibold text-[var(--ss-accent)] underline-offset-4 hover:underline"
              >
                <UserPlus className="mr-1 size-3.5" />
                Create account
              </Link>
            </p>
            </GlassCard>
          </main>
        </div>
      </div>
    </AuthLayout>
  );
}
