"use client"

import { Alert, Button, Dropdown, MenuProps, Tag } from "antd"
import { ColumnsType } from "antd/es/table"
import { MoreVertical, Plus, Users } from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/router"
import React, { useCallback, useEffect, useMemo, useState } from "react"

import { IProgram, usePrograms } from "@/client/program"
import DefaultTable from "@/components/shared/ui/default-table"
import DefaultTableBtn from "@/components/shared/ui/default-table-btn"
import { getLocalDate, getUTCDatetime } from "@/helpers/datetime"

const ListPanel = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const router = useRouter()

  const { data, error, isLoading } = usePrograms({
    page: router.query.page ? Number(router.query.page) : 1,
    tag: router.query.tag ? (typeof router.query.tag === "string" ? router.query.tag : router.query.tag[0]) : "",
    q: router.query.q ? (typeof router.query.q === "string" ? router.query.q : router.query.q[0]) : "",
  })
  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<IProgram> = [
    {
      title: "제목",
      width: 200,
      align: "left",
      dataIndex: "subject",
      render: (value: string, item: IProgram) => {
        return (
          <span>
            <Link href={`/program/${item.id}`}>{value}</Link>
          </span>
        )
      },
    },
    {
      title: "프로그램",
      width: 140,
      align: "left",
      dataIndex: "course",
      render: (value: string, item: IProgram) => {
        return <span>{value}</span>
      },
    },
    {
      title: "문항",
      width: 40,
      align: "center",
      dataIndex: "cnt",
      render: (value: number, item: IProgram) => {
        return <span>{value}</span>
      },
    },
    {
      title: "태그",
      dataIndex: "tag",
      align: "left",
      width: 120,
      render: (value: any) => {
        return (
          <span>
            {value.map((t: string, i: number) => (
              <Tag key={i}>
                <Link href={`/program?tag=${t}`}>{t}</Link>
              </Tag>
            ))}
          </span>
        )
      },
    },
    {
      title: "상태",
      dataIndex: "status",
      align: "center",
      width: 80,
      render: (value: string) => {
        return (
          <span>
            {value === "on" && <Tag color="success">ON</Tag>}
            {value === "off" && <Tag color="error">OFF</Tag>}
          </span>
        )
      },
    },
    {
      title: "등록날짜",
      dataIndex: "publish_at",
      align: "center",
      width: 120,
      render: (value: string) => {
        return (
          <div className="text-sm">
            <span className="block">{getLocalDate(value)}</span>
          </div>
        )
      },
    },
    {
      title: "",
      dataIndex: "id",
      align: "center",
      width: 30,
      render: (value: string) => {
        const items: MenuProps["items"] = [
          {
            key: "1",
            label: <Link href={`/program/${value}`}>편집</Link>,
          },
          {
            key: "2",
            label: (
              <Link href={`/program/${value}/preview`} target="_blank">
                미리보기
              </Link>
            ),
          },
        ]
        return (
          <Dropdown menu={{ items }} placement="topRight">
            <MoreVertical />
          </Dropdown>
        )
      },
    },
  ]

  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={<Plus />} onClick={() => router.push("/program/create")}>
            New
          </Button>
        </div>
      </DefaultTableBtn>

      <DefaultTable<IProgram>
        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)
