"use client";

import { Article } from "@/server/db/schema";

import React from "react";

import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import TextareaAutosize from "react-textarea-autosize";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { articleSchema } from "@/lib/validation/zod/article";
import { cn, debounce } from "@/lib/utils";
import { updateArticle } from "@/server/actions/article";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
import CategorySelect from "@/components/category/category-select";
import { CheckCircle, XCircle } from "lucide-react";
import PublishArticleAlertDialog from "./publish-article-alert-dialog";
import { Label } from "@/components/ui/label";
import dynamic from "next/dynamic";
import { appRoutes } from "@/config";
const Editor = dynamic(() => import("../editor"), { ssr: false });

export default ({ server_article }: { server_article: Article }) => {
  const [loading, setLoading] = React.useState(false);
  const form = useForm<z.infer<typeof articleSchema>>({
    resolver: zodResolver(articleSchema),
    defaultValues: {
      title: server_article?.title ?? "",
      slug: server_article?.slug,
      published: server_article?.published ?? false,
      categoryId: server_article?.categoryId ?? "",
      authorId: server_article?.authorId ?? "",
      content: server_article?.content,
    },
  });

  // 2. Define a submit handler.
  async function onSubmit(values: z.infer<typeof articleSchema>) {
    console.log("Content before save", values.content);

    setLoading(true);
    await updateArticle(
      { ...values, content: JSON.stringify(values.content) },
      server_article.id,
    );
    setLoading(false);
    form.reset(values);
  }
  const debouncedSubmit = React.useCallback(
    debounce(() => {
      if (!form.formState.isDirty) return;
      form.handleSubmit(onSubmit)();
    }, 3000),
    [form],
  );
  const published = form.watch("published");

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="flex w-full flex-col-reverse gap-4 space-y-4 xl:flex-row"
      >
        <div className="flex w-full max-w-3xl flex-col gap-2">
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <TextareaAutosize
                    cols={1}
                    className="h-max w-full resize-none bg-transparent text-4xl font-bold focus-visible:outline-none"
                    value={field.value}
                    onChange={(e) => {
                      field.onChange(e);
                      debouncedSubmit();
                    }}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="content"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormControl>
                  <Editor
                    initialContent={field.value}
                    onContentChange={(content) => {
                      field.onChange(content);
                      debouncedSubmit();
                    }}
                  />
                </FormControl>

                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <div
          className={cn(
            "top-4 h-max w-full max-w-xl xl:sticky xl:max-w-md",
            // loading && "border-t-blue-600",
          )}
        >
          <div className="relative w-full space-y-4 overflow-hidden rounded-md border bg-background p-4">
            <div
              className={cn(
                "saving absolute left-0 right-0 top-0 h-0.5 rounded-full bg-primary",
                !loading && "hidden",
              )}
            />

            <div className="flex w-full items-center justify-between">
              <div className="flex items-center gap-2">
                <Badge variant={"outline"} className="flex items-center gap-1">
                  {!form.formState.isDirty && !loading ? (
                    <>
                      <CheckCircle className="size-4 text-emerald-600" />
                      <span>Gespeichert</span>
                    </>
                  ) : (
                    <>
                      <XCircle className="size-4 text-destructive" />
                      <span>Nicht Gespeichert</span>
                    </>
                  )}
                </Badge>
                <span
                  className={cn(
                    "text-xs",
                    published ? "text-emerald-700" : "text-muted-foreground",
                  )}
                >
                  {published
                    ? "Veröffentlicht"
                    : "Draft (nicht veröffentlicht)"}
                </span>
              </div>
              <Link
                href={appRoutes.article(server_article.slug)}
                target="_blank"
                className="size-max scale-90 p-0 text-xs text-muted-foreground"
              >
                <span>Ansehen</span>
              </Link>
            </div>
            <FormField
              control={form.control}
              name="published"
              render={({ field }) => (
                <FormItem className="rounded-md border bg-background px-4 py-2">
                  <FormControl>
                    <div className="flex items-center gap-2">
                      <Label>Veröffentlicht </Label>
                      <PublishArticleAlertDialog
                        published={field.value}
                        setPublished={(value) => {
                          field.onChange(value);
                          form.handleSubmit(onSubmit)();
                        }}
                      />
                    </div>
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="categoryId"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormControl>
                    <CategorySelect
                      className="w-full"
                      initialValue={field.value}
                      onSelect={(categoryId) => {
                        field.onChange(categoryId);
                        form.handleSubmit(onSubmit)();
                      }}
                    />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>
      </form>
    </Form>
  );
};
