"use client";

import { useState, useTransition } from "react";
import { useRouter, useSearchParams } from "next/navigation";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [formState, setFormState] = useState({
    email: "",
    password: "",
  });

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);

    startTransition(async () => {
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formState),
      });

      const payload = (await response.json().catch(() => null)) as
        | { message?: string }
        | null;

      if (!response.ok) {
        setError(payload?.message || "تعذر تسجيل الدخول.");
        return;
      }

      const nextPath = searchParams.get("next") || "/dashboard/customers";
      router.replace(nextPath);
      router.refresh();
    });
  }

  return (
    <form className="space-y-5" onSubmit={handleSubmit}>
      <div className="space-y-2">
        <h2 className="text-3xl font-bold text-[var(--foreground)]">
          تسجيل الدخول
        </h2>
        <p className="text-sm leading-7 text-[var(--foreground-muted)]">
          ادخل على حسابك وكمل متابعة عملاءك وملفاتهم.
        </p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="login-email">البريد الإلكتروني</Label>
        <Input
          id="login-email"
          type="email"
          autoComplete="email"
          placeholder="name@example.com"
          value={formState.email}
          onChange={(event) =>
            setFormState((current) => ({ ...current, email: event.target.value }))
          }
          required
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="login-password">كلمة السر</Label>
        <Input
          id="login-password"
          type="password"
          autoComplete="current-password"
          placeholder="اكتب كلمة السر"
          value={formState.password}
          onChange={(event) =>
            setFormState((current) => ({
              ...current,
              password: event.target.value,
            }))
          }
          required
        />
      </div>

      {error ? (
        <p className="rounded-2xl bg-[color:rgba(185,28,28,0.08)] px-4 py-3 text-sm font-medium text-[var(--destructive)]">
          {error}
        </p>
      ) : null}

      <Button className="w-full" size="lg" disabled={isPending} type="submit">
        {isPending ? "جارٍ تسجيل الدخول..." : "دخول"}
      </Button>
    </form>
  );
}
