import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Filter,
  Inbox,
  ListVideo,
  Lock,
  PlayCircle,
  Tags,
  type LucideIcon,
} from "lucide-react";
import { api } from "../lib/api";
import { HttpError } from "../lib/api";
import { setLanguage, type LangCode } from "../i18n";
import LanguageSwitcher from "./LanguageSwitcher";

const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const PASSWORD_MIN = 10;

type Mode = "signin" | "register" | "forgot" | "reset";

// Public landing + authentication. One scrollable page: a hero with the auth card (email+
// password, Google, explicit demo) over a short marketing pitch with feature cards. Shown
// whenever the user isn't signed in (see App.tsx). The auth forms talk to /auth/* (see the
// backend); errors are surfaced inline (the api calls use the quiet flag).
export default function Welcome() {
  const { t, i18n } = useTranslation();
  return (
    <div className="min-h-screen bg-bg text-fg overflow-y-auto">
      <header className="flex items-center justify-between px-5 sm:px-8 py-4">
        <div className="text-xl font-bold tracking-tight">
          Sift<span className="text-accent">lode</span>
        </div>
        <LanguageSwitcher value={i18n.language as LangCode} onChange={setLanguage} />
      </header>

      <main className="max-w-6xl mx-auto px-5 sm:px-8 pb-16">
        {/* Hero: pitch + auth card */}
        <section className="grid lg:grid-cols-2 gap-10 items-center py-8 lg:py-14">
          <div className="max-w-xl">
            <h1 className="text-3xl sm:text-4xl font-bold tracking-tight leading-tight">
              {t("welcome.hero.title")}
            </h1>
            <p className="text-muted mt-4 text-lg leading-relaxed">{t("welcome.hero.subtitle")}</p>
            <p className="text-sm text-muted mt-4">{t("welcome.hero.trust")}</p>
          </div>
          <AuthCard />
        </section>

        {/* App preview */}
        <Preview src="/welcome/feed.png" label={t("welcome.preview.feed")} className="aspect-video" />

        {/* Features */}
        <section className="mt-14">
          <h2 className="text-2xl font-semibold text-center">{t("welcome.features.heading")}</h2>
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-8">
            {FEATURES.map((f) => (
              <FeatureCard key={f.key} icon={f.icon} k={f.key} />
            ))}
          </div>
        </section>

        {/* Secondary showcase */}
        <section className="grid sm:grid-cols-2 gap-4 mt-12">
          <Preview src="/welcome/channels.png" label={t("welcome.preview.channels")} className="aspect-[4/3]" />
          <Preview src="/welcome/playlists.png" label={t("welcome.preview.playlists")} className="aspect-[4/3]" />
        </section>
      </main>

      <footer className="border-t border-border py-6 text-center text-xs text-muted flex flex-col sm:flex-row gap-3 justify-center items-center">
        <span>
          Sift<span className="text-accent">lode</span>
        </span>
        <span className="hidden sm:inline">·</span>
        <a href="/privacy" className="hover:text-fg transition">
          {t("common.privacyPolicy")}
        </a>
        <a href="/terms" className="hover:text-fg transition">
          {t("common.termsOfService")}
        </a>
      </footer>
    </div>
  );
}

const FEATURES: { key: string; icon: LucideIcon }[] = [
  { key: "readable", icon: Filter },
  { key: "neverMiss", icon: Inbox },
  { key: "playlists", icon: ListVideo },
  { key: "player", icon: PlayCircle },
  { key: "channels", icon: Tags },
  { key: "private", icon: Lock },
];

function FeatureCard({ icon: Icon, k }: { icon: LucideIcon; k: string }) {
  const { t } = useTranslation();
  return (
    <div className="glass-card rounded-2xl p-5">
      <div className="w-10 h-10 rounded-xl bg-accent/15 text-accent grid place-items-center mb-3">
        <Icon className="w-5 h-5" />
      </div>
      <h3 className="font-semibold">{t(`welcome.features.${k}.title`)}</h3>
      <p className="text-sm text-muted leading-relaxed mt-1">{t(`welcome.features.${k}.body`)}</p>
    </div>
  );
}

// Image with a graceful fallback: if the file isn't present yet, show a tasteful placeholder
// frame instead of a broken image (the demo screenshots drop into frontend/public/welcome/).
function Preview({ src, label, className }: { src: string; label: string; className?: string }) {
  const [failed, setFailed] = useState(false);
  return (
    <div className={`glass-card rounded-2xl overflow-hidden ${className ?? ""}`}>
      {failed ? (
        <div className="w-full h-full grid place-items-center bg-gradient-to-br from-accent/10 to-card text-muted text-sm p-6 text-center">
          {label}
        </div>
      ) : (
        <img
          src={src}
          alt={label}
          loading="lazy"
          onError={() => setFailed(true)}
          className="w-full h-full object-cover object-top"
        />
      )}
    </div>
  );
}

function AuthCard() {
  const { t } = useTranslation();
  const params = new URLSearchParams(window.location.search);
  const resetToken = params.get("reset");
  const bounced = params.get("access"); // Google denied → "requested" | "denied"
  const verify = params.get("verify"); // "ok" | "invalid"

  const [mode, setMode] = useState<Mode>(resetToken ? "reset" : "signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState<string>(""); // success/info message replacing the form

  // Explicit demo entry (replaces the old hidden probe): a labelled email field, still gated
  // by the demo whitelist server-side.
  const [showDemo, setShowDemo] = useState(false);
  const [demoEmail, setDemoEmail] = useState("");
  const [demoBusy, setDemoBusy] = useState(false);
  const [demoError, setDemoError] = useState("");

  const reset = () => {
    setError("");
    setDone("");
  };

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    reset();
    const mail = email.trim().toLowerCase();
    if ((mode === "signin" || mode === "register" || mode === "forgot") && !EMAIL_RE.test(mail)) {
      setError(t("welcome.auth.invalidEmail"));
      return;
    }
    if ((mode === "register" || mode === "reset") && password.length < PASSWORD_MIN) {
      setError(t("welcome.auth.weakPassword", { min: PASSWORD_MIN }));
      return;
    }
    setBusy(true);
    try {
      if (mode === "signin") {
        await api.passwordLogin(mail, password);
        window.location.reload();
        return;
      }
      if (mode === "register") {
        await api.register(mail, password);
        setDone(t("welcome.auth.registerDone"));
      } else if (mode === "forgot") {
        await api.requestPasswordReset(mail);
        setDone(t("welcome.auth.forgotDone"));
      } else if (mode === "reset") {
        await api.confirmPasswordReset(resetToken ?? "", password);
        setDone(t("welcome.auth.resetDone"));
      }
    } catch (err) {
      setError(err instanceof HttpError && err.detail ? err.detail : t("welcome.auth.genericError"));
    } finally {
      setBusy(false);
    }
  }

  async function onDemo(e: React.FormEvent) {
    e.preventDefault();
    setDemoError("");
    const mail = demoEmail.trim().toLowerCase();
    if (!EMAIL_RE.test(mail)) {
      setDemoError(t("welcome.auth.invalidEmail"));
      return;
    }
    setDemoBusy(true);
    try {
      const r = await api.demoLogin(mail);
      if (r.authenticated) window.location.reload();
      else setDemoError(t("welcome.auth.demoDenied"));
    } catch {
      setDemoError(t("welcome.auth.demoDenied"));
    } finally {
      setDemoBusy(false);
    }
  }

  const inputCls =
    "w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none focus:border-accent";
  const titleKey =
    mode === "register"
      ? "welcome.auth.createTitle"
      : mode === "forgot"
        ? "welcome.auth.forgotTitle"
        : mode === "reset"
          ? "welcome.auth.resetTitle"
          : "welcome.auth.signinTitle";

  return (
    <div className="glass rounded-2xl p-6 sm:p-7 w-full max-w-md lg:justify-self-end">
      <h2 className="text-lg font-semibold mb-1">{t(titleKey)}</h2>

      {/* One-time status banners from a redirect (Google-denied, email verification). */}
      {verify === "ok" && <Banner tone="ok">{t("welcome.auth.verifyOk")}</Banner>}
      {verify === "invalid" && <Banner tone="warn">{t("welcome.auth.verifyInvalid")}</Banner>}
      {bounced === "requested" && <Banner tone="ok">{t("welcome.auth.accessRequested")}</Banner>}
      {bounced === "denied" && <Banner tone="warn">{t("welcome.auth.accessDenied")}</Banner>}

      {done ? (
        <div className="mt-3">
          <p className="text-sm text-fg/80 leading-relaxed">{done}</p>
          <button
            onClick={() => {
              setMode("signin");
              setDone("");
            }}
            className="mt-4 text-sm text-accent hover:underline"
          >
            {t("welcome.auth.backToSignin")}
          </button>
        </div>
      ) : (
        <>
          <form onSubmit={onSubmit} className="flex flex-col gap-3 mt-3">
            {mode !== "reset" && (
              <input
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={t("welcome.auth.email")}
                className={inputCls}
              />
            )}
            {mode !== "forgot" && (
              <input
                type="password"
                autoComplete={mode === "signin" ? "current-password" : "new-password"}
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={
                  mode === "reset" || mode === "register"
                    ? t("welcome.auth.newPassword", { min: PASSWORD_MIN })
                    : t("welcome.auth.password")
                }
                className={inputCls}
              />
            )}
            {error && <p className="text-xs text-red-400">{error}</p>}
            <button
              type="submit"
              disabled={busy}
              className="px-4 py-2.5 rounded-xl font-semibold bg-accent text-accent-fg hover:opacity-90 disabled:opacity-50 transition"
            >
              {busy
                ? t("welcome.auth.working")
                : t(
                    mode === "register"
                      ? "welcome.auth.createButton"
                      : mode === "forgot"
                        ? "welcome.auth.forgotButton"
                        : mode === "reset"
                          ? "welcome.auth.resetButton"
                          : "welcome.auth.signinButton"
                  )}
            </button>
          </form>

          {/* Mode switches */}
          <div className="flex items-center justify-between mt-3 text-xs">
            {mode === "signin" ? (
              <>
                <button onClick={() => { reset(); setMode("register"); }} className="text-accent hover:underline">
                  {t("welcome.auth.createLink")}
                </button>
                <button onClick={() => { reset(); setMode("forgot"); }} className="text-muted hover:text-fg">
                  {t("welcome.auth.forgotLink")}
                </button>
              </>
            ) : (
              <button onClick={() => { reset(); setMode("signin"); }} className="text-accent hover:underline">
                {t("welcome.auth.backToSignin")}
              </button>
            )}
          </div>

          {mode === "signin" && (
            <>
              <div className="flex items-center gap-3 my-4 text-[11px] uppercase tracking-wide text-muted">
                <span className="h-px flex-1 bg-border" />
                {t("welcome.auth.or")}
                <span className="h-px flex-1 bg-border" />
              </div>
              <a
                href="/auth/login"
                className="block text-center px-4 py-2.5 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent transition"
              >
                {t("welcome.auth.google")}
              </a>
              {!showDemo ? (
                <button
                  onClick={() => setShowDemo(true)}
                  className="w-full mt-2 px-4 py-2.5 rounded-xl text-sm bg-card border border-border hover:border-accent transition"
                >
                  {t("welcome.auth.tryDemo")}
                </button>
              ) : (
                <form onSubmit={onDemo} className="mt-2 flex flex-col gap-2">
                  <p className="text-[11px] text-muted">{t("welcome.auth.demoHint")}</p>
                  <div className="flex gap-2">
                    <input
                      type="email"
                      value={demoEmail}
                      onChange={(e) => setDemoEmail(e.target.value)}
                      placeholder={t("welcome.auth.demoEmail")}
                      className={inputCls}
                    />
                    <button
                      type="submit"
                      disabled={demoBusy}
                      className="shrink-0 px-3 py-2.5 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent disabled:opacity-50 transition"
                    >
                      {demoBusy ? t("welcome.auth.working") : t("welcome.auth.demoEnter")}
                    </button>
                  </div>
                  {demoError && <p className="text-xs text-red-400">{demoError}</p>}
                </form>
              )}
            </>
          )}
        </>
      )}
    </div>
  );
}

function Banner({ tone, children }: { tone: "ok" | "warn"; children: React.ReactNode }) {
  const cls = tone === "ok" ? "bg-accent/15 text-fg" : "bg-amber-500/15 text-fg";
  return <div className={`rounded-xl px-3 py-2 text-xs leading-relaxed mt-3 ${cls}`}>{children}</div>;
}
