"use client";

import React, { Suspense, useState, useEffect, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import { ArrowUpRight, Sparkles, RefreshCw } from "lucide-react";
import { useAuth } from "@/components/onboarding/hooks/useAuth";
import { canStartReapplication, resolveFarmerDestination } from "@/lib/farmer-routing";
import { api } from "@/lib/api-client";

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 },
  }),
};

function FarmerApplyPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const auth = useAuth();
  const [phone, setPhone] = useState("");
  const [otp, setOtp] = useState("");
  const [otpSent, setOtpSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const [startingNew, setStartingNew] = useState(false);
  const [error, setError] = useState("");

  const isReapply =
    searchParams.get("reapply") === "1" ||
    (auth.isAuthenticated && canStartReapplication(auth));

  useEffect(() => {
    if (auth.loading) return;
    if (auth.isAuthenticated && !isReapply) {
      router.replace(resolveFarmerDestination(auth));
    }
  }, [auth.loading, auth.isAuthenticated, auth, isReapply, 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 verifyAndRedirect = async () => {
    if (otp.length < 4) return;
    setVerifying(true);
    setError("");
    try {
      await auth.verify(phone, otp);
      const me = await auth.checkAuth();
      router.push(resolveFarmerDestination({ activeSession: me?.activeSession ?? null }));
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Invalid OTP");
      setVerifying(false);
    }
  };

  const startNewApplication = useCallback(async () => {
    setStartingNew(true);
    setError("");
    try {
      await api.onboarding.createOrResume("UZ", "farmer", true);
      await auth.checkAuth();
      router.push("/farmers/onboarding");
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Could not start new application");
      setStartingNew(false);
    }
  }, [auth, router]);

  if (auth.loading) return null;

  if (auth.isAuthenticated && isReapply) {
    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="relative z-10 max-w-md mx-auto px-4 sm:px-6 lg:px-8 text-center space-y-6">
            <img src="/agnet-global-logo.png" alt="AgNet Global" className="h-10 mx-auto" />
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-green-deep/15 bg-green-deep/5">
              <RefreshCw className="w-4 h-4 text-green-deep" />
              <span className="font-inter text-sm font-medium text-green-deep">Re-application</span>
            </div>
            <h1 className="font-onest text-3xl font-semibold text-ink">
              Start a new application
            </h1>
            <p className="font-inter text-sm text-ink-soft leading-relaxed">
              Your previous pilot application is complete. You can view your dashboard or begin a
              fresh application for a new financing season.
            </p>
            {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>
            )}
            <button
              onClick={startNewApplication}
              disabled={startingNew}
              className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium cursor-pointer disabled:opacity-50"
            >
              {startingNew ? "Starting..." : "Start new application"}
              <ArrowUpRight className="w-4 h-4" />
            </button>
            <button
              onClick={() => router.push("/farmers/dashboard")}
              className="w-full font-inter text-sm text-green-deep hover:underline cursor-pointer"
            >
              Go to dashboard
            </button>
          </div>
        </section>
      </main>
    );
  }

  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>

            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-green-deep/15 bg-green-deep/5 mb-6">
              <Sparkles className="w-4 h-4 text-green-deep" />
              <span className="font-inter text-sm font-medium text-green-deep">
                Farmer Pilot Application
              </span>
            </div>

            <h1 className="font-onest text-3xl sm:text-4xl font-semibold leading-tight tracking-tight text-ink">
              Start your{" "}
              <span className="font-playfair italic text-muted">onboarding</span>
            </h1>
            <p className="mt-3 font-inter text-base text-ink-soft leading-relaxed">
              Enter your phone number to begin or resume your pilot application.
            </p>
          </motion.div>

          <motion.div
            initial="hidden"
            animate="visible"
            custom={1}
            variants={fadeUp}
            className="space-y-4"
          >
            {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="apply-phone" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
                Phone Number
              </label>
              <input
                id="apply-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"}
                <ArrowUpRight className="w-4 h-4" />
              </button>
            ) : (
              <>
                <div>
                  <label htmlFor="apply-otp" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
                    Verification Code
                  </label>
                  <input
                    id="apply-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"
                  />
                  <p className="mt-1 text-xs text-muted font-inter">
                    In development, use code: 1234
                  </p>
                </div>
                <button
                  onClick={verifyAndRedirect}
                  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 ? "Verifying..." : "Continue to Application"}
                  <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>
              </>
            )}

            <p className="text-center font-inter text-xs text-muted pt-2">
              Already completed? Sign in to start a re-application or view your dashboard.
            </p>
          </motion.div>
        </div>
      </section>
    </main>
  );
}

export default function FarmerApplyPage() {
  return (
    <Suspense fallback={null}>
      <FarmerApplyPageContent />
    </Suspense>
  );
}
