"use client";

import { useState } from "react";
import { createClient, isSupabaseConfigured } from "@/lib/supabase/client";
import Link from "next/link";

type Tab = "signin" | "signup" | "magic";

export default function SignInPage() {
  const [tab, setTab] = useState<Tab>("signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [status, setStatus] = useState<"idle" | "loading" | "sent" | "ok" | "error">("idle");
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!email) return;
    setStatus("loading");
    setError(null);
    try {
      const supabase = createClient();

      if (tab === "signin") {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
        window.location.href = "/";
        return;
      }

      if (tab === "signup") {
        if (password.length < 6) throw new Error("Senha precisa ter pelo menos 6 caracteres.");
        const { data, error } = await supabase.auth.signUp({
          email,
          password,
          options: {
            data: { display_name: displayName || email.split("@")[0] },
            emailRedirectTo: `${window.location.origin}/auth/callback`,
          },
        });
        if (error) throw error;
        // If email confirmation is required by Supabase, session is null → ask user to check inbox.
        if (data.session) {
          window.location.href = "/";
          return;
        }
        setStatus("sent");
        return;
      }

      // magic-link path
      const { error } = await supabase.auth.signInWithOtp({
        email,
        options: { emailRedirectTo: `${window.location.origin}/auth/callback` },
      });
      if (error) throw error;
      setStatus("sent");
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
      setStatus("error");
    }
  }

  if (!isSupabaseConfigured()) {
    return (
      <main className="min-h-screen flex items-center justify-center p-8">
        <div className="max-w-md text-center">
          <h1 className="font-mono text-xl text-[#ff3344] mb-3">Auth not configured</h1>
          <p className="text-[#8896aa] text-sm">
            Supabase env vars are missing. See <code>web/.env.local.example</code>.
          </p>
          <Link href="/" className="block mt-4 text-[#7fdbff]">← back home</Link>
        </div>
      </main>
    );
  }

  const tabClass = (t: Tab) =>
    `flex-1 px-3 py-2 font-mono text-[11px] uppercase tracking-widest rounded-t border-b-2 transition ${
      tab === t
        ? "text-[#00ff9c] border-[#00ff9c] bg-[rgba(0,255,156,0.06)]"
        : "text-[#5a6678] border-transparent hover:text-[#8896aa]"
    }`;

  return (
    <main className="min-h-screen flex items-center justify-center p-8">
      <div className="w-full max-w-md bg-[#0a121e] border border-[rgba(0,255,156,0.32)] rounded p-6">
        <div className="font-mono text-[10px] text-[#5a6678] tracking-widest uppercase mb-2">
          // THE DISCLOSURE BUREAU // ACCESS REQUEST
        </div>
        <h1 className="font-mono text-2xl text-[#00ff9c] mb-4">▍ Entrar</h1>

        <div className="flex gap-1 mb-5 border-b border-[rgba(0,255,156,0.12)]">
          <button onClick={() => { setTab("signin"); setStatus("idle"); setError(null); }} className={tabClass("signin")}>entrar</button>
          <button onClick={() => { setTab("signup"); setStatus("idle"); setError(null); }} className={tabClass("signup")}>criar conta</button>
          <button onClick={() => { setTab("magic"); setStatus("idle"); setError(null); }} className={tabClass("magic")}>magic-link</button>
        </div>

        {status === "sent" ? (
          <div className="text-sm">
            <p className="text-[#00ff9c] mb-2">✓ Confira seu email.</p>
            <p className="text-[#8896aa]">
              {tab === "signup"
                ? <>Enviamos um link de confirmação para <span className="font-mono text-[#7fdbff]">{email}</span>. Clique nele para ativar a conta.</>
                : <>Enviamos um magic-link para <span className="font-mono text-[#7fdbff]">{email}</span>. Clique para entrar.</>}
            </p>
            <button
              onClick={() => { setStatus("idle"); setEmail(""); setPassword(""); }}
              className="mt-4 text-xs text-[#7fdbff] hover:text-[#00ff9c]"
            >
              ← usar outro email
            </button>
          </div>
        ) : (
          <form onSubmit={submit} className="space-y-4">
            {tab === "signup" && (
              <div>
                <label htmlFor="name" className="block font-mono text-[10px] text-[#8896aa] uppercase tracking-widest mb-1">
                  Nome (opcional)
                </label>
                <input
                  id="name"
                  type="text"
                  value={displayName}
                  onChange={(e) => setDisplayName(e.target.value)}
                  placeholder="Como devemos te chamar"
                  className="w-full bg-[#060a13] border border-[rgba(0,255,156,0.32)] rounded
                             px-3 py-2 text-sm focus:outline-none focus:border-[#00ff9c]"
                />
              </div>
            )}
            <div>
              <label htmlFor="email" className="block font-mono text-[10px] text-[#8896aa] uppercase tracking-widest mb-1">
                Email
              </label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="agente@example.com"
                required
                autoComplete={tab === "signup" ? "email" : "username"}
                className="w-full bg-[#060a13] border border-[rgba(0,255,156,0.32)] rounded
                           px-3 py-2 text-sm focus:outline-none focus:border-[#00ff9c]"
              />
            </div>
            {tab !== "magic" && (
              <div>
                <label htmlFor="password" className="block font-mono text-[10px] text-[#8896aa] uppercase tracking-widest mb-1">
                  Senha {tab === "signup" && <span className="text-[#5a6678] normal-case tracking-normal">(mín. 6 caracteres)</span>}
                </label>
                <input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  minLength={tab === "signup" ? 6 : 1}
                  autoComplete={tab === "signup" ? "new-password" : "current-password"}
                  className="w-full bg-[#060a13] border border-[rgba(0,255,156,0.32)] rounded
                             px-3 py-2 text-sm focus:outline-none focus:border-[#00ff9c]"
                />
              </div>
            )}
            <button
              type="submit"
              disabled={status === "loading"}
              className="w-full px-4 py-2 bg-[#00ff9c] text-black font-mono uppercase tracking-widest text-sm
                         hover:bg-[#00d4a8] disabled:opacity-40 rounded"
            >
              {status === "loading"
                ? "…"
                : tab === "signin"
                  ? "entrar"
                  : tab === "signup"
                    ? "criar conta"
                    : "enviar magic-link"}
            </button>
            {error && <p className="text-xs text-[#ff3344]">{error}</p>}
            {tab === "magic" && (
              <p className="text-xs text-[#5a6678]">
                Sem senha. Mandamos um link único pro seu email.
              </p>
            )}
          </form>
        )}

        <div className="mt-6 pt-4 border-t border-[rgba(0,255,156,0.10)] flex items-center justify-between text-xs">
          <Link href="/" className="text-[#7fdbff] hover:text-[#00ff9c]">← voltar ao arquivo</Link>
          <span className="text-[#5a6678] font-mono text-[10px]">WhatsApp 🔜</span>
        </div>
      </div>
    </main>
  );
}
