"use client"

import { useTransition, type ReactElement } from "react"
import { useTranslations } from "next-intl"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { Loader2, Save } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Form } from "@/shared/components/ui/form"
import { TextField } from "@/shared/components/form-fields/text-field"
import { SelectField } from "@/shared/components/form-fields/select-field"
import type { UserProfile } from "@/modules/users/data-access"
import { useSettingsService } from "@/modules/settings/components/settings-service-context"

const profileFormSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters."),
  email: z.string().email().optional(),
  role: z.string().optional(),
  phone: z.string().optional(),
  address: z.string().optional(),
  gender: z.string().optional(),
  age: z.string().optional(),
})

type ProfileFormValues = z.infer<typeof profileFormSchema>

const GENDER_OPTIONS = [
  { value: "male", label: "Male" },
  { value: "female", label: "Female" },
  { value: "other", label: "Other" },
  { value: "prefer_not_to_say", label: "Prefer not to say" },
]

export function ProfileSettingsForm({ user }: { user: UserProfile }): ReactElement {
  const t = useTranslations("settings.profile")
  const { profile } = useSettingsService()
  const [isPending, startTransition] = useTransition()

  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(profileFormSchema),
    defaultValues: {
      name: user.name ?? "",
      email: user.email ?? "",
      role: user.role ?? "",
      phone: user.phone ?? "",
      address: user.address ?? "",
      gender: user.gender ?? "",
      age: user.age !== undefined && user.age !== null ? String(user.age) : "",
    },
  })

  function onSubmit(data: ProfileFormValues): void {
    startTransition(async () => {
      try {
        const ageNum = data.age ? Number(data.age) : undefined
        const result = await profile.updateProfile({
          name: data.name,
          phone: data.phone || undefined,
          address: data.address || undefined,
          gender: data.gender || undefined,
          age: ageNum !== undefined && !Number.isNaN(ageNum) ? ageNum : undefined,
        })
        if (result.success) {
          toast.success(t("success"))
        } else {
          toast.error(result.message || t("failure"))
        }
      } catch {
        toast.error(t("failure"))
      }
    })
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("title")}</CardTitle>
        <CardDescription>{t("description")}</CardDescription>
      </CardHeader>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <TextField
                control={form.control}
                name="name"
                label={t("fields.name")}
                placeholder={t("fields.namePlaceholder")}
              />
              <TextField
                control={form.control}
                name="email"
                label={t("fields.email")}
                disabled
                description={t("fields.emailDisabled")}
              />
              <TextField
                control={form.control}
                name="phone"
                label={t("fields.phone")}
                placeholder={t("fields.phonePlaceholder")}
              />
              <SelectField
                control={form.control}
                name="gender"
                label={t("fields.gender")}
                placeholder={t("fields.genderPlaceholder")}
                options={GENDER_OPTIONS}
              />
              <TextField
                control={form.control}
                name="age"
                label={t("fields.age")}
                type="number"
                placeholder={t("fields.age")}
              />
              <TextField
                control={form.control}
                name="role"
                label={t("fields.role")}
                disabled
                inputClassName="capitalize"
              />
              <TextField
                control={form.control}
                name="address"
                label={t("fields.address")}
                placeholder={t("fields.addressPlaceholder")}
                itemClassName="col-span-1 sm:col-span-2"
              />
            </div>
          </CardContent>
          <CardFooter className="flex justify-end border-t px-6 py-4">
            <Button type="submit" disabled={isPending}>
              {isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  {t("saving")}
                </>
              ) : (
                <>
                  <Save className="mr-2 h-4 w-4" />
                  {t("save")}
                </>
              )}
            </Button>
          </CardFooter>
        </form>
      </Form>
    </Card>
  )
}
