"use client"

import { create, QuizFormValue, update } from "@/client/quiz"
import "@uiw/react-markdown-preview/markdown.css"
import "@uiw/react-md-editor/markdown-editor.css"
import { Button, Checkbox, Divider, Form, Input, message, Radio } from "antd"
import { useForm } from "antd/lib/form/Form"
import dynamic from "next/dynamic"
import Router from "next/router"
import React, { useEffect, useState } from "react"

import DefaultForm from "@/components/shared/form/ui/default-form"
import FormGroup from "@/components/shared/form/ui/form-group"
import FormSection from "@/components/shared/form/ui/form-section"
import router from "next/router"

interface Props {
  pid?: string
  qid?: string
  data?: any
}

const QuizCheckForm = (props: Props) => {
  const { pid, qid, data } = props
  const program_id = router.query.program_id ? (router.query.program_id as string) : ""
  const sequence = data?.sequence ? data?.sequence : router.query.sequence ? Number(router.query.sequence as string) : 1
  const [form] = useForm()
  const [isLoading, setIsLoading] = useState(false)
  const [messageApi, contextHolder] = message.useMessage()

  const [quizType, setQuizType] = React.useState(data ? data.quiz_choicec : "choice")
  const [answer, setAnswer] = React.useState("")
  const [formData, setFormData] = useState<any>(null)

  const handleFinish = async (value: any) => {
    console.log("value", value)
    let answer: string[] = []
    if (value.check1) {
      answer.push("1")
    }
    if (value.check2) {
      answer.push("2")
    }
    if (value.check3) {
      answer.push("3")
    }
    if (value.check4) {
      answer.push("4")
    }
    if (answer.length === 0) {
      messageApi.error("해답을 선택하세요.")
      return
    }

    let params: QuizFormValue = {
      quiz_type: "check",
      program_id: data ? data.program_id : pid,
      answer: answer,
      choice: [value.choice1!, value.choice2!, value.choice3!, value.choice4!],
      sequence: Number(value.sequence),
      question: value.question,
      hint: value.hint,
      comment: "",
    }

    console.log("params", params)

    try {
      setIsLoading(true)
      if (qid) {
        await update(qid, params)
        messageApi.success("수정되었습니다")
        setTimeout(() => Router.back(), 500)
      } else {
        await create(params)
        messageApi.success("생성되었습니다")
        setTimeout(() => Router.back(), 500)
      }
    } catch (e: unknown) {
      messageApi.error("에러가 발생했습니다")
    } finally {
      setTimeout(() => setIsLoading(false), 500)
    }
  }

  const Editor = dynamic(() => import("@uiw/react-md-editor"), { ssr: false })
  const selectQuizType = (e: any) => {
    setQuizType(e.target.value)
  }

  const selectAnswer = (e: any) => {
    console.log("selectAnswer", e.target.value)
    setAnswer(e.target.value)
  }

  const updateData = (data: any) => {
    console.log("updateData", data)
    setAnswer(data?.answer[0])
    setFormData(data)
    setFormData((prevData: any) => ({
      ...prevData,
      ["choice1"]: data?.choice[0] ?? "",
      ["choice2"]: data?.choice[1] ?? "",
      ["choice3"]: data?.choice[2] ?? "",
      ["choice4"]: data?.choice[3] ?? "",
      ["check1"]: data?.answer?.includes("1"),
      ["check2"]: data?.answer?.includes("2"),
      ["check3"]: data?.answer?.includes("3"),
      ["check4"]: data?.answer?.includes("4"),
    }))
  }

  useEffect(() => {
    console.log("use effect data", data)
    if (data) {
      updateData(data)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data])

  useEffect(() => {
    console.log("formData", formData)
    if (!data && !formData) {
      const sequence = router.query.sequence
      setFormData({ sequence: sequence })
    }
    form.resetFields()
  }, [data, form, formData])

  return (
    <>
      {contextHolder}
      <DefaultForm<QuizFormValue> form={form} initialValues={formData} onFinish={handleFinish}>
        <FormSection>
          <FormGroup title="번호">
            <Form.Item name="sequence" rules={[{ required: true, message: "필수값입니다" }]}>
              <Input type="number" value={sequence} />
            </Form.Item>
          </FormGroup>
          <FormGroup title="문제">
            <Form.Item name="question" rules={[{ required: true, message: "필수값입니다" }]}>
              <Editor height={100} value={formData?.question} />
            </Form.Item>
          </FormGroup>
        </FormSection>

        <FormSection>
          <div className="mb-0 lg:flex lg:mb-3">
            <div className="flex-none w-full mt-1 mb-3 lg:w-48 lg:mb-0">
              <Form.Item name="check1" valuePropName="checked">
                <Checkbox checked={formData?.answer?.includes("1") ? true : false}>해답 1</Checkbox>
              </Form.Item>
            </div>
            <div className="min-w-0 mb-5 grow lg:-mb-3">
              <Form.Item name="choice1" rules={[{ required: true, message: "필수값입니다" }]}>
                <Editor height={120} value={formData?.choice1} />
              </Form.Item>
            </div>
          </div>

          <Divider />

          <div className="mb-0 lg:flex lg:mb-3">
            <div className="flex-none w-full mt-1 mb-3 lg:w-48 lg:mb-0">
              <Form.Item name="check2" valuePropName="checked">
                <Checkbox checked={formData?.answer?.includes("2") ? true : false}>해답 2</Checkbox>
              </Form.Item>
            </div>
            <div className="min-w-0 mb-5 grow lg:-mb-3">
              <Form.Item name="choice2" rules={[{ required: true, message: "필수값입니다" }]}>
                <Editor height={120} value={formData?.choice2} />
              </Form.Item>
            </div>
          </div>

          <Divider />

          <div className="mb-0 lg:flex lg:mb-3">
            <div className="flex-none w-full mt-1 mb-3 lg:w-48 lg:mb-0">
              <Form.Item name="check3" valuePropName="checked">
                <Checkbox checked={formData?.answer?.includes("3") ? true : false}>해답 3</Checkbox>
              </Form.Item>
            </div>
            <div className="min-w-0 mb-5 grow lg:-mb-3">
              <Form.Item name="choice3" rules={[{ required: true, message: "필수값입니다" }]}>
                <Editor height={120} value={formData?.choice3} />
              </Form.Item>
            </div>
          </div>

          <Divider />

          <div className="mb-0 lg:flex lg:mb-3">
            <div className="flex-none w-full mt-1 mb-3 lg:w-48 lg:mb-0">
              <Form.Item name="check4" valuePropName="checked">
                <Checkbox checked={formData?.answer?.includes("4") ? true : false}>해답 4</Checkbox>
              </Form.Item>
            </div>
            <div className="min-w-0 mb-5 grow lg:-mb-3">
              <Form.Item name="choice4" rules={[{ required: true, message: "필수값입니다" }]}>
                <Editor height={120} value={formData?.choice4} />
              </Form.Item>
            </div>
          </div>
        </FormSection>

        <FormSection>
          <FormGroup title="힌트">
            <Form.Item name="hint">
              <Editor height={100} value={formData?.hint} />
            </Form.Item>
          </FormGroup>
        </FormSection>

        <div className="text-center">
          <Button htmlType="submit" type="primary" loading={isLoading}>
            Save
          </Button>
        </div>
      </DefaultForm>
    </>
  )
}

export default React.memo(QuizCheckForm)
