"use client"

import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect } from "react"
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 { MediaPreview } from "@/components/markatty/media-preview"
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 {
  useCreateTheme,
  useDeleteTheme,
  useUpdateTheme,
} from "@/hooks/api/use-themes"
import { Link, useRouter } from "@/i18n/navigation"
import { ApiError } from "@/lib/api/errors"
import type { ThemeRecord } from "@/lib/admin-content"
import { themeToFormValues, type ThemeInput } from "@/lib/api/themes"

const themeFormSchema = z.object({
  key: z.string().min(1, "Key is required."),
  name: z.string().min(1, "Name is required."),
  parent: z.string().min(1, "Parent is required."),
  industry: z.string().min(1, "Industry is required."),
  preview: z
    .string()
    .min(1, "Preview URL is required.")
    .url("Enter a valid preview URL."),
  viewsPath: z.string().min(1, "Views path is required."),
  assetsPath: z.string().min(1, "Assets path is required."),
  mainTheme: z.string().min(1, "Main theme is required."),
  layout: z.number().int().nullable(),
  pagination: z.number().int().min(1, "Pagination must be at least 1."),
  adsNumber: z.number().int().min(0, "Ads number cannot be negative."),
  sticker: z.string(),
  main: z.boolean(),
  active: z.boolean(),
  mainImageFile: z.any().optional(),
})

type ThemeFormValues = z.infer<typeof themeFormSchema>

function toMutationInput(values: ThemeFormValues): ThemeInput {
  return {
    key: values.key,
    name: values.name,
    parent: values.parent,
    industry: values.industry,
    preview: values.preview,
    viewsPath: values.viewsPath,
    assetsPath: values.assetsPath,
    mainTheme: values.mainTheme,
    layout: values.layout,
    pagination: values.pagination,
    adsNumber: values.adsNumber,
    sticker: values.sticker,
    main: values.main,
    active: values.active,
    mainImageFile:
      values.mainImageFile instanceof File ? values.mainImageFile : null,
  }
}

function toFormValues(theme?: ThemeRecord): ThemeFormValues {
  const base = themeToFormValues(theme)
  return {
    ...base,
    mainImageFile: null,
  }
}

export function ThemeEditor({
  mode,
  theme,
}: {
  mode: "create" | "edit"
  theme?: ThemeRecord
}) {
  const t = useTranslations("Themes")
  const tForm = useTranslations("Themes.Form")
  const tc = useTranslations("Common")
  const router = useRouter()
  const createTheme = useCreateTheme()
  const updateTheme = useUpdateTheme()
  const deleteThemeMutation = useDeleteTheme()

  const form = useForm<ThemeFormValues>({
    resolver: zodResolver(themeFormSchema),
    defaultValues: toFormValues(theme),
    values: theme ? toFormValues(theme) : undefined,
  })

  const watchedKey = form.watch("key")
  const watchedParent = form.watch("parent")

  useEffect(() => {
    if (mode !== "create") return
    const key = watchedKey.trim()
    if (key) {
      form.setValue("assetsPath", `public/themes/${key}/assets`, {
        shouldDirty: true,
      })
    }
  }, [form, mode, watchedKey])

  useEffect(() => {
    if (mode !== "create") return
    const parent = watchedParent.trim()
    if (parent) {
      form.setValue("viewsPath", `resources/themes/${parent}/views`, {
        shouldDirty: true,
      })
    }
  }, [form, mode, watchedParent])

  const isPending =
    createTheme.isPending ||
    updateTheme.isPending ||
    deleteThemeMutation.isPending

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

  async function onSubmit(values: ThemeFormValues) {
    const input = toMutationInput(values)
    try {
      if (mode === "create") {
        await createTheme.mutateAsync(input)
        toast.success(t("toast.created"))
      } else if (theme) {
        await updateTheme.mutateAsync({ key: theme.key, input })
        toast.success(t("toast.updated"))
      }
      router.back()
    } catch (e) {
      showApiError(e)
    }
  }

  async function handleDelete() {
    if (!theme) return
    try {
      await deleteThemeMutation.mutateAsync(theme)
      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"
            ? tForm("createTitle")
            : tForm("editTitle", { name: theme?.name ?? "" })
        }
        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={tForm("sections.general")}>
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="key"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.key")}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={tForm("placeholders.key")}
                        disabled={mode === "edit"}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.name")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.name")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="parent"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.parent")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.parent")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="industry"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.industry")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.industry")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="sticker"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.sticker")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.sticker")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="mainTheme"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.mainTheme")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.mainTheme")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </FormSection>

          <FormSection title={tForm("sections.paths")}>
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="viewsPath"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>{tForm("labels.viewsPath")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.viewsPath")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="assetsPath"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>{tForm("labels.assetsPath")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.assetsPath")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </FormSection>

          <FormSection title={tForm("sections.settings")}>
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="layout"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.layout")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={tForm("placeholders.layout")}
                        value={field.value ?? ""}
                        onChange={(e) => {
                          const next = e.target.value
                          field.onChange(next === "" ? null : Number(next))
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="pagination"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.pagination")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min={1}
                        value={field.value}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="adsNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{tForm("labels.adsNumber")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min={0}
                        value={field.value}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <StatusSwitchField
                control={form.control}
                name="main"
                label={tForm("labels.main")}
              />
              <StatusSwitchField
                control={form.control}
                name="active"
                label={tForm("labels.active")}
              />
            </div>
          </FormSection>

          <FormSection title={tForm("sections.preview")}>
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="preview"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>{tForm("labels.preview")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tForm("placeholders.preview")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="mainImageFile"
                render={({ field }) => (
                  <MediaFileField
                    className="md:col-span-2"
                    label={tForm("labels.mainImage")}
                    accept="image/*"
                    name={field.name}
                    onBlur={field.onBlur}
                    inputRef={field.ref}
                    onChange={field.onChange}
                    helperText={tForm("help.mainImage")}
                    currentText={
                      theme?.thumbnailUrl
                        ? tForm("help.currentImage", { value: theme.thumbnailUrl })
                        : undefined
                    }
                  />
                )}
              />
              {mode === "edit" && theme?.thumbnailUrl ? (
                <div className="md:col-span-2 flex items-center gap-3">
                  <MediaPreview
                    src={theme.thumbnailUrl}
                    label={tForm("labels.currentImage")}
                    className="size-20"
                  />
                </div>
              ) : null}
            </div>
          </FormSection>

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

          <div className="px-4 lg:px-6">
            <div className="flex flex-wrap 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>
  )
}
