"use client";

import { useState } from "react";

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

import { zodResolver } from "@hookform/resolvers/zod";
import {
  Activity,
  ArrowLeft,
  BarChart2,
  Eye,
  EyeOff,
  Lock,
  Mail,
  Shield,
  ShieldCheck,
  Users,
} from "lucide-react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useAuthStore } from "@/stores/auth-store";
import { cn } from "@/lib/utils";

const adminLoginSchema = z.object({
  email: z.string().email("Please enter a valid email address"),
  password: z.string().min(1, "Password is required"),
});

type AdminLoginFormValues = z.infer<typeof adminLoginSchema>;

const ADMIN_FEATURES = [
  { icon: Users, label: "User management", desc: "Profiles, assessments & billing" },
  { icon: Activity, label: "GLP-1 eligibility", desc: "Medical review workflow" },
  { icon: BarChart2, label: "Analytics & CRM", desc: "Revenue, leads & conversions" },
];

export default function AdminLoginPage() {
  const router = useRouter();
  const loginAdmin = useAuthStore((s) => s.loginAdmin);
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<AdminLoginFormValues>({
    resolver: zodResolver(adminLoginSchema),
  });

  const fillDemo = () => {
    setValue("email", "admin@novalife.com");
    setValue("password", "Admin@123");
    toast.info("Demo credentials applied");
  };

  const onSubmit = async (data: AdminLoginFormValues) => {
    setIsLoading(true);
    await new Promise((r) => setTimeout(r, 400));

    const result = loginAdmin(data.email, data.password);
    setIsLoading(false);

    if (!result.success) {
      toast.error(result.error ?? "Invalid admin credentials.");
      return;
    }

    toast.success("Admin access granted.");
    router.replace("/admin");
  };

  return (
    <div className="relative min-h-screen overflow-hidden bg-[#0a0f1a]">
      {/* Ambient background */}
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -left-32 top-0 h-[500px] w-[500px] rounded-full bg-teal-600/10 blur-[120px]" />
        <div className="absolute -right-32 bottom-0 h-[400px] w-[400px] rounded-full bg-cyan-500/8 blur-[100px]" />
        <div
          className="absolute inset-0 opacity-[0.04]"
          style={{
            backgroundImage:
              "linear-gradient(rgba(255,255,255,1) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,1) 1px,transparent 1px)",
            backgroundSize: "48px 48px",
          }}
        />
      </div>

      <div className="relative z-10 flex min-h-screen">
        {/* Left panel — branding (desktop) */}
        <aside className="hidden lg:flex lg:w-[52%] xl:w-[55%] flex-col justify-between border-r border-white/5 bg-gradient-to-br from-[#0d1526] to-[#0a0f1a] p-12 xl:p-16">
          <div>
            <Link
              href="/"
              className="inline-flex items-center gap-2 text-sm text-slate-500 transition-colors hover:text-slate-300"
            >
              <ArrowLeft className="h-4 w-4" />
              Back to site
            </Link>

            <div className="mt-14 flex items-center gap-4">
              <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-teal-500 to-teal-700 shadow-lg shadow-teal-900/50">
                <Shield className="h-7 w-7 text-white" />
              </div>
              <div>
                <h1 className="text-3xl font-extrabold tracking-tight text-white">
                  Nova<span className="text-teal-400">life</span>
                </h1>
                <p className="text-sm font-medium text-teal-400/90">Admin Portal</p>
              </div>
            </div>

            <p className="mt-8 max-w-md text-lg leading-relaxed text-slate-400">
              Secure management console for the Novalife Precision Diagnostic platform.
            </p>

            <ul className="mt-12 space-y-5">
              {ADMIN_FEATURES.map(({ icon: Icon, label, desc }) => (
                <li key={label} className="flex items-start gap-4">
                  <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white/5 ring-1 ring-white/10">
                    <Icon className="h-5 w-5 text-teal-400" />
                  </div>
                  <div>
                    <p className="font-semibold text-white">{label}</p>
                    <p className="text-sm text-slate-500">{desc}</p>
                  </div>
                </li>
              ))}
            </ul>
          </div>

          <div className="flex items-center gap-2 rounded-xl border border-amber-500/20 bg-amber-500/5 px-4 py-3">
            <ShieldCheck className="h-4 w-4 shrink-0 text-amber-400" />
            <p className="text-xs text-amber-200/80">
              Restricted access — authorised personnel only. All actions are logged in PoC mode.
            </p>
          </div>
        </aside>

        {/* Right panel — login form */}
        <main className="flex flex-1 flex-col items-center justify-center px-6 py-12 sm:px-10">
          {/* Mobile header */}
          <div className="mb-8 w-full max-w-[420px] text-center lg:hidden">
            <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-teal-500 to-teal-700">
              <Shield className="h-6 w-6 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-white">
              Nova<span className="text-teal-400">life</span> Admin
            </h1>
            <p className="mt-1 text-sm text-slate-500">Management dashboard access</p>
          </div>

          <div className="w-full max-w-[420px]">
            <div className="rounded-2xl border border-white/10 bg-white/[0.03] p-8 shadow-2xl shadow-black/40 backdrop-blur-xl">
              <div className="mb-8">
                <h2 className="text-xl font-bold text-white">Sign in</h2>
                <p className="mt-1 text-sm text-slate-400">
                  Enter your admin credentials to continue
                </p>
              </div>

              {/* Demo quick-fill */}
              <button
                type="button"
                onClick={fillDemo}
                className="group mb-6 w-full rounded-xl border border-teal-500/25 bg-teal-500/5 p-4 text-left transition-all hover:border-teal-500/40 hover:bg-teal-500/10"
              >
                <div className="flex items-center justify-between gap-3">
                  <div className="flex items-center gap-2">
                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-teal-500/20">
                      <ShieldCheck className="h-4 w-4 text-teal-400" />
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-teal-300">Use demo admin</p>
                      <p className="text-xs text-slate-500">One-click fill for PoC demo</p>
                    </div>
                  </div>
                  <span className="rounded-lg bg-teal-600 px-3 py-1.5 text-xs font-bold text-white opacity-90 transition-opacity group-hover:opacity-100">
                    Fill
                  </span>
                </div>
                <div className="mt-3 grid grid-cols-2 gap-2 font-mono text-[11px] text-slate-400">
                  <span className="truncate rounded-md bg-black/20 px-2 py-1">admin@novalife.com</span>
                  <span className="truncate rounded-md bg-black/20 px-2 py-1">Admin@123</span>
                </div>
              </button>

              <div className="mb-6 flex items-center gap-3">
                <div className="h-px flex-1 bg-white/10" />
                <span className="text-xs text-slate-600">or sign in manually</span>
                <div className="h-px flex-1 bg-white/10" />
              </div>

              <form
                id="admin-login-form"
                onSubmit={handleSubmit(onSubmit)}
                className="space-y-5"
                noValidate
              >
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-sm font-medium text-slate-300">
                    Admin email
                  </Label>
                  <div className="relative">
                    <Mail className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                    <Input
                      id="email"
                      type="email"
                      placeholder="admin@novalife.com"
                      autoComplete="email"
                      className={cn(
                        "h-11 border-white/10 bg-white/5 pl-10 text-white placeholder:text-slate-600",
                        "focus-visible:border-teal-500/50 focus-visible:ring-teal-500/20",
                        errors.email && "border-red-500/50",
                      )}
                      {...register("email")}
                    />
                  </div>
                  {errors.email && (
                    <p className="text-xs text-red-400">{errors.email.message}</p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="password" className="text-sm font-medium text-slate-300">
                    Password
                  </Label>
                  <div className="relative">
                    <Lock className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="••••••••"
                      autoComplete="current-password"
                      className={cn(
                        "h-11 border-white/10 bg-white/5 pl-10 pr-11 text-white placeholder:text-slate-600",
                        "focus-visible:border-teal-500/50 focus-visible:ring-teal-500/20",
                        errors.password && "border-red-500/50",
                      )}
                      {...register("password")}
                    />
                    <button
                      type="button"
                      tabIndex={-1}
                      onClick={() => setShowPassword((v) => !v)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 transition-colors hover:text-slate-300"
                      aria-label={showPassword ? "Hide password" : "Show password"}
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </button>
                  </div>
                  {errors.password && (
                    <p className="text-xs text-red-400">{errors.password.message}</p>
                  )}
                </div>

                <Button
                  type="submit"
                  disabled={isLoading}
                  className="h-11 w-full rounded-xl bg-gradient-to-r from-teal-600 to-teal-500 font-semibold text-white shadow-lg shadow-teal-900/30 transition-all hover:from-teal-500 hover:to-teal-400 hover:shadow-teal-800/40 disabled:opacity-70"
                >
                  {isLoading ? (
                    <span className="flex items-center gap-2">
                      <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                      Authenticating…
                    </span>
                  ) : (
                    <span className="flex items-center gap-2">
                      <Shield className="h-4 w-4" />
                      Access admin dashboard
                    </span>
                  )}
                </Button>
              </form>
            </div>

            <p className="mt-6 text-center text-sm text-slate-500">
              User account?{" "}
              <Link
                href="/auth/login"
                className="font-medium text-teal-400 transition-colors hover:text-teal-300"
              >
                User sign in
              </Link>
            </p>

            <p className="mt-4 text-center text-xs text-slate-600">
              Demo application — no real data is stored or transmitted.
            </p>
          </div>
        </main>
      </div>
    </div>
  );
}
