"use client";

import { useActionState } from "react";
import { Loader2, LogIn } from "lucide-react";
import { loginAction, type AuthState } from "@/app/actions/auth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const initialState: AuthState = {};

export function LoginForm({ configured }: { configured: boolean }) {
  const [state, formAction, pending] = useActionState(loginAction, initialState);
  return (
    <form action={formAction} className="grid gap-5">
      {!configured ? (
        <p
          className="rounded-md border-r-4 border-[#c98a22] bg-[#fff3dd] px-4 py-3 text-sm font-semibold leading-7 text-[#694716]"
          role="status"
        >
          يلزم إضافة مفتاح Supabase العام إلى إعدادات الخادم قبل تسجيل الدخول.
        </p>
      ) : null}
      <div>
        <Label htmlFor="identifier">البريد الإلكتروني أو رقم الهاتف</Label>
        <Input
          id="identifier"
          name="identifier"
          type="text"
          dir="ltr"
          inputMode="text"
          autoComplete="username"
          placeholder="admin@example.org أو +249912345678"
          required
          disabled={!configured}
        />
      </div>
      <div>
        <Label htmlFor="password">كلمة المرور</Label>
        <Input id="password" name="password" type="password" dir="ltr" autoComplete="current-password" minLength={6} required disabled={!configured} />
      </div>
      {state.error ? (
        <p className="rounded-md bg-[#fae5e5] px-4 py-3 text-sm font-semibold text-[#922f31]" role="alert">
          {state.error}
        </p>
      ) : null}
      <Button type="submit" disabled={pending || !configured}>
        {pending ? <Loader2 className="animate-spin" size={18} aria-hidden /> : <LogIn size={18} aria-hidden />}
        {pending ? "جارٍ تسجيل الدخول..." : "تسجيل الدخول"}
      </Button>
    </form>
  );
}
