"use client";

import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { useAuthStore } from "@/store/authStore";
import { useTenantStore } from "@/store/tenantStore";
import { login, getCurrentUser } from "@/services/auth";
import { usePermissionStore } from "@/store/permissionStore";
import { useApiStore } from "@/store/uiStore";
import { t } from "@/lib/locale";
import { useLocaleStore } from "@/store/uiStore";

export default function LoginPage() {
  const router = useRouter();
  const setAuth = useAuthStore((s) => s.setAuthFromLogin);
  const setPermissions = usePermissionStore((s) => s.setProfile);
  const setProfile = useAuthStore((s) => s.setProfile);
  const addToast = useApiStore((s) => s.addToast);
  const tenantId = useTenantStore((s) => s.tenantId);
  const setTenant = useTenantStore((s) => s.setTenantId);
  const availableTenants = useTenantStore((s) => s.availableTenants);
  const locale = useLocaleStore((s) => s.locale);
  const hasToken = useAuthStore((s) => !!s.accessToken);

  useEffect(() => {
    useAuthStore.getState().hydrate();
    if (hasToken) router.replace("/dashboard");
  }, [hasToken, router]);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [selectedTenant, setSelectedTenant] = useState(tenantId);
  const [isLoading, setIsLoading] = useState(false);

  const onSubmit = async (ev: FormEvent) => {
    ev.preventDefault();
    if (!selectedTenant) {
      addToast("Tenant is required", "error");
      return;
    }
    if (!username || !password) {
      addToast("Username and password are required", "error");
      return;
    }
    setIsLoading(true);
    try {
      const authRes = await login({ username, password }, selectedTenant);
      setAuth({
        tokenType: authRes.tokenType,
        accessToken: authRes.accessToken,
        refreshToken: authRes.refreshToken,
        expiresInSeconds: authRes.expiresInSeconds
      });
      setTenant(selectedTenant);
      const me = await getCurrentUser();
      setProfile(me.data);
      setPermissions(me.data.roles, me.data.permissions);
      addToast(t("loginSuccess", locale), "success");
      router.replace("/dashboard");
    } catch (error: unknown) {
      const message =
        (error as { message?: string } | undefined)?.message ||
        t("unknownError", locale);
      addToast(message, "error");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <main className="min-vh-100 d-flex align-items-center justify-content-center">
      <section className="card p-4 w-100" style={{ maxWidth: 420 }}>
        <div className="mb-3 text-center">
          <h1 className="h3">UTMS Admin</h1>
          <p className="text-muted">Sign in with tenant context</p>
        </div>
        <form className="vstack gap-3" onSubmit={onSubmit}>
          <select
            className="form-select"
            value={selectedTenant}
            onChange={(e) => setSelectedTenant(e.target.value)}
          >
            <option value="">Select tenant</option>
            {availableTenants.map((tenant) => (
              <option key={tenant} value={tenant}>
                {tenant}
              </option>
            ))}
          </select>
          <input
            className="form-control"
            placeholder="Username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
          <input
            className="form-control"
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <button className="btn btn-primary" type="submit" disabled={isLoading}>
            {isLoading ? "Signing in..." : "Sign in"}
          </button>
        </form>
      </section>
    </main>
  );
}
