"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useSWRConfig } from "swr";
import {
  ArrowLeft,
  ArrowRight,
  BarChart3,
  FileText,
  Loader2,
  LockKeyhole,
  ShieldCheck,
  Users,
} from "lucide-react";
import { toast } from "sonner";
import { Logo } from "@/components/logo";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const DEMO_ACCOUNTS = [
  { role: "Administrator", username: "admin", password: "admin123" },
  { role: "Operator", username: "operator", password: "operator123" },
  { role: "Editor", username: "editor", password: "editor123" },
];

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { mutate } = useSWRConfig();
  const next = searchParams.get("next") || "/admin";

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });
      const data = await res.json().catch(() => ({}));

      if (!res.ok) {
        setError(data?.message ?? "Login gagal. Periksa username dan password.");
        return;
      }

      await mutate("/api/auth/session").catch(() => undefined);
      toast.success(`Selamat datang, ${data?.user?.nama ?? username}`);
      router.replace(next);
      router.refresh();
    } catch {
      setError("Tidak dapat menghubungi server. Coba lagi.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="grid min-h-screen lg:grid-cols-[1.05fr_1fr]">
      <aside className="relative hidden overflow-hidden bg-sidebar p-12 text-white lg:flex lg:flex-col lg:justify-between">
        <div className="absolute inset-0 bg-brand-deep opacity-40" />
        <div className="hero-grid absolute inset-0 opacity-60" />
        <div className="orb-brand absolute -left-20 top-16 h-72 w-72 rounded-full blur-3xl" />
        <div className="absolute -right-16 bottom-10 h-80 w-80 rounded-full bg-[hsl(var(--primary)/0.22)] blur-3xl" />

        <div className="relative">
          <Link href="/" className="inline-flex items-center gap-3">
            <Logo className="h-16 w-auto" />
            <div>
              <div className="text-lg font-bold tracking-tight">Core Mulyadadi</div>
              <div className="text-xs text-white/55">Sistem Informasi Desa</div>
            </div>
          </Link>

          <h1 className="mt-16 max-w-md text-4xl font-bold leading-tight tracking-tight text-balance">
            Satu pintu layanan administrasi desa.
          </h1>
          <p className="mt-4 max-w-md text-sm leading-relaxed text-white/70">
            Kelola data kependudukan, layanan surat, keuangan desa, dan publikasi
            berita dalam satu sistem terintegrasi.
          </p>

          <div className="mt-10 space-y-4">
            {[
              { icon: Users, title: "Data kependudukan", desc: "Penduduk, keluarga, dan wilayah RT." },
              { icon: FileText, title: "Layanan surat", desc: "Permohonan dan jenis surat keterangan." },
              { icon: BarChart3, title: "Transparansi APBDes", desc: "Anggaran dan realisasi tiap bidang." },
              { icon: ShieldCheck, title: "Akses berbasis peran", desc: "Admin, operator, dan editor berita." },
            ].map((item) => (
              <div key={item.title} className="flex gap-3">
                <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/5">
                  <item.icon className="h-4 w-4 text-brand-accent" />
                </div>
                <div>
                  <div className="text-sm font-semibold">{item.title}</div>
                  <div className="text-xs text-white/55">{item.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <p className="relative text-xs text-white/40">
          Next.js · NestJS · MySQL · Prisma
        </p>
      </aside>

      <main className="flex items-center justify-center bg-background px-5 py-12">
        <div className="w-full max-w-sm">
          <Link
            href="/"
            className="inline-flex items-center gap-2 text-sm text-muted-foreground transition-colors hover:text-foreground lg:hidden"
          >
            <ArrowLeft className="h-4 w-4" />
            Kembali ke website desa
          </Link>

          <div className="mt-8 flex items-center gap-3 lg:hidden">
            <Logo className="h-12 w-auto" />
            <div>
              <div className="font-bold">Core Mulyadadi</div>
              <div className="text-xs text-muted-foreground">Sistem Informasi Desa</div>
            </div>
          </div>

          <div className="mt-8 flex h-12 w-12 items-center justify-center rounded-2xl bg-secondary text-primary">
            <LockKeyhole className="h-6 w-6" />
          </div>
          <h2 className="mt-5 text-2xl font-bold tracking-tight">Masuk ke Dasbor</h2>
          <p className="mt-1 text-sm text-muted-foreground">
            Gunakan akun yang diberikan administrator desa.
          </p>

          <form onSubmit={handleSubmit} className="mt-7 space-y-4">
            <div className="space-y-2">
              <Label htmlFor="username">Username</Label>
              <Input
                id="username"
                name="username"
                autoComplete="username"
                placeholder="mis. admin"
                value={username}
                onChange={(event) => setUsername(event.target.value)}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                placeholder="••••••••"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                required
              />
            </div>

            {error && (
              <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                {error}
              </div>
            )}

            <Button type="submit" className="w-full" size="lg" disabled={loading}>
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Memproses…
                </>
              ) : (
                <>
                  Masuk
                  <ArrowRight className="h-4 w-4" />
                </>
              )}
            </Button>
          </form>

          <div className="mt-8 rounded-xl border border-dashed border-border bg-muted/40 p-4">
            <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              Akun demo
            </div>
            <div className="mt-3 space-y-2">
              {DEMO_ACCOUNTS.map((account) => (
                <button
                  key={account.username}
                  type="button"
                  onClick={() => {
                    setUsername(account.username);
                    setPassword(account.password);
                    setError(null);
                  }}
                  className="flex w-full items-center justify-between rounded-lg border border-border bg-card px-3 py-2 text-left text-xs transition-colors hover:border-primary/40 hover:bg-secondary"
                >
                  <span className="font-semibold">{account.role}</span>
                  <span className="font-mono text-muted-foreground">
                    {account.username} / {account.password}
                  </span>
                </button>
              ))}
            </div>
          </div>

          <p className="mt-6 text-center text-xs text-muted-foreground">
            <Link href="/" className="inline-flex items-center gap-1 hover:text-foreground">
              <ArrowLeft className="h-3 w-3" />
              Kembali ke website desa
            </Link>
          </p>
        </div>
      </main>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
          Memuat…
        </div>
      }
    >
      <LoginForm />
    </Suspense>
  );
}
