"use client";

import { AppstoreOutlined, LockOutlined, UserOutlined } from "@ant-design/icons";
import { Alert, Button, Card, Form, Input, Spin, Typography } from "antd";
import { loginRequiresTwoFactor } from "@domainops/shared-types";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { TwoFactorEnrollForm } from "@/components/features/TwoFactorEnrollForm";
import { ApiError } from "@/lib/api/client";
import { useAuth } from "@/lib/auth/AuthProvider";
import { useSiteBranding } from "@/lib/branding/BrandingProvider";
import { useThemeMode, useThemeSettings } from "@/lib/theme/ThemeProvider";

interface LoginFormValues {
  username: string;
  password: string;
}

interface CodeFormValues {
  code: string;
}

export default function LoginPage() {
  const { user, isLoading: isAuthLoading, login, completeTwoFactorChallenge } = useAuth();
  const branding = useSiteBranding();
  const theme = useThemeSettings();
  const { isDark } = useThemeMode();
  const primaryColor = isDark ? theme.dark_primary_color : theme.light_primary_color;
  const loginBackgroundColor = isDark ? theme.dark_login_background_color : theme.light_login_background_color;
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [awaitingCode, setAwaitingCode] = useState(false);
  const [pendingEnrollment, setPendingEnrollment] = useState(false);
  const [logoFailed, setLogoFailed] = useState(false);

  useEffect(() => {
    // The reliable check - proxy.ts can only see cookie presence, which a
    // guest session also has, so it can't safely make this call itself.
    // Held off while pendingEnrollment is true - global_settings.require_2fa
    // is enforced right here at login, not as an ongoing mid-session lock
    // (see docs/ARCHITECTURE.md §9), so a user without a device yet doesn't
    // get redirected into the dashboard until they've set one up.
    if (!isAuthLoading && user && !pendingEnrollment) {
      router.replace("/");
    }
  }, [isAuthLoading, user, pendingEnrollment, router]);

  if (pendingEnrollment) {
    return (
      <div className="flex flex-1 min-h-screen items-center justify-center p-6 auth-page auth-page--enrollment">
        <Card style={{ width: 400 }} styles={{ body: { padding: 32 } }} className="auth-card dms_login_enrollment_card">
          <Typography.Title level={3} style={{ marginBottom: 4 }} className="auth-card__title">
            Set up two-factor authentication
          </Typography.Title>
          <Typography.Text type="secondary" className="auth-card__subtitle">
            Your administrator requires 2FA for every account before you can continue.
          </Typography.Text>
          <div style={{ marginTop: 24 }}>
            <TwoFactorEnrollForm autoStart onEnrolled={() => router.push("/")} />
          </div>
        </Card>
      </div>
    );
  }

  if (isAuthLoading || user) {
    return (
      <div className="flex flex-1 min-h-screen items-center justify-center auth-page__loading">
        <Spin size="large" />
      </div>
    );
  }

  async function handleSubmit(values: LoginFormValues) {
    setError(null);
    setIsSubmitting(true);
    try {
      const result = await login(values.username, values.password);
      if (loginRequiresTwoFactor(result)) {
        setAwaitingCode(true);
        return;
      }
      if (result.two_factor_setup_required) {
        setPendingEnrollment(true);
        return;
      }
      router.push("/");
    } catch (err) {
      setError(
        err instanceof ApiError
          ? err.message
          : "Couldn't reach the server. Please try again.",
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  async function handleCodeSubmit(values: CodeFormValues) {
    setError(null);
    setIsSubmitting(true);
    try {
      const loggedInUser = await completeTwoFactorChallenge(values.code);
      if (loggedInUser.two_factor_setup_required) {
        setPendingEnrollment(true);
        return;
      }
      router.push("/");
    } catch (err) {
      setError(
        err instanceof ApiError
          ? err.message
          : "Couldn't reach the server. Please try again.",
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  const form = (
    <Card
      style={{ width: 360 }}
      styles={{ body: { padding: 32 } }}
      className="auth-card dms_login_card"
    >
      {branding.site_logo && !logoFailed ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={branding.site_logo}
          alt={branding.site_title}
          style={{ height: 40, marginBottom: 12 }}
          className="auth-card__logo dms_login_logo"
          onError={() => setLogoFailed(true)}
        />
      ) : (
        <span className="dms__brand-logo auth-card__logo dms_login_logo" style={{ marginBottom: 12 }}>
          <AppstoreOutlined style={{ fontSize: 18 }} />
        </span>
      )}
      <Typography.Title level={3} style={{ marginBottom: 4 }} className="auth-card__title">
        {awaitingCode ? "Verify it's you" : "Sign in"}
      </Typography.Title>
      <Typography.Text type="secondary" className="auth-card__subtitle">
        {awaitingCode ? "Enter the 6-digit code from your authenticator app." : `${branding.site_title} console`}
      </Typography.Text>

      {awaitingCode ? (
        <Form<CodeFormValues>
          layout="vertical"
          onFinish={handleCodeSubmit}
          style={{ marginTop: 24 }}
          disabled={isSubmitting}
          className="auth-form auth-form--2fa dms_login_2fa_form"
        >
          {error && (
            <Form.Item className="auth-form__error dms_login_2fa_error_field">
              <Alert type="error" title={error} showIcon />
            </Form.Item>
          )}

          <Form.Item
            name="code"
            label="Authentication code"
            rules={[{ required: true, len: 6, message: "Enter the 6-digit code" }]}
            className="auth-form__code dms_login_2fa_code_field"
          >
            <Input.OTP length={6} autoFocus className="dms_login_2fa_code_otp" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }} className="auth-form__submit dms_login_2fa_submit_field">
            <Button type="primary" htmlType="submit" block loading={isSubmitting} className="dms_login_2fa_verify_btn">
              Verify
            </Button>
          </Form.Item>
        </Form>
      ) : (
        <Form<LoginFormValues>
          layout="vertical"
          onFinish={handleSubmit}
          style={{ marginTop: 24 }}
          disabled={isSubmitting}
          className="auth-form dms_login_form"
        >
          {error && (
            <Form.Item className="auth-form__error dms_login_error_field">
              <Alert type="error" title={error} showIcon />
            </Form.Item>
          )}

          <Form.Item
            name="username"
            label="Username"
            rules={[{ required: true, message: "Enter your username" }]}
            className="auth-form__username dms_login_username_field"
          >
            <Input prefix={<UserOutlined />} autoComplete="username" autoFocus />
          </Form.Item>

          <Form.Item
            name="password"
            label="Password"
            rules={[{ required: true, message: "Enter your password" }]}
            className="auth-form__password dms_login_password_field"
          >
            <Input.Password prefix={<LockOutlined />} autoComplete="current-password" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }} className="auth-form__submit dms_login_submit_field">
            <Button type="primary" htmlType="submit" block loading={isSubmitting} className="dms_login_submit_btn">
              Sign in
            </Button>
          </Form.Item>
        </Form>
      )}
    </Card>
  );

  if (theme.login_layout === "split-image") {
    return (
      <div className="flex flex-1 min-h-screen auth-page auth-page--split-image">
        <div
          className="hidden md:block md:w-1/2 auth-page__image"
          style={{
            backgroundColor: loginBackgroundColor ?? primaryColor,
            backgroundImage: `url(${theme.login_image_url || "https://picsum.photos/1200/1600"})`,
            backgroundSize: "cover",
            backgroundPosition: "center",
          }}
        />
        <div className="flex flex-1 items-center justify-center p-6 auth-page__form-pane">{form}</div>
      </div>
    );
  }

  if (theme.login_layout === "minimal-fullscreen") {
    // Edge-to-edge, no floating card chrome - deliberately distinct from
    // centered-card (which keeps padding and the Card's shadow/border) so
    // the two options actually look different from each other.
    return (
      <div
        className="flex flex-1 min-h-screen items-center justify-center auth-page auth-page--minimal-fullscreen"
        style={{ background: loginBackgroundColor ?? undefined }}
      >
        <div className="w-full max-w-sm px-6 auth-page__minimal-form">{form}</div>
      </div>
    );
  }

  // centered-card (default)
  return (
    <div
      className="flex flex-1 min-h-screen items-center justify-center p-6 auth-page auth-page--centered-card"
      style={{ background: loginBackgroundColor ?? undefined }}
    >
      {form}
    </div>
  );
}
