"use client";

import type * as React from "react";
import Image from "next/image";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useAuthSettings } from "./auth-settings-context";
import { authClient } from "@/lib/auth-client";

type AuthShellProps = {
  title: string;
  subtitle: string;
  children: React.ReactNode;
  reverse?: boolean;
};

function GithubIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0 1 12 6.844a9.59 9.59 0 0 1 2.504.337c1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.02 10.02 0 0 0 22 12.017C22 6.484 17.522 2 12 2z" />
    </svg>
  );
}

function DiscordIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057c.003.02.015.04.03.052a19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
    </svg>
  );
}

const PROVIDER_META: Record<string, { label: string; icon: React.FC<{ className?: string }>; color: string }> = {
  github: { label: "GitHub", icon: GithubIcon, color: "hover:bg-[#24292e] hover:text-white hover:border-[#24292e]" },
  discord: { label: "Discord", icon: DiscordIcon, color: "hover:bg-[#5865F2] hover:text-white hover:border-[#5865F2]" },
};

function Logo({ logoUrl, appName, className }: { logoUrl: string | null; appName: string; className?: string }) {
  if (logoUrl) {
    // eslint-disable-next-line @next/next/no-img-element
    return <img src={logoUrl} alt={appName} className={className ?? "h-7 w-auto"} />;
  }
  return (
    <>
      <Image src="/logo-dark.svg" alt="Struxa" width={96} height={28} priority className={`w-auto dark:hidden ${className ?? "h-7"}`} />
      <Image src="/logo-white.svg" alt="Struxa" width={96} height={28} priority className={`hidden w-auto dark:block ${className ?? "h-7"}`} />
    </>
  );
}

export default function AuthShell({ title, subtitle, children, reverse }: AuthShellProps) {
  const t = useTranslations("auth.social");
  const { appName, logoUrl, ogDescription, socialProviders } = useAuthSettings();
  const [loadingProvider, setLoadingProvider] = useState<string | null>(null);

  async function signInWithProvider(provider: string) {
    setLoadingProvider(provider);
    try {
      await authClient.signIn.social({ provider: provider as never, callbackURL: "/" });
    } finally {
      setLoadingProvider(null);
    }
  }

  return (
    <main className="min-h-svh bg-background lg:grid lg:grid-cols-2">
      {/* Branding panel — desktop only */}
      <div className={`relative hidden lg:flex lg:flex-col lg:justify-between bg-muted/40 border-border px-12 py-10 ${reverse ? "lg:order-2 lg:items-end border-l" : "lg:order-1 lg:items-start border-r"}`}>
        <Logo logoUrl={logoUrl} appName={appName} className="h-7" />
        <div className={`flex flex-col gap-2 ${reverse ? "items-end text-right" : "items-start text-left"}`}>
          <p className="text-2xl font-semibold tracking-tight text-foreground">{appName}</p>
          <p className="text-sm text-muted-foreground max-w-xs">
            {ogDescription || t("tagline")}
          </p>
        </div>
        <p className="text-xs text-muted-foreground/60">© {new Date().getFullYear()} Struxa</p>
      </div>

      {/* Form panel */}
      <div className={`flex min-h-svh flex-col items-center justify-center px-4 py-10 lg:min-h-0 lg:py-16 ${reverse ? "lg:order-1" : "lg:order-2"}`}>
        <div className="flex w-full max-w-sm flex-col gap-6">
          {/* Logo shown only on mobile */}
          <div className="flex justify-center lg:hidden">
            <Logo logoUrl={logoUrl} appName={appName} className="h-7" />
          </div>

          <div className="flex flex-col gap-1 text-center">
            <h1 className="text-xl font-semibold tracking-tight text-foreground">{title}</h1>
            <p className="text-sm text-muted-foreground">{subtitle}</p>
          </div>

          <div className="flex flex-col gap-4">
            {socialProviders.length > 0 && (
              <>
                <div className="flex flex-col gap-2">
                  {socialProviders.map((provider) => {
                    const meta = PROVIDER_META[provider];
                    if (!meta) return null;
                    const Icon = meta.icon;
                    return (
                      <button
                        key={provider}
                        type="button"
                        disabled={!!loadingProvider}
                        onClick={() => signInWithProvider(provider)}
                        className={`flex w-full items-center justify-center gap-2 rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors disabled:opacity-50 ${meta.color}`}
                      >
                        <Icon className="h-4 w-4" />
                        {loadingProvider === provider ? t("redirecting") : t("continueWith", { provider: meta.label })}
                      </button>
                    );
                  })}
                </div>
                <div className="relative flex items-center gap-3">
                  <div className="flex-1 border-t border-border" />
                  <span className="text-xs text-muted-foreground">{t("or")}</span>
                  <div className="flex-1 border-t border-border" />
                </div>
              </>
            )}
            {children}
          </div>
        </div>
      </div>
    </main>
  );
}
