"use client";

import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { AvatarPicker } from "@/components/avatar";
import { updateMyProfileAction, type ProfileState } from "./actions";

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" className="btn-primary" disabled={pending}>
      {pending ? "Đang lưu…" : "Lưu thông tin"}
    </button>
  );
}

export function ProfileForm({
  initial,
}: {
  initial: { fullName: string; phone: string; birthDate: string; gender: string; avatar: string | null };
}) {
  const [state, formAction] = useActionState<ProfileState, FormData>(updateMyProfileAction, {});

  return (
    <form action={formAction} className="card mb-6 flex max-w-2xl flex-col gap-4 p-4">
      <AvatarPicker name={initial.fullName} current={initial.avatar} />

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <label htmlFor="fullName" className="label-caps mb-1.5 block">
            Họ tên
          </label>
          <input id="fullName" name="fullName" required defaultValue={initial.fullName} className="input" />
        </div>
        <div>
          <label htmlFor="phone" className="label-caps mb-1.5 block">
            Điện thoại
          </label>
          <input id="phone" name="phone" type="tel" defaultValue={initial.phone} className="input" />
        </div>
        <div>
          <label htmlFor="birthDate" className="label-caps mb-1.5 block">
            Ngày sinh
          </label>
          <input id="birthDate" name="birthDate" type="date" defaultValue={initial.birthDate} className="input" />
        </div>
        <div>
          <label htmlFor="gender" className="label-caps mb-1.5 block">
            Giới tính
          </label>
          <select id="gender" name="gender" defaultValue={initial.gender} className="input">
            <option value="">— Không nêu —</option>
            <option value="M">Nam</option>
            <option value="F">Nữ</option>
            <option value="O">Khác</option>
          </select>
        </div>
      </div>

      {state.error && (
        <p role="alert" className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
          {state.error}
        </p>
      )}
      {state.ok && <p className="rounded-lg bg-ink-100 px-3 py-2 text-sm text-brand-600">{state.ok}</p>}

      <div>
        <SubmitButton />
      </div>
    </form>
  );
}
