"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 { QueryState } from "@/components/api/query-state"
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 {
  useCreateVideo,
  useDeleteVideo,
  useUpdateVideo,
  useVideo,
} from "@/hooks/api/use-videos"
import { useRouter } from "@/i18n/navigation"
import { ApiError } from "@/lib/api/errors"
import { videoToFormValues } from "@/lib/api/videos"
import type { VideoRecord } from "@/lib/markatty"

const videoSchema = z.object({
  url: z.string().url("Enter a valid URL."),
  videoFile: z.any().optional(),
  active: z.boolean(),
})

type VideoFormValues = z.infer<typeof videoSchema>

function toMutationInput(values: VideoFormValues) {
  return {
    url: values.url,
    active: values.active,
    videoFile: values.videoFile instanceof File ? values.videoFile : null,
  }
}

function VideoEditorForm({
  mode,
  video,
}: {
  mode: "create" | "edit"
  video?: VideoRecord
}) {
  const t = useTranslations("Videos")
  const tCreate = useTranslations("Videos.Create")
  const tEdit = useTranslations("Videos.Edit")
  const tc = useTranslations("Common")
  const router = useRouter()
  const createVideo = useCreateVideo()
  const updateVideo = useUpdateVideo()
  const deleteVideo = useDeleteVideo()

  const form = useForm<VideoFormValues>({
    resolver: zodResolver(videoSchema),
    defaultValues: videoToFormValues(video),
    values: video ? videoToFormValues(video) : undefined,
  })

  const isPending =
    createVideo.isPending || updateVideo.isPending || deleteVideo.isPending

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

  async function onSubmit(values: VideoFormValues) {
    if (mode === "create" && !(values.videoFile instanceof File)) {
      form.setError("videoFile", { message: tCreate("errors.videoRequired") })
      return
    }

    const input = toMutationInput(values)

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

  async function handleDelete() {
    if (!video) return

    try {
      await deleteVideo.mutateAsync(video.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: video?.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">
              {mode === "edit" && video ? (
                <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground md:col-span-2">
                  <span>
                    {tCreate("labels.type")}: {video.type}
                  </span>
                  <span>
                    {tCreate("labels.locale")}: {video.locale || "—"}
                  </span>
                </div>
              ) : null}
              <FormField
                control={form.control}
                name="url"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>{tCreate("labels.url")}</FormLabel>
                    <FormControl>
                      <Input placeholder={tCreate("placeholders.url")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="videoFile"
                render={({ field }) => (
                  <MediaFileField
                    className="md:col-span-2"
                    label={tCreate("labels.video")}
                    accept="video/*"
                    name={field.name}
                    onBlur={field.onBlur}
                    inputRef={field.ref}
                    onChange={field.onChange}
                    helperText={
                      mode === "create"
                        ? tCreate("help.videoFileOnly")
                        : tCreate("help.videoFileOptional")
                    }
                    currentText={
                      video?.videoUrl
                        ? tCreate("help.currentFile", { value: video.videoUrl })
                        : undefined
                    }
                    previewUrl={video?.videoUrl}
                    selectedPreviewLabel={tCreate("labels.selectedVideo")}
                    currentPreviewLabel={tCreate("labels.currentVideo")}
                    previewKind="video"
                  />
                )}
              />
            </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" && video ? (
            <EditDangerSection
              sectionTitle={tEdit("sections.dangerZone")}
              actionTitle={tEdit("danger.deleteTitle")}
              actionDescription={tEdit("danger.deleteDescription")}
              confirmMessage={t("confirm.delete", { id: video.id })}
              actionLabel={tc("actions.delete")}
              disabled={isPending}
              isPending={deleteVideo.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>
  )
}

export function VideoEditor({
  mode,
  id,
}: {
  mode: "create" | "edit"
  id?: string
}) {
  const { data: video, isLoading, isError, error } = useVideo(id ?? "")

  if (mode === "create") {
    return <VideoEditorForm mode="create" />
  }

  return (
    <QueryState isLoading={isLoading} isError={isError} error={error}>
      {video ? (
        <VideoEditorForm key={video.id} mode="edit" video={video} />
      ) : null}
    </QueryState>
  )
}
