"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 LoginContent() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [magicLinkMessage, setMagicLinkMessage] = 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);
    setMagicLinkMessage(null);
    setLoading(true);

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

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

      if (!response.ok) {
        setError(result.error || "Anmeldung fehlgeschlagen.");
        setLoading(false);
        return;
      }
    } catch {
      setError("Der Auth-Dienst ist gerade nicht erreichbar. Prüfe deine Internetverbindung und die Supabase-Konfiguration.");
      setLoading(false);
      return;
    }

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

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

    setError(null);
    setMagicLinkMessage(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(), 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;
    }

    setMagicLinkMessage(`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">
          Welcome back
        </h2>
        <p className="mt-1 text-sm text-muted-foreground">
          Sign in to your account to continue
        </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 sign in with email</span>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <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"
            autoFocus
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="password">Password</Label>
          <Input
            id="password"
            type="password"
            placeholder="Enter your password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            autoComplete="current-password"
          />
        </div>

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

        <Button type="submit" className="w-full" disabled={loading}>
          {loading ? "Signing in..." : "Sign in"}
        </Button>

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

      <div className="mt-6 space-y-2 text-center text-sm text-muted-foreground">
        <p>
          Forgot your password?{" "}
          <Link
            href="/reset-password"
            className="font-medium text-foreground hover:underline"
          >
            Reset it
          </Link>
        </p>
        <p>
          Don&apos;t have an account?{" "}
          <Link
            href="/signup"
            className="font-medium text-foreground hover:underline"
          >
            Sign up
          </Link>
        </p>
      </div>
    </>
  );
}

export default function LoginPage() {
  return (
    <Suspense>
      <LoginContent />
    </Suspense>
  );
}
