"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useTranslations } from "next-intl";
import { useLocale, SUPPORTED_LOCALES, type Locale } from "@/lib/i18n/provider";

type UserProps = {
  name: string;
  email: string;
  image: string | null;
  locale: string;
};

export function SettingsForm({ user }: { user: UserProps }) {
  const t = useTranslations("settingsForm");
  const t_common = useTranslations("common");
  const { setLocale } = useLocale();

  const [name, setName] = useState(user.name);
  const [saving, setSaving] = useState(false);

  async function saveProfile() {
    setSaving(true);
    try {
      const res = await fetch("/api/v1/users/me", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name }),
      });
      if (res.ok) toast.success(t_common("saved"));
      else toast.error(t_common("saveFailed"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="space-y-6">
      <section className="rounded-xl border p-6 space-y-4">
        <h2 className="font-semibold text-lg">{t("profile")}</h2>
        <div className="space-y-2">
          <Label>{t("displayName")}</Label>
          <Input value={name} onChange={(e) => setName(e.target.value)} />
        </div>
        <div className="space-y-2">
          <Label>{t("email")}</Label>
          <Input value={user.email} disabled className="opacity-70" />
        </div>
        <Button onClick={saveProfile} disabled={saving || name === user.name}>
          {saving ? t("saving") : t_common("save")}
        </Button>
      </section>

      <section className="rounded-xl border p-6 space-y-4">
        <h2 className="font-semibold text-lg">{t("language")}</h2>
        <p className="text-sm text-muted-foreground">{t("languageDescription")}</p>
        <Select defaultValue={user.locale} onValueChange={(v) => setLocale(v as Locale)}>
          <SelectTrigger className="w-48">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {SUPPORTED_LOCALES.map((l) => (
              <SelectItem key={l.code} value={l.code}>
                {l.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </section>
    </div>
  );
}
