"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { useToast } from "@/components/toast";
import { ApiError } from "@/lib/api";
import { Button, Field, Input } from "@/components/ui";

export default function LoginPage() {
  const { login, token, ready } = useAuth();
  const router = useRouter();
  const toast = useToast();

  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  // Already logged in? skip the form.
  useEffect(() => {
    if (ready && token) router.replace("/dashboard");
  }, [ready, token, router]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      await login(identifier.trim(), password);
      toast.success("خوش آمدید!");
      router.replace("/dashboard");
    } catch (err) {
      toast.error(
        err instanceof ApiError ? err.message : "ورود ناموفق بود. دوباره تلاش کنید.",
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-bl from-[#eef1fb] to-[#f6f3fb] p-4">
      <div className="w-full max-w-md rounded-3xl border border-border bg-surface p-8 shadow-lg">
        <div className="mb-8 text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-primary-soft text-3xl">
            🧘
          </div>
          <h1 className="text-2xl font-bold text-foreground">پنل مدیریت مدیتیشن</h1>
          <p className="mt-2 text-sm text-muted">
            برای ورود، نام کاربری و رمز عبور خود را وارد کنید.
          </p>
        </div>

        <form onSubmit={onSubmit} className="flex flex-col gap-4">
          <Field label="ایمیل یا شماره موبایل" required>
            <Input
              type="text"
              dir="ltr"
              autoComplete="username"
              placeholder="admin@gmail.com یا 09001234567"
              value={identifier}
              onChange={(e) => setIdentifier(e.target.value)}
              required
            />
          </Field>

          <Field label="رمز عبور" required>
            <Input
              type="password"
              dir="ltr"
              autoComplete="current-password"
              placeholder="••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </Field>

          <Button type="submit" loading={loading} className="mt-2 w-full py-2.5">
            ورود
          </Button>
        </form>
      </div>
    </div>
  );
}
