"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ArrowUpRight, Building2, Shield, Sprout } from "lucide-react";
import {
  DEV_FARMER_CREDENTIALS,
  DEV_OFFICER_CREDENTIALS,
  DEV_OTP_CODE,
  DEV_PASSWORD,
} from "@/lib/dev-seed-users";

function CredentialRow({
  label,
  value,
}: {
  label: string;
  value: string;
}) {
  return (
    <div className="flex justify-between gap-4 font-inter text-sm">
      <span className="text-ink-soft shrink-0">{label}</span>
      <code className="text-ink font-mono text-xs sm:text-sm text-right break-all">{value}</code>
    </div>
  );
}

export default function LoginHubPage() {
  const router = useRouter();
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [error, setError] = useState("");

  const quickAdminLogin = async (email: string) => {
    setLoadingId(email);
    setError("");
    try {
      const res = await fetch("/api/admin/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password: DEV_PASSWORD }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body?.error?.message ?? "Login failed");
      }
      router.push("/admin/cases");
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Login failed");
      setLoadingId(null);
    }
  };

  return (
    <main className="min-h-screen bg-gradient-to-b from-[var(--page-2)] to-[var(--page)] pt-24 pb-20">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-10">
          <Link href="/">
            <img src="/agnet-global-logo.png" alt="AgNet Global" className="h-10 mx-auto mb-6" />
          </Link>
          <h1 className="font-onest text-3xl sm:text-4xl font-semibold text-ink tracking-tight">
            Sign in to AGNET
          </h1>
          <p className="mt-3 font-inter text-base text-ink-soft max-w-xl mx-auto">
            Choose your role below. Development credentials are listed for demo personas — OTP code is{" "}
            <code className="font-mono text-green-deep">{DEV_OTP_CODE}</code>, officer password is{" "}
            <code className="font-mono text-green-deep">{DEV_PASSWORD}</code>.
          </p>
        </div>

        {error && (
          <div className="mb-6 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 font-inter">
            {error}
          </div>
        )}

        <div className="space-y-8">
          {/* Farmers */}
          <section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
            <div className="flex items-center gap-3 mb-5">
              <div className="w-10 h-10 rounded-xl bg-green-deep/10 flex items-center justify-center">
                <Sprout className="w-5 h-5 text-green-deep" />
              </div>
              <div>
                <h2 className="font-onest text-lg font-semibold text-ink">Farmers</h2>
                <p className="font-inter text-xs text-muted">Phone OTP login → farmer dashboard</p>
              </div>
            </div>
            <div className="space-y-4">
              {DEV_FARMER_CREDENTIALS.map((farmer) => (
                <div
                  key={farmer.userId}
                  className="rounded-xl border border-border bg-[var(--page)]/50 p-4 space-y-3"
                >
                  <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                    <div>
                      <p className="font-onest font-medium text-ink">{farmer.name}</p>
                      <p className="font-inter text-xs text-muted mt-0.5">{farmer.description}</p>
                      <span className="inline-block mt-2 px-2 py-0.5 rounded-full bg-green-deep/10 text-green-deep font-inter text-xs font-medium capitalize">
                        {farmer.module} module
                      </span>
                    </div>
                    <Link
                      href={`/farmers/login?phone=${encodeURIComponent(farmer.phone)}`}
                      className="inline-flex items-center justify-center gap-1.5 px-4 py-2 rounded-full bg-green-deep text-white font-inter text-sm font-medium hover:bg-green-deep/90 shrink-0"
                    >
                      Log in
                      <ArrowUpRight className="w-3.5 h-3.5" />
                    </Link>
                  </div>
                  <div className="space-y-1.5 pt-2 border-t border-border/60">
                    <CredentialRow label="Phone" value={farmer.phone} />
                    <CredentialRow label="OTP" value={farmer.otp} />
                  </div>
                </div>
              ))}
            </div>
          </section>

          {/* AGNET Officers */}
          <section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
            <div className="flex items-center gap-3 mb-5">
              <div className="w-10 h-10 rounded-xl bg-[#042718]/10 flex items-center justify-center">
                <Shield className="w-5 h-5 text-[#042718]" />
              </div>
              <div>
                <h2 className="font-onest text-lg font-semibold text-ink">AGNET Officers</h2>
                <p className="font-inter text-xs text-muted">Email + password → case review portal</p>
              </div>
            </div>
            <div className="space-y-4">
              {DEV_OFFICER_CREDENTIALS.filter((c) => c.kind === "agnet_officer").map((cred) => (
                <div
                  key={cred.officer.id}
                  className="rounded-xl border border-border bg-[var(--page)]/50 p-4 space-y-3"
                >
                  <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                    <div>
                      <p className="font-onest font-medium text-ink">{cred.officer.name}</p>
                      <p className="font-inter text-xs text-muted mt-0.5">{cred.description}</p>
                      <span className="inline-block mt-2 px-2 py-0.5 rounded-full bg-[#042718]/10 text-[#042718] font-inter text-xs font-medium capitalize">
                        {cred.officer.role.replace("_", " ")} · {cred.officer.permissions.join(", ")}
                      </span>
                    </div>
                    <button
                      type="button"
                      disabled={loadingId === cred.officer.email}
                      onClick={() => quickAdminLogin(cred.officer.email)}
                      className="inline-flex items-center justify-center gap-1.5 px-4 py-2 rounded-full bg-[#042718] text-white font-inter text-sm font-medium hover:bg-[#042718]/90 disabled:opacity-50 shrink-0 cursor-pointer"
                    >
                      {loadingId === cred.officer.email ? "Signing in…" : "Log in"}
                      <ArrowUpRight className="w-3.5 h-3.5" />
                    </button>
                  </div>
                  <div className="space-y-1.5 pt-2 border-t border-border/60">
                    <CredentialRow label="Email" value={cred.officer.email} />
                    <CredentialRow label="Password" value={cred.password} />
                  </div>
                </div>
              ))}
            </div>
          </section>

          {/* Bank Authority */}
          <section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
            <div className="flex items-center gap-3 mb-5">
              <div className="w-10 h-10 rounded-xl bg-violet-500/10 flex items-center justify-center">
                <Building2 className="w-5 h-5 text-violet-700" />
              </div>
              <div>
                <h2 className="font-onest text-lg font-semibold text-ink">Bank Authority</h2>
                <p className="font-inter text-xs text-muted">
                  Institution-scoped case queue — Agrobank routed applications only
                </p>
              </div>
            </div>
            <div className="space-y-4">
              {DEV_OFFICER_CREDENTIALS.filter((c) => c.kind === "bank_officer").map((cred) => (
                <div
                  key={cred.officer.id}
                  className="rounded-xl border border-border bg-[var(--page)]/50 p-4 space-y-3"
                >
                  <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                    <div>
                      <p className="font-onest font-medium text-ink">{cred.officer.name}</p>
                      <p className="font-inter text-xs text-muted mt-0.5">{cred.description}</p>
                      <span className="inline-block mt-2 px-2 py-0.5 rounded-full bg-violet-500/10 text-violet-700 font-inter text-xs font-medium">
                        {cred.officer.institutionId} · institution-only access
                      </span>
                    </div>
                    <button
                      type="button"
                      disabled={loadingId === cred.officer.email}
                      onClick={() => quickAdminLogin(cred.officer.email)}
                      className="inline-flex items-center justify-center gap-1.5 px-4 py-2 rounded-full bg-violet-700 text-white font-inter text-sm font-medium hover:bg-violet-700/90 disabled:opacity-50 shrink-0 cursor-pointer"
                    >
                      {loadingId === cred.officer.email ? "Signing in…" : "Log in"}
                      <ArrowUpRight className="w-3.5 h-3.5" />
                    </button>
                  </div>
                  <div className="space-y-1.5 pt-2 border-t border-border/60">
                    <CredentialRow label="Email" value={cred.officer.email} />
                    <CredentialRow label="Password" value={cred.password} />
                    <CredentialRow label="Institution" value={cred.officer.institutionId ?? "—"} />
                  </div>
                </div>
              ))}
            </div>
          </section>
        </div>

        <p className="mt-10 text-center font-inter text-xs text-muted">
          New farmer?{" "}
          <Link href="/farmers/apply" className="text-green-deep font-medium hover:underline">
            Apply for the pilot
          </Link>
        </p>
      </div>
    </main>
  );
}
