"use client";

import * as React from "react";
import { useActionState } from "react";
import { toast } from "sonner";
import { UserRound } from "lucide-react";
import { Button } from "@/components/ui/button";
import { accountTexts } from "@/lib/i18n/account";
import { updateProfileAction } from "@/lib/actions/account";
import type { AccountActionState } from "@/lib/validation/account";
import { FormFooter, SectionCard, TextField } from "./section-card";

export type ProfileValues = {
  username: string;
  email: string;
  phone: string;
  firstName: string;
  lastName: string;
};

export function ProfileForm({ initial }: { initial: ProfileValues }) {
  const [state, formAction, pending] = useActionState<AccountActionState, FormData>(
    updateProfileAction,
    null,
  );

  const [values, setValues] = React.useState(initial);
  const set = (key: keyof ProfileValues) => (value: string) =>
    setValues((prev) => ({ ...prev, [key]: value }));

  React.useEffect(() => {
    if (!state) return;
    if (state.ok) toast.success(accountTexts.profileSaved);
    else toast.error(state.error);
  }, [state]);

  const failure = state && state.ok === false ? state : null;
  const errors = failure?.fieldErrors ?? {};

  return (
    <SectionCard
      icon={UserRound}
      title={accountTexts.profileTitle}
      description={accountTexts.profileHint}
    >
      <form action={formAction}>
        <fieldset disabled={pending} className="grid gap-4 sm:grid-cols-2">
          <TextField
            id="username"
            label={accountTexts.usernameLabel}
            value={values.username}
            readOnly
            hint={accountTexts.usernameHint}
            className="sm:col-span-2"
          />
          <TextField
            id="email"
            label={accountTexts.emailLabel}
            type="email"
            autoComplete="email"
            value={values.email}
            onChange={set("email")}
            error={errors.email}
          />
          <TextField
            id="phone"
            label={accountTexts.phoneLabel}
            type="tel"
            autoComplete="tel"
            placeholder="+355 69 000 0000"
            value={values.phone}
            onChange={set("phone")}
            error={errors.phone}
          />
          <TextField
            id="firstName"
            label={accountTexts.firstNameLabel}
            autoComplete="given-name"
            value={values.firstName}
            onChange={set("firstName")}
            error={errors.firstName}
          />
          <TextField
            id="lastName"
            label={accountTexts.lastNameLabel}
            autoComplete="family-name"
            value={values.lastName}
            onChange={set("lastName")}
            error={errors.lastName}
          />
        </fieldset>

        <FormFooter
          message={
            state?.ok
              ? accountTexts.profileSaved
              : failure && !Object.keys(errors).length
                ? failure.error
                : null
          }
          tone={failure ? "error" : "success"}
        >
          <Button type="submit" disabled={pending}>
            {pending ? "Saving…" : "Save changes"}
          </Button>
        </FormFooter>
      </form>
    </SectionCard>
  );
}

export default ProfileForm;
