"use client";

import React, { SyntheticEvent, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import Cookies from "js-cookie";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PasswordInput } from "@/components/ui/password-input";
import { PhoneInput } from "@/components/ui/phone-input";
import { Card, CardContent } from "@/components/ui/card";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { applyLoginCookiesOnly } from "@/redux/api/auth-api";
import type { AuthIdentityMode } from "@/lib/auth-identity";
import { useTenantSlugContext } from "../layout";
import logo from "@/assets/icons/logo.svg";

export default function TenantLoginPage() {
  const { tenant, loading, error } = useTenantSlugContext();
  const [mode, setMode] = useState<AuthIdentityMode>("phone");
  const [identity, setIdentity] = useState("");
  const [password, setPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: SyntheticEvent) => {
    e.preventDefault();
    if (!tenant?.clientId) return;
    setSubmitting(true);
    try {
      const body =
        mode === "phone"
          ? { password, phone: identity.trim(), username: identity.trim(), clientId: tenant.clientId }
          : { password, email: identity.trim(), username: identity.trim(), clientId: tenant.clientId };
      const res = await DataService.post("/auth/login", body);
      const data = res.data;
      if (!data?.token) {
        toast.error("Login failed. Please try again.");
        return;
      }
      applyLoginCookiesOnly(data);
      try {
        localStorage.setItem("nizamify_active_org", tenant.clientId);
      } catch {
        /* ignore */
      }
      Cookies.set("portal", "tenant-property", { expires: 7, sameSite: "lax" });
      toast.success("Signed in successfully");
      window.location.replace(`/${tenant.slug}/dashboard`);
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Invalid username or password."));
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex min-h-screen items-center justify-center text-slate-600">Loading…</div>
    );
  }

  if (error || !tenant) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-3 px-4">
        <p className="text-slate-700">Organization not found</p>
        <Link href="/" className="text-sm text-blue-700 underline">
          Back to Nizamify
        </Link>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-slate-800 to-slate-600 px-4">
      <Card className="w-full max-w-md p-2 shadow">
        <CardContent className="flex flex-col gap-4 p-6 text-center">
          <Link href="/" title="Nizamify home" className="mx-auto">
            <Image src={logo} alt="Nizamify" width={160} height={36} className="h-9 w-auto" />
          </Link>
          <h1 className="text-lg font-bold text-slate-900">{tenant.name}</h1>
          <p className="text-sm text-slate-500">Sign in to this organization</p>
          <form onSubmit={handleSubmit} className="flex flex-col gap-3 text-left">
            <div className="flex items-center justify-between gap-2">
              <Label htmlFor="identity">{mode === "phone" ? "Mobile number" : "Email"}</Label>
              <button
                type="button"
                className="text-xs text-primary underline-offset-2 hover:underline"
                onClick={() => {
                  setMode((m) => (m === "phone" ? "email" : "phone"));
                  setIdentity("");
                }}
              >
                {mode === "phone" ? "Use email instead" : "Use phone instead"}
              </button>
            </div>
            {mode === "phone" ? (
              <PhoneInput
                required
                id="identity"
                value={identity}
                onChange={setIdentity}
              />
            ) : (
              <Input
                required
                id="identity"
                type="email"
                value={identity}
                onChange={(e) => setIdentity(e.target.value)}
                placeholder="you@example.com"
              />
            )}
            <Label htmlFor="password">Password</Label>
            <PasswordInput
              required
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
            />
            <Button className="w-full" type="submit" disabled={submitting}>
              {submitting ? "Signing in…" : "Sign In"}
            </Button>
          </form>
          <Link href={`/${tenant.slug}`} className="text-sm text-slate-500 hover:underline">
            Back to profile
          </Link>
        </CardContent>
      </Card>
    </div>
  );
}
