import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState, type FormEvent } from "react";
import {
  AuthShell,
  AuthToast,
  PassField,
  PhoneField,
  TextField,
  type AuthToastData,
} from "@/components/lotus/AuthShell";
import { apiCall, setUserSession } from "@/lib/api";
import { setBalance } from "@/lib/wallet";

export const Route = createFileRoute("/login")({
  head: () => ({
    meta: [
      { title: "Log in – Lotus365" },
      { name: "description", content: "Log in to Lotus365 with your phone number or email." },
    ],
  }),
  component: LoginPage,
});

function LoginPage() {
  const [tab, setTab] = useState<"phone" | "email">("phone");
  const [id, setId] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [toast, setToast] = useState<AuthToastData | null>(null);
  const navigate = useNavigate();

  const submit = async (event: FormEvent) => {
    event.preventDefault();
    const validId = tab === "phone" ? id.length === 10 : /.+@.+\..+/.test(id);
    if (!validId || password.length < 6) {
      setToast({
        type: "error",
        message: tab === "phone"
          ? "Enter a 10-digit mobile number and password (minimum 6 characters)."
          : "Enter a valid email and password (minimum 6 characters).",
      });
      return;
    }
    setLoading(true);
    try {
      const res = await apiCall("login", { identifier: id, password });
      if (!res.ok) {
        setToast({ type: "error", message: res.error || "Invalid credentials" });
      } else {
        setUserSession(res.token, res.user);
        setBalance(Number(res.user.wallet_balance || 0));
        navigate({ to: "/" });
      }
    } catch {
      setToast({ type: "error", message: "Server connection error." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthShell active="login" title="LOG IN">
      <div className="flex rounded-xl border border-auth-border bg-auth-panel p-1">
        {(["phone", "email"] as const).map((mode) => (
          <button
            key={mode}
            type="button"
            aria-pressed={tab === mode}
            onClick={() => { setTab(mode); setId(""); setToast(null); }}
            className={`flex-1 rounded-lg py-2.5 text-xs font-bold capitalize transition md:text-sm ${tab === mode ? "bg-auth-accent text-auth-button-text" : "text-auth-label hover:text-foreground"}`}
          >
            {mode}
          </button>
        ))}
      </div>
      <form onSubmit={submit} className="space-y-3.5">
        {tab === "phone" ? (
          <PhoneField value={id} onChange={(value) => { setId(value); setToast(null); }} />
        ) : (
          <TextField
            label="Email Address"
            type="email"
            autoComplete="email"
            value={id}
            onChange={(value) => { setId(value.trim()); setToast(null); }}
            placeholder="name@example.com"
          />
        )}
        <PassField value={password} onChange={(value) => { setPassword(value); setToast(null); }} />
        <div className="flex justify-end pt-0.5">
          <Link to="/forgot-password" className="text-xs font-semibold text-auth-accent hover:underline">
            Forgot your password?
          </Link>
        </div>
        <button disabled={loading} type="submit" className="mt-2 w-full rounded-xl bg-auth-accent py-3.5 text-sm font-black uppercase tracking-wider text-auth-button-text shadow-lg transition active:scale-[0.99] disabled:opacity-50">
          {loading ? "SIGNING IN..." : "LOG IN"}
        </button>
        <p className="pt-3 text-center text-xs text-auth-label">
          Don&apos;t have an account?
          <Link to="/register" className="ml-1 font-bold text-auth-accent hover:underline">Join Now</Link>
        </p>
      </form>
      <AuthToast toast={toast} onClose={() => setToast(null)} />
    </AuthShell>
  );
}
