"use client";

import { useState } from "react";

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

import {
  Banknote,
  BookOpen,
  Building2,
  CheckCircle2,
  Command,
  FileText,
  GraduationCap,
  Lock,
  Shield,
  User,
  Users,
} 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 { login, MOCK_CREDENTIALS, ROLE_COLORS, ROLE_LABELS, type Role } from "@/lib/auth";

const accountMeta: Record<Role, { icon: typeof Shield; color: string }> = {
  owner: { icon: Shield, color: "bg-violet-500" },
  school_admin: { icon: Building2, color: "bg-blue-500" },
  dso: { icon: FileText, color: "bg-cyan-600" },
  finance: { icon: Banknote, color: "bg-emerald-600" },
  agent: { icon: Users, color: "bg-amber-500" },
  teacher: { icon: BookOpen, color: "bg-rose-500" },
  student: { icon: GraduationCap, color: "bg-slate-700" },
};

const FEATURES = [
  "Multi-school dashboards with role-aware visibility",
  "Student lifecycle, documents, requests, and finance",
  "Sessions, classes, attendance, audit, and notifications",
];

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

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

  const handleSubmit = (event: React.FormEvent) => {
    event.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(user.role === "student" ? "/portal" : "/dashboard");
    }, 250);
  };

  return (
    <div className="flex min-h-screen bg-zinc-50 text-zinc-950">
      <aside className="hidden w-[460px] flex-col justify-between bg-zinc-950 p-12 text-white lg:flex">
        <div className="flex items-center gap-3">
          <div className="flex size-10 items-center justify-center rounded-lg bg-white/10">
            <Command className="size-5" />
          </div>
          <span className="font-semibold text-lg">{APP_CONFIG.name}</span>
        </div>

        <div className="space-y-8">
          <div className="space-y-4">
            <p className="font-semibold text-cyan-300 text-xs uppercase tracking-widest">Education SaaS POC</p>
            <h1 className="font-bold text-4xl leading-tight">
              Student lifecycle operations,
              <span className="block text-white/45">in one school platform.</span>
            </h1>
            <p className="max-w-sm text-sm text-white/55 leading-relaxed">
              A frontend-first demo for owners, school staff, DSOs, finance officers, agents, teachers, and students.
            </p>
          </div>

          <div className="space-y-3">
            {FEATURES.map((feature) => (
              <div key={feature} className="flex items-center gap-3 text-sm text-white/60">
                <CheckCircle2 className="size-4 text-cyan-300" />
                {feature}
              </div>
            ))}
          </div>
        </div>

        <p className="text-white/30 text-xs">{APP_CONFIG.copyright}</p>
      </aside>

      <main className="flex flex-1 items-center justify-center px-5 py-10">
        <div className="w-full max-w-[680px] space-y-7">
          <div className="space-y-1">
            <div className="mb-4 flex items-center gap-2 lg:hidden">
              <Command className="size-5" />
              <span className="font-semibold">{APP_CONFIG.name}</span>
            </div>
            <h2 className="font-bold text-2xl">Sign in</h2>
            <p className="text-sm text-zinc-500">Choose any demo role to inspect the POC through that user’s access.</p>
          </div>

          <div className="grid gap-2 sm:grid-cols-2">
            {MOCK_CREDENTIALS.map((credential) => {
              const meta = accountMeta[credential.user.role];
              const Icon = meta.icon;
              const isActive = activeRole === credential.user.role;
              return (
                <button
                  key={credential.username}
                  type="button"
                  onClick={() => fillDemo(credential.username, credential.password, credential.user.role)}
                  className={`flex items-center gap-3 rounded-lg border bg-white p-3 text-left shadow-sm transition ${isActive ? "border-zinc-950 ring-1 ring-zinc-950/10" : "border-zinc-200 hover:border-zinc-300"}`}
                >
                  <span
                    className={`flex size-9 shrink-0 items-center justify-center rounded-md text-white ${meta.color}`}
                  >
                    <Icon className="size-4" />
                  </span>
                  <span className="min-w-0 flex-1">
                    <span className="flex items-center gap-2">
                      <span className="truncate font-semibold text-sm">{credential.user.name}</span>
                      <span
                        className={`shrink-0 rounded border px-1.5 py-px font-semibold text-[10px] ${ROLE_COLORS[credential.user.role]}`}
                      >
                        {ROLE_LABELS[credential.user.role]}
                      </span>
                    </span>
                    <span className="mt-0.5 block text-xs text-zinc-400">
                      {credential.username} / {credential.password}
                    </span>
                  </span>
                </button>
              );
            })}
          </div>

          <form onSubmit={handleSubmit} className="rounded-lg border bg-white p-4 shadow-sm">
            <div className="grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
              <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-zinc-400" />
                  <Input
                    id="username"
                    value={username}
                    onChange={(event) => {
                      setUsername(event.target.value);
                      setActiveRole("");
                      setError("");
                    }}
                    className="pl-9"
                    autoComplete="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-zinc-400" />
                  <Input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(event) => {
                      setPassword(event.target.value);
                      setError("");
                    }}
                    className="pl-9"
                    autoComplete="current-password"
                  />
                </div>
              </div>
              <Button type="submit" className="self-end" disabled={loading || !username || !password}>
                {loading ? "Signing in..." : "Enter"}
              </Button>
            </div>
            {error && <p className="mt-3 rounded-md bg-destructive/10 px-3 py-2 text-destructive text-sm">{error}</p>}
          </form>

          <p className="text-center text-sm text-zinc-500">
            New student?{" "}
            <Link href="/register" className="font-medium text-zinc-950 hover:underline">
              Create a portal account
            </Link>
          </p>
        </div>
      </main>
    </div>
  );
}
