"use client";

import { useState } from "react";
import { login, signup } from "@/lib/api";
import { useLocale } from "@/i18n/LocaleProvider";
import { Button, Field } from "@/components/ui";

type Mode = "signin" | "signup";

/**
 * Investor sign-in / self-registration, the split-screen layout from the prototype: form on one
 * side, brand panel on the other, dark-first.
 *
 * Sign-up creates a PENDING account; investor-service will not issue a token until a super-admin
 * approves it, so after registering we show a "pending approval" note rather than logging in.
 */
export function LoginScreen({
  onSignedIn,
}: {
  onSignedIn: (investorId: string, token: string) => void;
}) {
  const { t, locale } = useLocale();
  const [mode, setMode] = useState<Mode>("signin");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState(false);
  const [busy, setBusy] = useState(false);

  const switchMode = (m: Mode) => {
    setMode(m);
    setError(null);
    setDone(false);
  };

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      if (mode === "signin") {
        const session = await login(email, password);
        onSignedIn(session.id, session.accessToken);
      } else {
        await signup({ name, email, phone, password });
        setDone(true);
      }
    } catch (err) {
      setError(err instanceof Error && err.message ? err.message : t("login.failed"));
    } finally {
      setBusy(false);
    }
  };

  const isSignup = mode === "signup";

  return (
    <div className="grid min-h-screen bg-background lg:grid-cols-2">
      {/* Form side */}
      <div className="flex items-center justify-center p-6">
        <form onSubmit={submit} className="w-full max-w-sm">
          <h1 className="text-2xl font-bold tracking-tight">
            {isSignup ? t("signup.title") : t("login.title")}
          </h1>
          <p className="mt-2 text-sm text-muted">
            {isSignup ? t("signup.subtitle") : t("login.subtitle")}
          </p>

          {done ? (
            <div className="tint tone-success mt-8 rounded-card border p-4 text-sm">
              {t("signup.pending")}
              <button
                type="button"
                onClick={() => switchMode("signin")}
                className="mt-3 block font-semibold text-brand underline"
              >
                {t("signup.backToSignin")}
              </button>
            </div>
          ) : (
            <>
              <div className="mt-8 space-y-4">
                {isSignup && (
                  <Field
                    label={t("signup.name")}
                    required
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder={t("signup.namePlaceholder")}
                  />
                )}
                <Field
                  label={t("login.email")}
                  type="email"
                  autoComplete="username"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com"
                />
                {isSignup && (
                  <Field
                    label={t("signup.phone")}
                    type="tel"
                    required
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="+9665XXXXXXXX"
                  />
                )}
                <Field
                  label={t("login.password")}
                  type="password"
                  autoComplete={isSignup ? "new-password" : "current-password"}
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••••"
                />
                {isSignup && <p className="text-xs text-muted">{t("signup.passwordHint")}</p>}
              </div>

              {error && (
                <div className="tint tone-danger mt-4 rounded-card border p-3 text-sm">
                  {error}
                </div>
              )}

              <Button
                variant="primary"
                type="submit"
                disabled={busy || !email || !password || (isSignup && (!name || !phone))}
                className="mt-6 w-full"
              >
                {busy
                  ? t("common.loading")
                  : isSignup
                    ? t("signup.submit")
                    : t("login.submit")}
              </Button>

              <p className="mt-4 text-center text-sm text-muted">
                {isSignup ? t("signup.haveAccount") : t("signup.noAccount")}{" "}
                <button
                  type="button"
                  onClick={() => switchMode(isSignup ? "signin" : "signup")}
                  className="font-semibold text-brand underline"
                >
                  {isSignup ? t("login.submit") : t("signup.submit")}
                </button>
              </p>
            </>
          )}
        </form>
      </div>

      {/* Brand side. Hidden on small screens, it's atmosphere, not information. */}
      <div className="relative hidden overflow-hidden bg-canvas lg:block">
        <div
          aria-hidden
          className="absolute inset-0 opacity-40"
          style={{
            background:
              "radial-gradient(120% 90% at 80% 10%, rgba(252,215,4,0.22), transparent 60%)",
          }}
        />
        <div className="relative flex h-full flex-col justify-center gap-6 p-14">
          <img src="/beeb-logo.png" alt="" className="h-16 w-16 rounded-full" />
          <h2 className="max-w-md text-4xl font-bold leading-tight">{t("login.panelTitle")}</h2>
          <p className="max-w-sm text-muted">{t("login.panelBody")}</p>
        </div>
      </div>

      <p className="pointer-events-none absolute bottom-4 w-full text-center text-xs text-muted-dim">
        BEEBBEEB © {new Date().getFullYear()} · {locale.toUpperCase()}
      </p>
    </div>
  );
}
