"use client";

import { useActionState } from "react";
import { updateProfile } from "@/lib/profile/actions";
import type { ActionState } from "@/lib/auth/actions";
import { TextField, TextAreaField, SelectField } from "@/components/ui/Field";
import { Button } from "@/components/ui/Button";
import { TR_CITIES } from "@/lib/constants/cities";
import type { Profile } from "@sohbetegir/db";

export function ProfileForm({ profile }: { profile: Profile }) {
  const [state, formAction, pending] = useActionState<ActionState, FormData>(updateProfile, undefined);

  return (
    <form action={formAction} className="flex flex-col gap-4">
      <TextField label="Ad Soyad" name="fullName" defaultValue={profile.fullName} error={state?.errors?.fullName} required />

      <div className="grid grid-cols-2 gap-3.5">
        <TextField label="Telefon" name="phone" defaultValue={profile.phone ?? ""} error={state?.errors?.phone} />
        <SelectField label="Şehir" name="city" defaultValue={profile.city ?? ""} error={state?.errors?.city} required>
          <option value="" disabled>
            Şehir seç
          </option>
          {TR_CITIES.map((city) => (
            <option key={city} value={city}>
              {city}
            </option>
          ))}
        </SelectField>
      </div>

      <TextField label="Adres" name="address" defaultValue={profile.address ?? ""} error={state?.errors?.address} />
      <TextField label="Yaş" name="age" type="number" min={18} max={120} defaultValue={profile.age ?? undefined} error={state?.errors?.age} required />

      <div className="grid grid-cols-2 gap-3.5">
        <TextField label="Sinema Zevki" name="cinemaTaste" defaultValue={profile.cinemaTaste ?? ""} error={state?.errors?.cinemaTaste} />
        <TextField label="Müzik Zevki" name="musicTaste" defaultValue={profile.musicTaste ?? ""} error={state?.errors?.musicTaste} />
      </div>

      <TextAreaField label="Hobiler" name="hobbies" defaultValue={profile.hobbies ?? ""} error={state?.errors?.hobbies} />
      <TextAreaField label="Fobiler" name="phobias" defaultValue={profile.phobias ?? ""} error={state?.errors?.phobias} />
      <TextAreaField label="Hakkımda" name="bio" defaultValue={profile.bio ?? ""} error={state?.errors?.bio} />

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

      <Button type="submit" disabled={pending} className="mt-1">
        {pending ? "Kaydediliyor..." : "Profili Kaydet"}
      </Button>
    </form>
  );
}
