"use client";

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

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

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

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

    if (formState.password !== formState.confirmPassword) {
      setError("تأكيد كلمة السر لازم يكون مطابق.");
      return;
    }

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

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

      if (!response.ok) {
        setError(payload?.message || "تعذر إنشاء الحساب.");
        return;
      }

      router.replace("/dashboard/customers");
      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="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor="register-firstName">الاسم الأول</Label>
          <Input
            id="register-firstName"
            autoComplete="given-name"
            placeholder="مثال: أحمد"
            value={formState.firstName}
            onChange={(event) =>
              setFormState((current) => ({
                ...current,
                firstName: event.target.value,
              }))
            }
            required
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="register-lastName">اسم العيلة</Label>
          <Input
            id="register-lastName"
            autoComplete="family-name"
            placeholder="مثال: محمود"
            value={formState.lastName}
            onChange={(event) =>
              setFormState((current) => ({
                ...current,
                lastName: event.target.value,
              }))
            }
            required
          />
        </div>
      </div>

      <div className="space-y-2">
        <Label htmlFor="register-email">البريد الإلكتروني</Label>
        <Input
          id="register-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="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor="register-password">كلمة السر</Label>
          <Input
            id="register-password"
            type="password"
            autoComplete="new-password"
            placeholder="8 حروف أو أكتر"
            value={formState.password}
            onChange={(event) =>
              setFormState((current) => ({
                ...current,
                password: event.target.value,
              }))
            }
            required
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="register-confirmPassword">تأكيد كلمة السر</Label>
          <Input
            id="register-confirmPassword"
            type="password"
            autoComplete="new-password"
            placeholder="اكتبها تاني"
            value={formState.confirmPassword}
            onChange={(event) =>
              setFormState((current) => ({
                ...current,
                confirmPassword: event.target.value,
              }))
            }
            required
          />
        </div>
      </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>
  );
}
