"use client";

import * as React from "react";
import { useActionState } from "react";
import { toast } from "sonner";
import { Globe } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
  NativeSelect,
  NativeSelectOption,
} from "@/components/ui/native-select";
import { accountTexts } from "@/lib/i18n/account";
import { updatePreferencesAction } from "@/lib/actions/account";
import { SUPPORTED_LANGUAGES, type AccountActionState } from "@/lib/validation/account";
import { FormFooter, SectionCard } from "./section-card";

export function PreferencesForm({
  language,
  timezone,
  timezones,
}: {
  language: string;
  timezone: string;
  timezones: string[];
}) {
  const [state, formAction, pending] = useActionState<AccountActionState, FormData>(
    updatePreferencesAction,
    null,
  );

  const [lang, setLang] = React.useState(language || "en");
  const [tz, setTz] = React.useState(timezone || "UTC");

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

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

  const options = React.useMemo(() => {
    const list = timezones.includes(tz) ? timezones : [tz, ...timezones];
    return list;
  }, [timezones, tz]);

  return (
    <SectionCard
      icon={Globe}
      title={accountTexts.preferencesTitle}
      description={accountTexts.preferencesHint}
    >
      <form action={formAction}>
        <fieldset disabled={pending} className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-1.5">
            <Label htmlFor="language" className="text-sm font-medium">
              {accountTexts.languageLabel}
            </Label>
            <NativeSelect
              id="language"
              name="language"
              value={lang}
              onChange={(e) => setLang(e.target.value)}
              disabled={pending}
              className="h-9 w-full [&_select]:h-9"
            >
              {SUPPORTED_LANGUAGES.map((l) => (
                <NativeSelectOption key={l.value} value={l.value}>
                  {l.label}
                </NativeSelectOption>
              ))}
            </NativeSelect>
            <p className="text-xs text-muted-foreground">{accountTexts.languageHint}</p>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="timezone" className="text-sm font-medium">
              {accountTexts.timezoneLabel}
            </Label>
            <NativeSelect
              id="timezone"
              name="timezone"
              value={tz}
              onChange={(e) => setTz(e.target.value)}
              disabled={pending}
              className="h-9 w-full [&_select]:h-9"
            >
              {options.map((zone) => (
                <NativeSelectOption key={zone} value={zone}>
                  {zone.replace(/_/g, " ")}
                </NativeSelectOption>
              ))}
            </NativeSelect>
            {errors.timezone ? (
              <p className="text-xs font-medium text-destructive">{errors.timezone}</p>
            ) : (
              <p className="text-xs text-muted-foreground">{accountTexts.timezoneHint}</p>
            )}
          </div>
        </fieldset>

        <FormFooter
          message={
            state?.ok
              ? accountTexts.preferencesSaved
              : 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 PreferencesForm;
