"use client";
import {
  Button,
  Input,
  Select,
  SelectItem,
  SelectSection,
  Textarea,
} from "@nextui-org/react";
import { FormEvent, useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { close, error, loading } from "@/config/swal";
import { getGenerateRewriter } from "@/service/generate-article";
import TranscriptDraftTable from "@/components/table/disestages/transcript-draft-table";
import ArticleDraftTable from "@/components/table/disestages/article-draft-table";

const writingStyle = [
  {
    id: 1,
    name: "Friendly",
  },
  {
    id: 1,
    name: "Professional",
  },
  {
    id: 3,
    name: "Informational",
  },
  {
    id: 4,
    name: "Neutral",
  },
  {
    id: 5,
    name: "Witty",
  },
];

const articleSize = [
  {
    id: 1,
    name: "News (300 - 900 words)",
    value: "News",
  },
  {
    id: 2,
    name: "Info (900 - 2000 words)",
    value: "Info",
  },
  {
    id: 3,
    name: "Detail (2000 - 5000 words)",
    value: "Detail",
  },
];

const formSchema = z.object({
  field1: z.string().min(2, {
    message: "Required",
  }),
  advancedConfiguration: z.string().optional(),
});

export default function GenerateRewriteArticle(props: {
  articleId: (data: number) => void;
  initTranscript?: number;
}) {
  const [selectedWritingSyle, setSelectedWritingStyle] =
    useState("Informational");
  const [selectedArticleSize, setSelectedArticleSize] = useState("News");
  const [selectedLanguage, setSelectedLanguage] = useState("id");
  const [contextType, setContextType] = useState("text");

  useEffect(() => {
    if (props.initTranscript) {
      setContextType("transcript");
    }
  }, [props.initTranscript]);

  const formOptions = { resolver: zodResolver(formSchema) };
  type UserSettingSchema = z.infer<typeof formSchema>;
  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
  } = useForm<UserSettingSchema>(formOptions);

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    loading();
    const request = {
      advConfig: values.advancedConfiguration || "",
      context: contextType == "url" ? null : values.field1,
      style: selectedWritingSyle,
      sentiment: "Humorous",
      clientId: "humasClientIdtest",
      createdBy: "123123",
      contextType: contextType,
      urlContext: contextType === "url" ? values.field1 : null,
      lang: selectedLanguage,
    };
    const res = await getGenerateRewriter(request);
    close();
    if (res?.error) {
      error("Error");
    }
    props.articleId(res?.data?.data?.id);
  };

  useEffect(() => {
    setValue("field1", "");
  }, [contextType]);
  return (
    <fieldset>
      <form
        className="flex flex-col gap-2 w-full"
        onSubmit={handleSubmit(onSubmit)}
      >
        <div className="grid grid-cols-1 md:grid-cols-4 gap-5 w-full">
          <Select
            label="Context Type"
            variant="bordered"
            labelPlacement="outside"
            placeholder=""
            selectedKeys={[contextType]}
            onChange={(e) =>
              e.target.value !== "" ? setContextType(e.target.value) : ""
            }
            className="w-full"
          >
            <SelectSection>
              <SelectItem key="text">Text</SelectItem>
              <SelectItem key="article">Article</SelectItem>
              <SelectItem key="transcript">Transcript</SelectItem>
              <SelectItem key="url">URL</SelectItem>
            </SelectSection>
          </Select>
          <Select
            label="Writing Style"
            variant="bordered"
            labelPlacement="outside"
            placeholder=""
            selectedKeys={[selectedWritingSyle]}
            onChange={(e) =>
              e.target.value !== ""
                ? setSelectedWritingStyle(e.target.value)
                : ""
            }
            className="w-full"
          >
            <SelectSection>
              {writingStyle.map((style) => (
                <SelectItem key={style.name}>{style.name}</SelectItem>
              ))}
            </SelectSection>
          </Select>
          <Select
            label="Article Size"
            variant="bordered"
            labelPlacement="outside"
            placeholder=""
            selectedKeys={[selectedArticleSize]}
            onChange={(e) =>
              e.target.value !== ""
                ? setSelectedArticleSize(e.target.value)
                : ""
            }
            className="w-full"
          >
            <SelectSection>
              {articleSize.map((size) => (
                <SelectItem key={size.value}>{size.name}</SelectItem>
              ))}
            </SelectSection>
          </Select>
          <Select
            label="Language"
            variant="bordered"
            labelPlacement="outside"
            placeholder=""
            selectedKeys={[selectedLanguage]}
            onChange={(e) =>
              e.target.value !== "" ? setSelectedLanguage(e.target.value) : ""
            }
            className="w-full"
          >
            <SelectSection>
              <SelectItem key="id">Indonesia</SelectItem>
              <SelectItem key="en">English</SelectItem>
            </SelectSection>
          </Select>
        </div>
        <div className="flex flex-col gap-3 mt-3">
          {(contextType === "text" || contextType === "url") && (
            <p className="text-sm">
              {contextType === "text" ? "Enter your text here" : "Insert URL"}
            </p>
          )}
          {(contextType === "text" || contextType === "url") && (
            <Controller
              control={control}
              name="field1"
              render={({ field: { onChange, value } }) =>
                contextType === "text" ? (
                  <Textarea
                    label=""
                    id="adv_config"
                    variant="bordered"
                    disableAnimation
                    className="pb-3"
                    placeholder="Type your custom instruction here!"
                    value={value}
                    onChange={onChange}
                  />
                ) : (
                  <Input
                    type="text"
                    id="mainKeyword"
                    placeholder=""
                    label=""
                    value={value}
                    onChange={onChange}
                    labelPlacement="outside"
                    className="w-full"
                    variant="bordered"
                  />
                )
              }
            />
          )}

          {errors.field1?.message && (
            <p className="text-red-400 text-sm">{errors.field1?.message}</p>
          )}

          {contextType === "article" && (
            <>
              <ArticleDraftTable
                articleContent={(data) => setValue("field1", data)}
              />
              {errors.field1?.message && (
                <p className="text-red-400 text-sm">Select Transcript</p>
              )}
            </>
          )}

          {contextType === "transcript" && (
            <>
              <TranscriptDraftTable
                transriptContent={(data) => setValue("field1", data)}
                initTranscriptId={String(props.initTranscript)}
              />
              {errors.field1?.message && (
                <p className="text-red-400 text-sm">Select Transcript</p>
              )}
            </>
          )}

          <Button
            color="primary"
            className="my-5 w-full py-5 text-xs md:text-base"
            type="submit"
          >
            Generate
          </Button>
        </div>
      </form>
    </fieldset>
  );
}
