"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Mail } from "lucide-react";
import { formatAuthMethodList } from "@/lib/organization-auth";
import { useAuthPolicyPreview } from "@/hooks/use-auth-policy-preview";
import { AuthPolicyNotice } from "@/components/auth/auth-policy-notice";
import { OAuthButtons } from "@/components/auth/oauth-buttons";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import { Suspense } from "react";

function SignupContent() {
  const [fullName, setFullName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [magicLinkLoading, setMagicLinkLoading] = useState(false);
  const router = useRouter();
  const searchParams = useSearchParams();
  const { preview } = useAuthPolicyPreview(email);
  const feedbackMessage = useMemo(
    () => searchParams.get("message") || searchParams.get("error"),
    [searchParams]
  );

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSuccess(null);
    setLoading(true);

    if (!preview.allowedMethods.includes("password")) {
      setError(`This email must use one of: ${formatAuthMethodList(preview.allowedMethods)}.`);
      setLoading(false);
      return;
    }

    let hasSession = false;
    try {
      const response = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, fullName }),
      });
      const result = (await response.json()) as { error?: string; hasSession?: boolean };

      if (!response.ok) {
        setError(result.error || "Registrierung fehlgeschlagen.");
        setLoading(false);
        return;
      }

      hasSession = !!result.hasSession;
    } catch {
      setError("Der Auth-Dienst ist gerade nicht erreichbar. Prüfe deine Internetverbindung und die Supabase-Konfiguration.");
      setLoading(false);
      return;
    }

    if (hasSession) {
      await fetch("/api/auth/sync-access", { method: "POST" });
      router.push("/");
      router.refresh();
      return;
    }

    setSuccess(`Check ${email.trim()} to confirm your account.`);
    setLoading(false);
  }

  async function handleMagicLinkSignup() {
    if (!email.trim() || magicLinkLoading) return;

    setError(null);
    setSuccess(null);
    setMagicLinkLoading(true);

    if (!preview.allowedMethods.includes("magic_link")) {
      setError(`This email must use one of: ${formatAuthMethodList(preview.allowedMethods)}.`);
      setMagicLinkLoading(false);
      return;
    }

    try {
      const response = await fetch("/api/auth/magic-link", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: email.trim(),
          fullName: fullName.trim(),
          nextPath: "/",
        }),
      });
      const result = (await response.json()) as { error?: string };

      if (!response.ok) {
        setError(result.error || "Magic Link konnte nicht gesendet werden.");
        setMagicLinkLoading(false);
        return;
      }
    } catch {
      setError("Der Auth-Dienst ist gerade nicht erreichbar. Magic Link konnte nicht gesendet werden.");
      setMagicLinkLoading(false);
      return;
    }

    setSuccess(`Magic link sent to ${email.trim()}.`);
    setMagicLinkLoading(false);
  }

  return (
    <>
      <div className="mb-8">
        <h1 className="text-2xl font-bold tracking-tight lg:hidden">
          Mindavio
        </h1>
        <h2 className="mt-2 text-xl font-semibold lg:mt-0 lg:text-2xl">
          Create your account
        </h2>
        <p className="mt-1 text-sm text-muted-foreground">
          Get started with Mindavio for free
        </p>
      </div>

      {feedbackMessage && (
        <p className="mb-4 rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm text-muted-foreground">
          {feedbackMessage}
        </p>
      )}

      <div className="mb-5">
        <OAuthButtons nextPath="/" email={email} policyPreview={preview} />
      </div>

      <div className="mb-5">
        <AuthPolicyNotice preview={preview} />
      </div>

      <div className="relative mb-5">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-border" />
        </div>
        <div className="relative flex justify-center text-xs uppercase tracking-[0.2em] text-muted-foreground">
          <span className="bg-background px-2">Or create an account with email</span>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="name">Full name</Label>
          <Input
            id="name"
            type="text"
            placeholder="John Doe"
            value={fullName}
            onChange={(e) => setFullName(e.target.value)}
            required
            autoComplete="name"
            autoFocus
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <Input
            id="email"
            type="email"
            placeholder="you@example.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoComplete="email"
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="password">Password</Label>
          <Input
            id="password"
            type="password"
            placeholder="Min. 12 characters"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            minLength={12}
            autoComplete="new-password"
          />
        </div>

        {error && (
          <p className="text-sm text-destructive">{error}</p>
        )}
        {success && (
          <p className="text-sm text-emerald-600">{success}</p>
        )}

        <Button type="submit" className="w-full" disabled={loading}>
          {loading ? "Creating account..." : "Create account"}
        </Button>

        <Button
          type="button"
          variant="outline"
          className="w-full"
          onClick={() => void handleMagicLinkSignup()}
          disabled={!email.trim() || magicLinkLoading}
        >
          <Mail className="h-4 w-4" />
          {magicLinkLoading ? "Sending magic link..." : "Use a magic link instead"}
        </Button>
      </form>

      <p className="mt-6 text-center text-sm text-muted-foreground">
        Already have an account?{" "}
        <Link
          href="/login"
          className="font-medium text-foreground hover:underline"
        >
          Sign in
        </Link>
      </p>
    </>
  );
}

export default function SignupPage() {
  return (
    <Suspense>
      <SignupContent />
    </Suspense>
  );
}
