import { Alert, Button, MenuProps, Tag } from "antd"
import { ColumnsType } from "antd/es/table"
import { Download } from "lucide-react"
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"

const ListPanel = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const router = useRouter()
  const pid = typeof router.query.pid === "string" ? typeof router.query.pid : ""

  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 columns: ColumnsType<IQuiz> = [
    {
      title: "제목",
      width: 200,
      align: "left",
      dataIndex: "subject",
      render: (value: string, item: IQuiz) => {
        return (
          <span>
            <span>
              <Link href={`/program/${item.id}`}>{value}</Link>
            </span>
          </span>
        )
      },
    },
    {
      title: "태그",
      dataIndex: "tag",
      align: "center",
      width: 80,
      render: (value: string) => {
        const tags = value.split(",")
        return (
          <span>
            {tags.map((tag, i) => (
              <Tag key={tag}>
                <Link href="/program?tag={tag}">{tag}</Link>
              </Tag>
            ))}
          </span>
        )
      },
    },
    {
      title: "상태",
      dataIndex: "status",
      align: "center",
      width: 80,
      render: (value: string) => {
        return (
          <span>
            <span>{value}</span>
          </span>
        )
      },
    },
    {
      title: "상태",
      dataIndex: "status",
      align: "center",
      width: 80,
      render: (value: string) => {
        return (
          <span>
            <span>{value}</span>
          </span>
        )
      },
    },
    {
      title: "등록날짜",
      dataIndex: "created_at",
      align: "center",
      width: 120,
      render: (value: string) => {
        return (
          <div className="text-sm">
            <span className="block">{getUTCDatetime(value)}</span>
          </div>
        )
      },
    },
  ]

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

  return (
    <>
      <DefaultTableBtn className="justify-between">
        <div></div>
        <div className="flex-item-list">
          <Button className="btn-with-icon" icon={<Download />}>
            XLS
          </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?.total}
      />
    </>
  )
}

export default React.memo(ListPanel)
