"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import { Background } from "../../components/background";
import { PageSchema } from "../../components/page-schema";
import { SiteFooter } from "../../components/site-footer";
import { SiteHeader } from "../../components/site-header";
import { defaultFaqs } from "../../data/faq";
import { siteInfo } from "../../data/site";
import { storeAuthTokens } from "@/lib/api";

type ApiResponse<T> = {
  data: T;
  meta: { timestamp: string; version: "v1" };
  error: null | { message: string; code?: string };
};

type AuthData = {
  user: { id: string; email: string; fullName?: string; emailVerified?: boolean };
  accessToken?: string;
  refreshToken?: string;
  requiresTwoFactor?: boolean;
};

const socialButtonClass =
  "flex w-full items-center justify-center gap-3 rounded-xl border border-border bg-white py-3 px-4 text-sm font-medium text-foreground shadow-sm transition-all hover:shadow-md hover:border-primary/30 focus:outline-none focus:ring-2 focus:ring-primary/20";

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = searchParams.get("next") ?? "/app";

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [staySignedIn, setStaySignedIn] = useState(true);
  const [totpToken, setTotpToken] = useState("");
  const [requiresTwoFactor, setRequiresTwoFactor] = useState(false);
  const [socialLoading, setSocialLoading] = useState<"google" | "apple" | null>(null);
  const [status, setStatus] = useState<string>("");
  const [isError, setIsError] = useState(false);

  const startSocialLogin = async (provider: "google" | "apple") => {
    setSocialLoading(provider);
    setStatus(`Redirecting to ${provider === "google" ? "Google" : "Apple"}...`);
    setIsError(false);
    try {
      const res = await fetch(`/api/auth/social/${provider}/url?next=${encodeURIComponent(nextPath)}`);
      const payload = (await res.json()) as ApiResponse<{ authUrl: string }>;
      if (!res.ok || payload.error || !payload.data?.authUrl) {
        setStatus(payload.error?.message ?? `${provider === "google" ? "Google" : "Apple"} sign in is unavailable.`);
        setIsError(true);
        setSocialLoading(null);
        return;
      }
      window.location.href = payload.data.authUrl;
    } catch {
      setStatus(`${provider === "google" ? "Google" : "Apple"} sign in failed to start.`);
      setIsError(true);
      setSocialLoading(null);
    }
  };

  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setStatus("Signing in...");
    setIsError(false);
    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, ...(requiresTwoFactor ? { totpToken } : {}) }),
      });
      const payload = (await res.json()) as ApiResponse<AuthData>;
      if (!res.ok || payload.error) {
        setStatus(payload.error?.message ?? "Login failed.");
        setIsError(true);
        return;
      }

      if (payload.data.requiresTwoFactor) {
        setRequiresTwoFactor(true);
        setStatus("Enter the code from your authenticator app.");
        return;
      }

      storeAuthTokens({
        user: payload.data.user,
      });
      setStatus(`Welcome back, ${payload.data.user.email}`);
      router.push(nextPath);
    } catch {
      setStatus("Login failed. Please try again.");
      setIsError(true);
    }
  };

  return (
    <form className="space-y-6" onSubmit={onSubmit}>
      {/* Social sign in */}
      <div className="flex flex-col gap-3">
        <button
          type="button"
          className={socialButtonClass}
          aria-label="Continue with Apple"
          disabled={socialLoading !== null}
          onClick={() => startSocialLogin("apple")}
        >
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
            <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z" />
          </svg>
          {socialLoading === "apple" ? "Redirecting..." : "Continue with Apple"}
        </button>
        <button
          type="button"
          className={socialButtonClass}
          aria-label="Continue with Google"
          disabled={socialLoading !== null}
          onClick={() => startSocialLogin("google")}
        >
          <svg className="h-5 w-5" viewBox="0 0 24 24" aria-hidden>
            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
          </svg>
          {socialLoading === "google" ? "Redirecting..." : "Continue with Google"}
        </button>
      </div>

      <div className="relative">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-border" />
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="bg-transparent px-3 text-muted-foreground">or</span>
        </div>
      </div>

      <div>
        <label htmlFor="email" className="block text-sm font-medium text-foreground">
          Email address
        </label>
        <div className="mt-1">
          <input
            id="email" name="email" type="email" autoComplete="email" required
            value={email} onChange={(e) => setEmail(e.target.value)}
            className="block w-full appearance-none rounded-lg border border-border bg-background/50 px-3 py-2 text-foreground placeholder-muted-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 sm:text-sm transition-all"
          />
        </div>
      </div>

      <div>
        <label htmlFor="password" className="block text-sm font-medium text-foreground">
          Password
        </label>
        <div className="mt-1">
          <input
            id="password" name="password" type="password" autoComplete="current-password" required
            value={password} onChange={(e) => setPassword(e.target.value)}
            className="block w-full appearance-none rounded-lg border border-border bg-background/50 px-3 py-2 text-foreground placeholder-muted-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 sm:text-sm transition-all"
          />
        </div>
      </div>

      <div className="flex items-center gap-3">
        <input
          id="staySignedIn"
          name="staySignedIn"
          type="checkbox"
          checked={staySignedIn}
          onChange={(e) => setStaySignedIn(e.target.checked)}
          className="h-4 w-4 rounded border-border bg-white text-primary focus:ring-2 focus:ring-primary/20 focus:ring-offset-0"
        />
        <label htmlFor="staySignedIn" className="text-sm text-muted-foreground">
          Stay signed in
        </label>
      </div>

      {requiresTwoFactor && (
        <div>
          <label htmlFor="totp" className="block text-sm font-medium text-foreground">
            Authenticator Code
          </label>
          <div className="mt-1">
            <input
              id="totp" name="totp" type="text" inputMode="numeric" maxLength={6}
              placeholder="6-digit code" autoComplete="one-time-code" required
              value={totpToken} onChange={(e) => setTotpToken(e.target.value.replace(/\D/g, ""))}
              className="block w-full appearance-none rounded-lg border border-border bg-background/50 px-3 py-2 text-foreground placeholder-muted-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 sm:text-sm transition-all tracking-widest text-center"
            />
          </div>
        </div>
      )}

      <div>
        <button type="submit" className="btn-primary w-full py-3">
          {requiresTwoFactor ? "Verify" : "Sign in"}
        </button>
      </div>

      <div className="text-center">
        <Link href="/forgot-password" className="text-sm text-muted-foreground hover:text-primary transition-colors">
          Forgot your password?
        </Link>
      </div>

      {status && (
        <div className={`mt-4 rounded-lg p-4 ${isError ? "bg-red-500/10 border border-red-500/20" : "bg-primary/10 border border-primary/20"}`}>
          <p className={`text-sm font-medium text-center ${isError ? "text-red-600 dark:text-red-400" : "text-foreground"}`}>{status}</p>
        </div>
      )}
    </form>
  );
}

export default function LoginPage() {
  const schema = [
    {
      "@context": "https://schema.org",
      "@type": "WebPage",
      name: "Aarthalabs Login",
      description: "Sign in to Aarthalabs to access your audit-ready ledger.",
      url: `${siteInfo.url}/login`,
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: defaultFaqs.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: { "@type": "Answer", text: item.answer },
      })),
    },
  ];

  return (
    <div className="page-soft-bg min-h-screen font-sans text-foreground flex flex-col relative overflow-hidden">
      <Background />
      <SiteHeader />
      <div className="relative z-10 flex flex-1 flex-col justify-center pt-24 pb-16 sm:px-6 lg:px-8">
        <div className="sm:mx-auto sm:w-full sm:max-w-md">
          <div className="flex justify-center">
            <div
              className="h-12 w-12 rounded-full flex items-center justify-center text-white font-bold text-xl shadow-[0_12px_30px_var(--gradient-glow)]"
              style={{ background: "linear-gradient(to right, var(--gradient-start), var(--gradient-mid), var(--gradient-end))" }}
            >
              A
            </div>
          </div>
          <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-foreground">
            Sign In
          </h2>
          <p className="mt-2 text-center text-sm text-muted-foreground">
            <Link href="/register" className="font-medium text-primary hover:text-primary/80 transition-colors">
              Start your 14-day free trial
            </Link>
          </p>
        </div>
        <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="rounded-3xl border border-border/60 bg-gradient-to-b from-background/90 via-background to-background/60 py-8 px-4 shadow-glass backdrop-blur-sm sm:px-10">
            <Suspense fallback={null}>
              <LoginForm />
            </Suspense>
          </div>
        </div>
      </div>
      <div className="relative z-10">
        <SiteFooter />
      </div>
      <PageSchema schema={schema} />
    </div>
  );
}
