"use client"

import { toastApiError } from "@/lib/toast-api-error";
import { useRouter } from "next/navigation"
import { zodResolver } from "@hookform/resolvers/zod"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Field,
  FieldError,
  FieldLabel,
} from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { RichTextEditor } from "@/components/settings/common-template/components/rich-text-editor"
import { SettingsInput } from "@/components/settings/ui/settings-input"
import { SettingsSelect } from "@/components/settings/ui/settings-select"
import { createArticle } from "@/components/articles/api/articles.api"
import { ArticleCategoryCheckboxes } from "@/components/articles/create/components/article-category-checkboxes"
import {
  articleCreateFormSchema,
  getArticleCreateDefaults,
  type ArticleCreateFormValues,
} from "@/components/articles/create/schema"
import type { ArticleCreateSectionMeta } from "@/components/articles/data/article-section-meta"
import {
  ARTICLE_CATEGORY_SELECT_OPTIONS,
  ARTICLE_ICON_OPTIONS,
  ARTICLE_STATUS_OPTIONS,
} from "@/components/articles/data/article-form-options"
import { CreateFormLayout } from "@/components/shared/create-form-layout"
import { TABLE_TOOLBAR_BTN_OUTLINE } from "@/components/shared/table-ui"

type ArticleCreateFormProps = {
  meta: ArticleCreateSectionMeta
}

export function ArticleCreateForm({ meta }: ArticleCreateFormProps) {
  const router = useRouter()
  const { id: section, listHref, icon: Icon, title, titlePlaceholder } = meta

  const {
    control,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<ArticleCreateFormValues>({
    resolver: zodResolver(articleCreateFormSchema),
    defaultValues: getArticleCreateDefaults(section),
    mode: "onBlur",
  })

  const onSubmit = async (values: ArticleCreateFormValues) => {
    try {
      await createArticle(values)
      toast.success("Saved successfully")
      router.push(listHref)
    } catch (error) {
      toastApiError(error, "Failed to save")
    }
  }

  const showCategoryCheckboxes = section === "view-all"
  const showCategoryText = section === "blog"
  const showCategorySelect =
    section === "tutorial" || section === "faqs"
  const showScreenshot = section === "tutorial"
  const showIcon = section === "faqs"
  const showPopup = section === "view-all"

  return (
    <CreateFormLayout
      icon={Icon}
      title={title}
      subtitle={meta.subtitle}
      cancelHref={listHref}
      isSubmitting={isSubmitting}
      onSubmit={(e) => void handleSubmit(onSubmit)(e)}
    >
      <Field data-invalid={!!errors.title} className="gap-1.5">
        <FieldLabel htmlFor="article-title" className="text-sm font-medium">
          Title <span className="text-destructive">*</span>
        </FieldLabel>
        <Controller
          name="title"
          control={control}
          render={({ field }) => (
            <SettingsInput
              id="article-title"
              placeholder={titlePlaceholder}
              {...field}
            />
          )}
        />
        <FieldError
          errors={
            errors.title?.message
              ? [{ message: String(errors.title.message) }]
              : undefined
          }
        />
      </Field>

      {showScreenshot ? (
        <Field data-invalid={!!errors.screenshotFileName} className="gap-1.5">
          <FieldLabel htmlFor="article-screenshot" className="text-sm font-medium">
            Screenshot <span className="text-destructive">*</span>
          </FieldLabel>
          <Controller
            name="screenshotFileName"
            control={control}
            render={({ field }) => (
              <div className="flex flex-wrap items-center gap-2">
                <Button
                  type="button"
                  {...TABLE_TOOLBAR_BTN_OUTLINE}
                  onClick={() => {
                    const input = document.getElementById(
                      "article-screenshot-input"
                    ) as HTMLInputElement | null
                    input?.click()
                  }}
                >
                  Browse
                </Button>
                <span className="text-sm text-muted-foreground">
                  {field.value || "No file selected"}
                </span>
                <input
                  id="article-screenshot-input"
                  type="file"
                  accept="image/*"
                  className="sr-only"
                  onChange={(e) => {
                    const file = e.target.files?.[0]
                    field.onChange(file?.name ?? "")
                  }}
                />
              </div>
            )}
          />
          <FieldError
            errors={
              errors.screenshotFileName?.message
                ? [{ message: String(errors.screenshotFileName.message) }]
                : undefined
            }
          />
        </Field>
      ) : null}

      {showIcon ? (
        <Field data-invalid={!!errors.icon} className="gap-1.5">
          <FieldLabel className="text-sm font-medium">
            Icon <span className="text-destructive">*</span>
          </FieldLabel>
          <Controller
            name="icon"
            control={control}
            render={({ field }) => (
              <SettingsSelect
                value={field.value}
                onValueChange={field.onChange}
                options={ARTICLE_ICON_OPTIONS}
                placeholder="Please Select"
              />
            )}
          />
          <FieldError
            errors={
              errors.icon?.message
                ? [{ message: String(errors.icon.message) }]
                : undefined
            }
          />
        </Field>
      ) : null}

      <Field data-invalid={!!errors.content} className="gap-1.5">
        <FieldLabel className="text-sm font-medium">
          Content <span className="text-destructive">*</span>
        </FieldLabel>
        <Controller
          name="content"
          control={control}
          render={({ field }) => (
            <RichTextEditor
              value={field.value}
              onChange={field.onChange}
              minHeight={400}
            />
          )}
        />
        <FieldError
          errors={
            errors.content?.message
              ? [{ message: String(errors.content.message) }]
              : undefined
          }
        />
      </Field>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        {showCategoryCheckboxes ? (
          <Field className="gap-1.5 sm:col-span-1">
            <FieldLabel className="text-sm font-medium">Category</FieldLabel>
            <Controller
              name="categories"
              control={control}
              render={({ field }) => (
                <ArticleCategoryCheckboxes
                  value={field.value}
                  onChange={field.onChange}
                />
              )}
            />
          </Field>
        ) : null}

        {showCategoryText ? (
          <Field className="gap-1.5">
            <FieldLabel htmlFor="article-category" className="text-sm font-medium">
              Category
            </FieldLabel>
            <Controller
              name="category"
              control={control}
              render={({ field }) => (
                <SettingsInput
                  id="article-category"
                  placeholder="Category"
                  {...field}
                />
              )}
            />
          </Field>
        ) : null}

        {showCategorySelect ? (
          <Field data-invalid={!!errors.category} className="gap-1.5">
            <FieldLabel className="text-sm font-medium">Category</FieldLabel>
            <Controller
              name="category"
              control={control}
              render={({ field }) => (
                <SettingsSelect
                  value={field.value}
                  onValueChange={field.onChange}
                  options={ARTICLE_CATEGORY_SELECT_OPTIONS}
                  placeholder="Please Select"
                />
              )}
            />
            <FieldError
              errors={
                errors.category?.message
                  ? [{ message: String(errors.category.message) }]
                  : undefined
              }
            />
          </Field>
        ) : null}

        <Field data-invalid={!!errors.status} className="gap-1.5">
          <FieldLabel className="text-sm font-medium">
            Status <span className="text-destructive">*</span>
          </FieldLabel>
          <Controller
            name="status"
            control={control}
            render={({ field }) => (
              <SettingsSelect
                value={field.value}
                onValueChange={field.onChange}
                options={ARTICLE_STATUS_OPTIONS}
              />
            )}
          />
          <FieldError
            errors={
              errors.status?.message
                ? [{ message: String(errors.status.message) }]
                : undefined
            }
          />
        </Field>

        {showPopup ? (
          <div className="flex items-end sm:col-span-2">
            <Controller
              name="popup"
              control={control}
              render={({ field }) => (
                <div className="flex items-center gap-2 pb-2">
                  <Checkbox
                    id="article-popup"
                    checked={field.value}
                    onCheckedChange={(checked) => field.onChange(checked === true)}
                  />
                  <Label htmlFor="article-popup" className="text-sm font-medium">
                    Popup
                  </Label>
                </div>
              )}
            />
          </div>
        ) : null}
      </div>
    </CreateFormLayout>
  )
}
