import { Alert, Button, MenuProps, Popconfirm } from "antd"
import { ColumnsType } from "antd/es/table"
import Link from "next/link"
import { useRouter } from "next/router"
import React, { useCallback, useEffect, useMemo, useState } from "react"

import { IQuiz, useQuizzes } from "@/client/quiz"
import DefaultTable from "@/components/shared/ui/default-table"
import DefaultTableBtn from "@/components/shared/ui/default-table-btn"
import { getUTCDatetime } from "@/helpers/datetime"
import dynamic from "next/dynamic"

const ListPanel = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const router = useRouter()
  const pid = router.query.pid ? (router.query.pid as string) : ""
  const { data, error, isLoading } = useQuizzes({
    page: router.query.page ? Number(router.query.page) : 1,
    program_id: pid,
  })
  useEffect(() => {
    console.log("data", data)
  }, [data])

  const handleChangePage = useCallback(
    (pageNumber: number) => {
      router.push({
        pathname: router.pathname,
        query: { ...router.query, page: pageNumber },
      })
    },
    [router]
  )

  const onSelectChange = useCallback((newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys)
  }, [])

  const modifyDropdownItems: MenuProps["items"] = useMemo(
    () => [
      {
        key: "statusUpdate",
        label: <a onClick={() => console.log(selectedRowKeys)}>상태수정</a>,
      },
    ],
    [selectedRowKeys]
  )

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }
  const hasSelected = selectedRowKeys.length > 0

  const Preview = dynamic(() => import("@uiw/react-markdown-preview"), { ssr: false })
  const columns: ColumnsType<IQuiz> = [
    {
      title: "Category",
      dataIndex: "category",
      align: "center",
      width: 80,
      render: (value: string, item: IQuiz) => {
        return (
          <span>
            <span>{value}</span>
          </span>
        )
      },
    },
    {
      title: "Subject",
      dataIndex: "subject",
      align: "center",
      width: 80,
      render: (value: string, item: IQuiz) => {
        return (
          <span>
            <span>{value}</span>
          </span>
        )
      },
    },
    {
      title: "Question",
      width: 240,
      align: "left",
      dataIndex: "question",
      render: (value: string, item: IQuiz) => {
        return (
          <Link href={`/program/${item.program_id}/quiz/${item.id}`}>
            <Preview source={value} />
          </Link>
        )
      },
    },
    {
      title: "Status",
      dataIndex: "status",
      align: "center",
      width: 100,
    },
    {
      title: "Created",
      dataIndex: "created_at",
      align: "center",
      width: 120,
      render: (value: string) => {
        return (
          <div className="text-sm">
            <span className="block">{getUTCDatetime(value)}</span>
          </div>
        )
      },
    },
    {
      key: "action",
      width: 100,
      align: "center",
      render: (_value: unknown, item: IQuiz) => {
        return (
          <span className="flex justify-center gap-1">
            <Link href={`/program/${item.program_id}/quiz/edit/${item.id}`} className="px-2 py-1 text-sm btn">
              Edit
            </Link>
            {
              <Popconfirm title="Delete?" onConfirm={() => alert("삭제")} okText="Yes" cancelText="No">
                <a className="px-1 py-1 text-sm btn">Del</a>
              </Popconfirm>
            }
          </span>
        )
      },
    },
  ]

  if (error) {
    return <Alert message="데이터 로딩 중 오류가 발생했습니다." type="warning" />
  }

  return (
    <>
      <DefaultTableBtn className="justify-between">
        <div></div>

        <div className="flex-item-list">
          <Button type="primary" onClick={() => router.push(`/program/${pid}quiz/new`)}>
            New
          </Button>
        </div>
      </DefaultTableBtn>

      <DefaultTable<IQuiz>
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data?.data || []}
        loading={isLoading}
        pagination={{
          current: Number(router.query.page || 1),
          defaultPageSize: 10,
          total: data?.total || 0,
          showSizeChanger: false,
          onChange: handleChangePage,
        }}
        className="mt-3"
        countLabel={data?.totalPage}
      />
    </>
  )
}

export default React.memo(ListPanel)
