"use client";

import { useState } from "react";

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

import {
  CheckCircle2,
  ClipboardList,
  Command,
  Eye,
  EyeOff,
  LayoutGrid,
  Lock,
  Shield,
  UtensilsCrossed,
  User,
} from "lucide-react";

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 {
  DEMO_LOGIN_HINTS,
  getPostLoginPath,
  login,
  ROLE_COLORS,
  ROLE_LABELS,
  type Role,
} from "@/lib/auth";

const demoAccounts = [
  { ...DEMO_LOGIN_HINTS.admin, name: "Alexandra Chen", icon: Shield, color: "bg-violet-500" },
  { ...DEMO_LOGIN_HINTS.manager, name: "Elena Vasquez", icon: ClipboardList, color: "bg-blue-500" },
  { ...DEMO_LOGIN_HINTS.ops, name: "Marco Deluca", icon: UtensilsCrossed, color: "bg-amber-500" },
];

const FEATURES = [
  { icon: Shield, text: "Super Admin — venues, managers, reports" },
  { icon: ClipboardList, text: "Reservation Manager — bookings & waiting list" },
  { icon: LayoutGrid, text: "Operations Staff — live floor & arrivals" },
  { icon: UtensilsCrossed, text: "Guest booking — public reservation flow" },
];

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 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. Select a demo account or try again.");
        setLoading(false);
        return;
      }
      router.replace(getPostLoginPath(user.role));
    }, 400);
  };

  return (
    <div className="flex min-h-screen">
      <aside className="relative hidden w-[460px] flex-none flex-col justify-between overflow-hidden bg-zinc-950 p-12 lg:flex">
        <div
          className="pointer-events-none absolute inset-0 opacity-[0.035]"
          style={{
            backgroundImage:
              "linear-gradient(rgba(255,255,255,1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,1) 1px,transparent 1px)",
            backgroundSize: "40px 40px",
          }}
        />
        <div className="pointer-events-none absolute -right-32 -top-32 h-[480px] w-[480px] rounded-full bg-amber-500/15 blur-[80px]" />

        <div className="relative z-10 flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-amber-500/20 ring-1 ring-amber-500/30">
            <UtensilsCrossed className="h-4 w-4 text-amber-400" />
          </div>
          <span className="text-base font-semibold tracking-tight text-white">{APP_CONFIG.name}</span>
        </div>

        <div className="relative z-10 space-y-8">
          <div className="space-y-4">
            <p className="text-xs font-semibold uppercase tracking-widest text-amber-400">
              Digital Floor Plan & Reservation Management
            </p>
            <h1 className="text-[2rem] font-bold leading-tight text-white">
              Hospitality operations,
              <br />
              <span className="text-white/40">one clickable PoC.</span>
            </h1>
            <p className="max-w-[280px] text-sm leading-relaxed text-white/40">
              Multi-role demo with mock data. No backend required.
            </p>
          </div>
          <ul className="space-y-3">
            {FEATURES.map(({ icon: Icon, text }) => (
              <li key={text} className="flex items-center gap-3">
                <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-white/8 ring-1 ring-white/10">
                  <Icon className="h-3.5 w-3.5 text-white/50" />
                </div>
                <span className="text-sm text-white/45">{text}</span>
              </li>
            ))}
          </ul>
        </div>

        <p className="relative z-10 text-xs text-white/20">{APP_CONFIG.copyright}</p>
      </aside>

      <main className="flex flex-1 items-center justify-center bg-zinc-50 px-6 py-16">
        <div className="w-full max-w-[400px] space-y-7">
          <div className="flex items-center gap-2.5 lg:hidden">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-zinc-900">
              <UtensilsCrossed className="h-4 w-4 text-amber-400" />
            </div>
            <span className="font-semibold">{APP_CONFIG.name}</span>
          </div>

          <div>
            <h2 className="text-2xl font-bold tracking-tight">Sign in</h2>
            <p className="mt-1 text-sm text-muted-foreground">Staff demo accounts — or book as a guest</p>
          </div>

          <div className="space-y-2">
            <p className="text-[11px] font-semibold uppercase tracking-widest text-muted-foreground">Demo accounts</p>
            {demoAccounts.map((acc) => {
              const Icon = acc.icon;
              const isActive = activeRole === acc.role;
              return (
                <button
                  key={acc.role}
                  type="button"
                  onClick={() => fillDemo(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",
                    isActive ? "border-zinc-900 bg-white shadow-md ring-1 ring-zinc-900/10" : "border-zinc-200 bg-white hover:border-zinc-300",
                  ].join(" ")}
                >
                  <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-white ${acc.color}`}>
                    <Icon className="h-4 w-4" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-semibold">{acc.name}</span>
                      <span className={`rounded border px-1.5 py-px text-[10px] font-semibold ${ROLE_COLORS[acc.role]}`}>
                        {ROLE_LABELS[acc.role]}
                      </span>
                    </div>
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      {acc.username} / {acc.password}
                    </p>
                  </div>
                  <CheckCircle2 className={`h-4 w-4 shrink-0 ${isActive ? "opacity-100" : "opacity-0"}`} />
                </button>
              );
            })}
          </div>

          <div className="flex items-center gap-3">
            <div className="h-px flex-1 bg-border" />
            <span className="text-xs text-muted-foreground">or enter manually</span>
            <div className="h-px flex-1 bg-border" />
          </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 left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="username"
                  className="pl-9"
                  value={username}
                  onChange={(e) => {
                    setUsername(e.target.value);
                    setActiveRole("");
                    setError("");
                  }}
                  autoFocus
                />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="password">Password</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  className="pl-9 pr-10"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <button
                  type="button"
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground"
                  onClick={() => setShowPassword(!showPassword)}
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
            {error && <p className="rounded-lg border border-red-100 bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>}
            <Button type="submit" className="w-full" disabled={loading || !username || !password}>
              {loading ? "Signing in…" : "Sign in"}
            </Button>
          </form>

          <div className="rounded-xl border bg-card p-4 text-center">
            <p className="text-sm text-muted-foreground">No staff account needed?</p>
            <Button asChild variant="outline" className="mt-2 w-full">
              <Link href="/book">Book a table as guest</Link>
            </Button>
          </div>

          <p className="text-center text-xs text-muted-foreground">PoC demo — mock data only</p>
        </div>
      </main>
    </div>
  );
}
