"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 {
  qid?: string
  pid?: string
  data?: any
}

const QuizChoiceForm = (props: Props) => {
  const { pid, qid, data } = props
  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: QuizFormValue) => {
    console.log("value", value)
    console.log("answer", answer)
    if (answer === "") {
      messageApi.error("해답을 선택하세요.")
      return
    }

    let params: QuizFormValue = {
      quiz_type: "choice",
      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 ? 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] ?? "",
    }))
  }

  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={formData?.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>
          <Radio.Group onChange={selectAnswer} value={answer} style={{ display: "block" }}>
            <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">
                <Radio value="1">해답 1</Radio>
              </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">
                <Radio value="2">해답 2</Radio>
              </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">
                <Radio value="3">해답 3</Radio>
              </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">
                <Radio value="4">해답 4</Radio>
              </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>
          </Radio.Group>
        </FormSection>

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

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

export default React.memo(QuizChoiceForm)
