"use client";

import React, { Suspense, useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import { ArrowUpRight, CheckCircle2, LogIn } from "lucide-react";
import { useAuth } from "@/components/onboarding/hooks/useAuth";
import {
  canContinueOnboarding,
  isWizardDeferred,
  resolveFarmerDestination,
} from "@/lib/farmer-routing";
import { DEV_FARMER_CREDENTIALS, DEV_OTP_CODE } from "@/lib/dev-seed-users";

const fadeUp = {
  hidden: { y: 30, opacity: 0 },
  visible: (i: number) => ({
    y: 0,
    opacity: 1,
    transition: { delay: i * 0.1, duration: 0.6, ease: [0.21, 0.45, 0.32, 0.9] as const },
  }),
};

const isDevToolsVisible = process.env.NODE_ENV !== "production";

function LoginContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const auth = useAuth();
  const justRegistered = searchParams.get("registered") === "1";
  const justDeferred = searchParams.get("deferred") === "1";
  const phoneParam = searchParams.get("phone") ?? "";

  const [phone, setPhone] = useState(phoneParam);
  const [otp, setOtp] = useState("");
  const [otpSent, setOtpSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const [error, setError] = useState("");

  const showContinueApplication =
    auth.isAuthenticated && canContinueOnboarding(auth) && isWizardDeferred(auth);

  useEffect(() => {
    if (phoneParam) setPhone(phoneParam);
  }, [phoneParam]);

  useEffect(() => {
    if (auth.loading || !auth.isAuthenticated) return;

    let cancelled = false;

    void (async () => {
      let routingAuth = auth;
      if (justRegistered || justDeferred) {
        const me = await auth.checkAuth();
        if (cancelled || !me) return;
        routingAuth = { activeSession: me.activeSession ?? null };
      }

      const dest = resolveFarmerDestination(routingAuth);
      if (justRegistered && dest === "/farmers/onboarding") return;
      router.replace(dest);
    })();

    return () => {
      cancelled = true;
    };
  }, [auth.loading, auth.isAuthenticated, justRegistered, justDeferred, auth, router]);

  const sendOtp = async () => {
    if (phone.length < 9) return;
    setSending(true);
    setError("");
    try {
      await auth.requestOtp(phone);
      setOtpSent(true);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to send OTP");
    } finally {
      setSending(false);
    }
  };

  const verifyAndLogin = async () => {
    if (otp.length < 4) return;
    setVerifying(true);
    setError("");
    try {
      await auth.verify(phone, otp);
      const me = await auth.checkAuth();
      const routingAuth = { activeSession: me?.activeSession ?? null };
      router.push(resolveFarmerDestination(routingAuth));
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Invalid OTP");
      setVerifying(false);
    }
  };

  return (
    <main className="min-h-screen">
      <section className="relative w-full overflow-hidden bg-gradient-to-b from-[var(--page-2)] to-[var(--page)] pt-24 pb-20 lg:pt-32 lg:pb-28">
        <div className="absolute inset-0 pointer-events-none opacity-30">
          <div className="absolute top-0 left-1/3 w-[500px] h-[500px] rounded-full bg-green-deep/10 blur-[120px]" />
        </div>

        <div className="relative z-10 max-w-md mx-auto px-4 sm:px-6 lg:px-8">
          <motion.div
            initial="hidden"
            animate="visible"
            custom={0}
            variants={fadeUp}
            className="text-center mb-8"
          >
            <a href="/">
              <img src="/agnet-global-logo.png" alt="AgNet Global" className="h-10 mx-auto mb-6" />
            </a>

            {justRegistered && (
              <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-green-deep/15 bg-green-deep/5 mb-6">
                <CheckCircle2 className="w-4 h-4 text-green-deep" />
                <span className="font-inter text-sm font-medium text-green-deep">
                  Registration complete!
                </span>
              </div>
            )}

            {justDeferred && (
              <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-green-deep/15 bg-green-deep/5 mb-6">
                <CheckCircle2 className="w-4 h-4 text-green-deep" />
                <span className="font-inter text-sm font-medium text-green-deep">
                  Identity verified — finish your application anytime
                </span>
              </div>
            )}

            <h1 className="font-onest text-3xl sm:text-4xl font-semibold leading-tight tracking-tight text-ink">
              {justRegistered ? "Welcome to AGNET" : "Farmer Login"}
            </h1>
            <p className="mt-3 font-inter text-base text-ink-soft leading-relaxed">
              {justRegistered
                ? "Your application has been submitted. Log in to track your status."
                : justDeferred
                  ? "Your identity is verified. Log in to explore your dashboard or continue your application."
                  : "Enter your phone number to access your farmer dashboard."}
            </p>
          </motion.div>

          <motion.div
            initial="hidden"
            animate="visible"
            custom={1}
            variants={fadeUp}
            className="space-y-4"
          >
            {showContinueApplication && (
              <button
                type="button"
                onClick={() => router.push("/farmers/onboarding")}
                className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full border border-green-deep/30 bg-green-deep/5 text-green-deep font-inter font-medium text-base hover:bg-green-deep/10 transition-colors cursor-pointer"
              >
                Continue your application
                <ArrowUpRight className="w-4 h-4" />
              </button>
            )}

            {error && (
              <div className="rounded-xl border border-red-200 bg-red-50 dark:border-red-700/30 dark:bg-red-900/20 px-4 py-3 text-sm text-red-700 dark:text-red-400 font-inter">
                {error}
              </div>
            )}

            <div>
              <label htmlFor="login-phone" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
                Phone Number
              </label>
              <input
                id="login-phone"
                type="tel"
                placeholder="+998 XX XXX XX XX"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                disabled={otpSent}
                className="w-full px-4 py-3 rounded-xl border border-border bg-surface font-inter text-sm text-ink placeholder:text-muted/70 focus:outline-none focus:border-green-deep/40 focus:ring-1 focus:ring-green-deep/20 transition-colors disabled:opacity-50"
              />
            </div>

            {!otpSent ? (
              <button
                onClick={sendOtp}
                disabled={phone.length < 9 || sending}
                className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
              >
                {sending ? "Sending..." : "Send Verification Code"}
                <LogIn className="w-4 h-4" />
              </button>
            ) : (
              <>
                <div>
                  <label htmlFor="login-otp" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
                    Verification Code
                  </label>
                  <input
                    id="login-otp"
                    type="text"
                    maxLength={4}
                    placeholder="1234"
                    value={otp}
                    onChange={(e) => setOtp(e.target.value)}
                    className="w-full px-4 py-3 rounded-xl border border-border bg-surface font-inter text-sm text-ink placeholder:text-muted/70 focus:outline-none focus:border-green-deep/40 focus:ring-1 focus:ring-green-deep/20 transition-colors tracking-widest text-center"
                  />
                  {isDevToolsVisible && (
                    <p className="mt-1 text-xs text-muted font-inter">
                      Dev OTP: <code className="font-mono text-green-deep">{DEV_OTP_CODE}</code>
                    </p>
                  )}
                </div>
                <button
                  onClick={verifyAndLogin}
                  disabled={otp.length < 4 || verifying}
                  className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
                >
                  {verifying ? "Logging in..." : "Log In"}
                  <ArrowUpRight className="w-4 h-4" />
                </button>
                <button
                  onClick={() => { setOtpSent(false); setOtp(""); setError(""); }}
                  className="w-full text-center font-inter text-sm text-green-deep hover:underline cursor-pointer"
                >
                  Change phone number
                </button>
              </>
            )}

            <div className="pt-4 border-t border-border mt-4 space-y-3">
              <p className="text-center font-inter text-sm text-muted">
                New farmer?{" "}
                <a href="/farmers/apply" className="text-green-deep font-medium hover:underline">
                  Apply for the pilot
                </a>
                {" · "}
                <a href="/login" className="text-green-deep font-medium hover:underline">
                  All demo logins
                </a>
              </p>
              {isDevToolsVisible && (
                <div className="rounded-xl border border-border/60 bg-[var(--page)]/50 p-3 space-y-1.5">
                  <p className="font-inter text-xs font-medium text-ink-soft">Seeded demo farmers</p>
                  {DEV_FARMER_CREDENTIALS.map((f) => (
                    <button
                      key={f.userId}
                      type="button"
                      onClick={() => { setPhone(f.phone); setOtpSent(false); setOtp(""); setError(""); }}
                      className="block w-full text-left font-inter text-xs text-muted hover:text-green-deep cursor-pointer"
                    >
                      {f.name} — {f.phone}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </motion.div>
        </div>
      </section>
    </main>
  );
}

export default function FarmerLoginPage() {
  return (
    <Suspense>
      <LoginContent />
    </Suspense>
  );
}
