"use client"

import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { EditDangerSection } from "@/components/edit-danger-section"
import { MediaFileField } from "@/components/markatty/media-file-field"
import { FormSection } from "@/components/form-section"
import { StatusSwitchField } from "@/components/status-switch-field"
import { PageHeader } from "@/components/page-header"
import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  useCreateTestimonial,
  useDeleteTestimonial,
  useUpdateTestimonial,
} from "@/hooks/api/use-testimonials"
import { Link, useRouter } from "@/i18n/navigation"
import { ApiError } from "@/lib/api/errors"
import { testimonialToFormValues } from "@/lib/api/testimonials"
import type { TestimonialRecord } from "@/lib/markatty"

const testimonialSchema = z.object({
  name: z.string().min(2, "Customer name is required."),
  roleCompany: z.string().min(2, "Role or company is required."),
  quote: z.string().min(10, "Quote is required."),
  avatarFile: z.any().optional(),
  rating: z.number().int().min(1, "Rating must be at least 1.").max(5, "Rating must be 5 or less."),
  active: z.boolean(),
})

type TestimonialFormValues = z.infer<typeof testimonialSchema>

function toMutationInput(values: TestimonialFormValues, locale?: string) {
  return {
    authorName: values.name,
    companyName: values.roleCompany,
    comment: values.quote,
    rating: values.rating,
    locale: locale ?? "",
    active: values.active,
    companyLogoFile:
      values.avatarFile instanceof File ? values.avatarFile : null,
  }
}

export function TestimonialEditor({
  mode,
  testimonial,
}: {
  mode: "create" | "edit"
  testimonial?: TestimonialRecord
}) {
  const t = useTranslations("Testimonials")
  const tCreate = useTranslations("Testimonials.Create")
  const tEdit = useTranslations("Testimonials.Edit")
  const tc = useTranslations("Common")
  const router = useRouter()
  const createTestimonial = useCreateTestimonial()
  const updateTestimonial = useUpdateTestimonial()
  const deleteTestimonial = useDeleteTestimonial()

  const form = useForm<TestimonialFormValues>({
    resolver: zodResolver(testimonialSchema),
    defaultValues: testimonialToFormValues(testimonial),
    values: testimonial ? testimonialToFormValues(testimonial) : undefined,
  })

  const isPending =
    createTestimonial.isPending ||
    updateTestimonial.isPending ||
    deleteTestimonial.isPending

  const showApiError = (e: unknown) => {
    toast.error(e instanceof ApiError ? e.message : tc("api.errorFallback"))
  }

  async function onSubmit(values: TestimonialFormValues) {
    const input = toMutationInput(values, testimonial?.locale)

    try {
      if (mode === "create") {
        await createTestimonial.mutateAsync(input)
        toast.success(t("toast.created"))
      } else if (testimonial) {
        await updateTestimonial.mutateAsync({ id: testimonial.id, ...input })
        toast.success(t("toast.updated"))
      }
      router.back()
    } catch (e) {
      showApiError(e)
    }
  }

  async function handleDelete() {
    if (!testimonial) return
    try {
      await deleteTestimonial.mutateAsync(testimonial.id)
      toast.success(t("toast.deleted"))
      router.back()
    } catch (e) {
      showApiError(e)
    }
  }

  return (
    <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
      <PageHeader
        title={
          mode === "create"
            ? tCreate("title")
            : tEdit("title", { id: testimonial?.id ?? "" })
        }
        actions={
          <Button variant="outline" type="button" onClick={() => router.back()}>
            {tc("actions.back")}
          </Button>
        }
      />

      <Form {...form}>
        <form className="grid gap-6" onSubmit={form.handleSubmit(onSubmit)}>
          <FormSection title={tCreate("sections.content")}>
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tCreate("labels.name")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tCreate("placeholders.name")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="roleCompany"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tCreate("labels.roleCompany")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tCreate("placeholders.roleCompany")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="quote"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>{tCreate("labels.quote")}</FormLabel>
                    <FormControl>
                      <Textarea rows={5} placeholder={tCreate("placeholders.quote")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="avatarFile"
                render={({ field }) => (
                  <MediaFileField
                    className="md:col-span-2"
                    label={tCreate("labels.avatar")}
                    accept="image/*"
                    name={field.name}
                    onBlur={field.onBlur}
                    inputRef={field.ref}
                    onChange={field.onChange}
                    helperText={
                      mode === "create"
                        ? tCreate("help.avatarFileOnly")
                        : tCreate("help.avatarFileOptional")
                    }
                    currentText={
                      testimonial?.avatarUrl
                        ? tCreate("help.currentFile", { value: testimonial.avatarUrl })
                        : undefined
                    }
                    previewUrl={testimonial?.avatarUrl}
                    selectedPreviewLabel={tCreate("labels.selectedAvatar")}
                    currentPreviewLabel={tCreate("labels.currentAvatar")}
                    previewClassName="size-20 rounded-full"
                    previewKind="image"
                  />
                )}
              />
              <FormField
                control={form.control}
                name="rating"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tCreate("labels.rating")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min={1}
                        max={5}
                        value={Number.isFinite(field.value) ? field.value : 5}
                        onChange={(event) => field.onChange(event.target.valueAsNumber)}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </FormSection>

          <FormSection title={tCreate("sections.settings")}>
            <div className="grid gap-4 md:grid-cols-2">
              <StatusSwitchField
                control={form.control}
                name="active"
                label={tCreate("labels.active")}
                description={tCreate("help.activeOnly")}
                className="md:col-span-2"
              />
            </div>
          </FormSection>

          {mode === "edit" && testimonial ? (
            <EditDangerSection
              sectionTitle={tEdit("sections.dangerZone")}
              actionTitle={tEdit("danger.deleteTitle")}
              actionDescription={tEdit("danger.deleteDescription")}
              confirmMessage={t("confirm.delete", { name: testimonial.name })}
              actionLabel={tc("actions.delete")}
              disabled={isPending}
              isPending={deleteTestimonial.isPending}
              onDelete={handleDelete}
            />
          ) : null}

          <div className="px-4 lg:px-6">
            <div className="flex items-center justify-end gap-2">
              <Button variant="outline" type="button" onClick={() => router.back()}>
                {tc("actions.cancel")}
              </Button>
              <Button type="submit" disabled={isPending}>
                {mode === "create" ? tc("actions.create") : tc("actions.saveChanges")}
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
}
