import { Link } from "@/app/_lib/data/link"
import { LinkType } from "@/app/_lib/data/linkType"
import { mRequest } from "@/app/_lib/request"
import ImageUpload from "@/app/_ui/ImageUpload"
import { useAntdTable, useRequest } from "ahooks"
import {
    Button,
    Card,
    DatePicker,
    Form,
    Image,
    Input,
    InputNumber,
    message,
    Modal,
    Popconfirm,
    Radio,
    Select,
    Space,
    Table,
} from "antd"
import dayjs from "dayjs"
import { useState } from "react"



export default function LinkTable(props: { id: string }) {
    const [loading, setLoading] = useState(false)
    const { data: LinkTypeList } = useRequest(async () => mRequest<{
        list: LinkType[]
    }>('GET', '/api/linkType'))
    const { tableProps, refresh } = useAntdTable(
        async ({ current, pageSize }) => {
            return mRequest<{
                total: number;
                list: Link[]
            }>(
                "GET",
                `/api/link?page=${current}&pageSize=${pageSize}&typeId=${props.id}`
            )
        },

    )
    // const refresh = useCallback(async () => {
    //     setLoading(true)
    //     const res = await mRequest<{ list: Link[] }>(
    //         "GET",
    //         `/api/link?typeId=${props.id}&page=1&pageSize=9999`
    //     )
    //     setList(res.list)
    //     setLoading(false)
    // }, [props.id])

    const [selected, setSelected] = useState<undefined | null | Link>(
        undefined
    )
    return (
        <div className="p-4">
            <Card
                title="链接列表"
                extra={
                    <Space>
                        <Button onClick={refresh}>
                            刷新
                        </Button>
                        <Button type="primary" onClick={() => setSelected(null)}>
                            添加链接
                        </Button>
                    </Space>

                }
            >
                <Table<Link>
                    {...tableProps}
                    loading={loading}
                    rowKey="_id"
                    columns={[
                        {
                            title: "名称",
                            dataIndex: "name",
                        },
                        {
                            title: "图标",
                            dataIndex: "logoLink",
                            render: (_, row) => (
                                <Image width={80} src={row.logoLink}></Image>
                            )
                        },
                        {
                            title: "是否热门",
                            dataIndex: "isHot",
                            render: (_, row) => (
                                row.isHot ? '是' : '否'
                            )
                        },
                        {
                            title: "操作",
                            fixed: "right",
                            width: 200,
                            render: (_, row) => (
                                <Space>
                                    <Button type="link" onClick={() => setSelected(row)}>
                                        编辑
                                    </Button>
                                    <Popconfirm
                                        title="确认删除？"
                                        onConfirm={async () => {
                                            await mRequest("DELETE", "/api/link/" + row._id,)
                                            refresh()
                                            message.success("删除成功")
                                        }}
                                    >
                                        <Button type="link" danger>
                                            删除
                                        </Button>
                                    </Popconfirm>
                                </Space>
                            ),
                        },
                    ]}
                />
            </Card>
            <Modal
                open={selected !== undefined}
                onCancel={() => setSelected(undefined)}
                destroyOnClose
                title={(selected ? "编辑" : "新增") + "链接"}
                footer={false}
            >
                <Form
                    labelCol={{ span: 4 }}
                    initialValues={
                        selected
                            ? {
                                ...selected,
                                addTime: selected.addTime ? dayjs(selected.addTime * 1000) : dayjs(),
                                isHot: selected?.isHot ? 1 : 0
                            }
                            : { title: "", url: "", logoLink: "", description: "", priority: 0, type: props.id, isHot: 0, addTime: dayjs() }
                    }
                    onFinish={async (res) => {
                        if (selected) {
                            await mRequest("PUT", "/api/link", {
                                _id: selected._id,
                                ...res,
                                type: props.id,
                                addTime: res.addTime.unix()

                            })
                        } else {
                            await mRequest("POST", "/api/link", {
                                ...res, type: props.id,
                                addTime: res.addTime.unix()
                            })
                        }
                        refresh()
                        setSelected(undefined)
                        message.success("操作成功")
                    }}
                >
                    <Form.Item
                        name="name"
                        label="图标名称"
                        rules={[{ required: true, message: "名称必填" }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item name="link" label="链接" rules={[{ required: true, message: "链接必填" }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="logoLink"
                        label="图标名称"
                        rules={[{ required: true, message: "名称必填" }]}
                    >
                        <ImageUpload
                            accept="image/*"
                            width={60}
                            height={60}
                        ></ImageUpload>
                    </Form.Item>

                    <Form.Item name="description" label="详情"
                        rules={[{ required: true, message: "详情必填" }]}
                    >
                        <Input.TextArea />
                    </Form.Item>
                    <Form.Item name="type" label="分类"
                        rules={[{ required: true, message: "分类必填" }]}

                    >
                        <Select options={LinkTypeList?.list.map(item => ({
                            label: item.label,
                            value: item._id
                        }))}></Select>
                    </Form.Item>
                    <Form.Item name="priority" label="优先级"
                        rules={[{ required: true, message: "请输入优先级" }]}

                    >
                        <InputNumber min={0} max={9999999}></InputNumber>
                    </Form.Item>
                    <Form.Item name="addTime" label="收录时间">
                        <DatePicker
                            allowClear={false}
                            showTime
                        />
                    </Form.Item>
                    <Form.Item name="isHot" label="是否热门">
                        <Radio.Group
                            options={[
                                {
                                    label: '是',
                                    value: 1
                                },
                                {
                                    label: '否',
                                    value: 0
                                }
                            ]}
                        />
                    </Form.Item>
                    <Form.Item className="flex justify-end">
                        <Button type="primary" htmlType="submit">
                            确认
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div >
    )
}
