"use client";

import { useActionState } from "react";
import Link from "next/link";
import { register, type ActionState } from "@/lib/auth/actions";
import { TextField, SelectField } from "@/components/ui/Field";
import { Button } from "@/components/ui/Button";
import { TR_CITIES } from "@/lib/constants/cities";

export function RegisterForm() {
  const [state, formAction, pending] = useActionState<ActionState, FormData>(register, undefined);

  return (
    <form action={formAction} className="flex flex-col gap-4">
      <TextField label="Ad Soyad" name="fullName" placeholder="Adın ve soyadın" error={state?.errors?.fullName} required />
      <TextField label="E-posta Adresi" name="email" type="email" placeholder="ornek@eposta.com" error={state?.errors?.email} required />

      <div className="grid grid-cols-2 gap-3.5">
        <SelectField label="Şehir" name="city" error={state?.errors?.city} defaultValue="" required>
          <option value="" disabled>
            Şehir seç
          </option>
          {TR_CITIES.map((city) => (
            <option key={city} value={city}>
              {city}
            </option>
          ))}
        </SelectField>
        <TextField label="Yaş" name="age" type="number" min={18} max={120} placeholder="Yaşın" error={state?.errors?.age} required />
      </div>

      <div className="grid grid-cols-2 gap-3.5">
        <TextField label="Şifre" name="password" type="password" placeholder="••••••••" error={state?.errors?.password} required />
        <TextField
          label="Şifre Tekrar"
          name="passwordConfirm"
          type="password"
          placeholder="••••••••"
          error={state?.errors?.passwordConfirm}
          required
        />
      </div>

      <label className="mt-1 flex items-start gap-2.5 text-[12.5px] leading-relaxed text-text-muted">
        <input type="checkbox" name="acceptTerms" required className="mt-0.5 h-[15px] w-[15px] accent-accent" />
        <span>
          <Link href="/uyelik-sozlesmesi" className="text-accent">
            Üyelik Sözleşmesi
          </Link>
          &apos;ni ve{" "}
          <Link href="/kvkk" className="text-accent">
            KVKK Aydınlatma Metni
          </Link>
          &apos;ni okudum, kabul ediyorum.
        </span>
      </label>
      {state?.errors?.acceptTerms && (
        <p className="text-[12.5px] text-accent">{state.errors.acceptTerms[0]}</p>
      )}

      {state?.message && <p className="text-[13px] text-accent">{state.message}</p>}

      <Button type="submit" disabled={pending} className="mt-1 w-full">
        {pending ? "Kaydediliyor..." : "Ücretsiz Üye Ol"}
      </Button>

      <p className="text-center text-[13px] text-text-muted">
        Zaten hesabın var mı?{" "}
        <Link href="/giris" className="font-semibold text-accent">
          Giriş Yap
        </Link>
      </p>
    </form>
  );
}
