"use client";
import { deleteSearchWay, SearchTypeItem, SearchWayItemType } from "@/app/_lib/data/search";
import { mRequest } from "@/app/_lib/request";
import { useAntdTable } from "ahooks";
import { Button, Card, Drawer, Form, Input, InputNumber, message, Popconfirm, Space, Table } from "antd";
import { useState } from "react";
import '@ant-design/v5-patch-for-react-19';
import SearchSelect from "./SearchSelect";

export default function Page() {
    const { tableProps, refresh } = useAntdTable(async ({ current, pageSize }) => mRequest<{
        total: number;
        list: SearchWayItemType[]
    }>('GET', `/api/search?page=${current}&pageSize=${pageSize}`))
    const { tableProps: typeTableProps, refresh: refreshTypeList } = useAntdTable(async ({ current, pageSize }) => mRequest<{
        total: number;
        list: SearchTypeItem[]
    }>('GET', `/api/searchType?page=${current}&pageSize=${pageSize}`))
    const [selected, setSelected] = useState<SearchWayItemType | null | undefined>()
    const [selectedType, setSelectedType] = useState<SearchTypeItem | null | undefined>()
    const [viewMode, setViewMode] = useState(false)
    return <>
        <Card title="搜索引擎管理"
            extra={
                <Space>
                    <Button onClick={() => {
                        refresh()
                    }}>刷新</Button>
                    <Button type="primary" onClick={() => {
                        setSelected(null)
                    }}>新增搜索引擎</Button>
                </Space>


            }>
            <Table<SearchWayItemType>
                {...tableProps}
                rowKey={'_id'}
                columns={[
                    {
                        title: '名称',
                        dataIndex: 'label',

                    },
                    {
                        title: '全称',
                        dataIndex: 'fullName',
                    },
                    {
                        title: '搜索链接',
                        dataIndex: 'value'
                    },
                    {
                        title: '操作',
                        render: (_, row) => (
                            <Space>
                                <Button type="primary" onClick={() => {
                                    setSelected(row)
                                }}>修改</Button>
                                <Popconfirm
                                    title="确定删除"
                                    description="是否删除该项?"
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={() => {
                                        // mRequest('DELETE', `/api/search/${row._id}`).then(res => {
                                        //     refresh()
                                        // })
                                        deleteSearchWay(row._id).then(() => {
                                            refresh()
                                            message.success('删除成功')
                                        })
                                    }}
                                >
                                    <Button danger >删除</Button>

                                </Popconfirm>
                            </Space>
                        )
                    }
                ]}
            >

            </Table>

        </Card>
        <Card
            className="mt-2"
            title="搜索分类管理"
            extra={
                <Space>
                    <Button onClick={() => {
                        refreshTypeList()
                    }}>刷新</Button>
                    <Button type="primary" onClick={() => {
                        setSelectedType(null)
                    }}>新增搜索分类</Button>
                </Space>


            }>
            <Table<SearchTypeItem>
                {...typeTableProps}
                rowKey={'_id'}
                columns={[
                    {
                        title: '名称',
                        dataIndex: 'name',
                        width: 400
                    },

                    {
                        title: '优先级',
                        dataIndex: 'priority'
                    },
                    {
                        title: '操作',
                        render: (_, row) => (
                            <Space>
                                <Button onClick={() => {
                                    console.log(row);
                                    setViewMode(true)
                                    setSelectedType(row)

                                }}>详请</Button>
                                <Button type="primary" onClick={() => {
                                    setSelectedType(row)
                                }}>修改</Button>
                                <Popconfirm
                                    title="确定删除"
                                    description="是否删除该项?"
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={() => {
                                        mRequest('DELETE', `/api/searchType/${row._id}`).then(() => {
                                            refreshTypeList()
                                            message.success('删除成功')
                                        })
                                    }}
                                >
                                    <Button danger >删除</Button>

                                </Popconfirm>
                            </Space>
                        )
                    }
                ]}
            >

            </Table>

        </Card>
        <Drawer
            destroyOnClose
            title={selected !== undefined ? selected === null ? "添加搜索引擎" : "修改搜索引擎" : ""}
            open={selected !== undefined}
            width={500}
            onClose={() => {
                setSelected(undefined)
            }}
        >
            <Form
                labelCol={{ span: 4 }}
                initialValues={selected ?
                    selected
                    : {
                    }
                }
                onFinish={async (res) => {
                    if (selected) {
                        await mRequest("PUT", "/api/search", {
                            _id: selected._id, ...res
                        })
                    } else {
                        await mRequest("POST", "/api/search", {
                            ...res,
                        })
                    }
                    refresh()
                    setSelected(undefined)
                    message.success("操作成功")
                }}
            >
                <Form.Item
                    name="label"
                    label="简称"
                    rules={[{ required: true, message: "请输入名称" }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="fullName"
                    label="全称"
                    rules={[{ required: true, message: "请输入名称" }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="value"
                    label="链接"

                    rules={[{ required: true, message: "请输入名称" }]}
                >
                    <Input placeholder="关键词以%s代替" />
                </Form.Item>

                <Form.Item className="flex justify-end">
                    <Space>
                        <Button>
                            重置
                        </Button>
                        <Button type="primary" htmlType="submit">
                            确认
                        </Button>
                    </Space>

                </Form.Item>
            </Form>
        </Drawer>
        <Drawer
            destroyOnClose
            title={viewMode ? '查看详请' : (selectedType !== undefined ? selectedType === null ? "添加搜索分类" : "修改搜索分类" : "")}
            open={selectedType !== undefined}
            width={500}
            onClose={() => {
                setSelectedType(undefined)
                setViewMode(false)
            }}

        >
            <Form
                disabled={viewMode}
                labelCol={{ span: 4 }}
                initialValues={selectedType ?
                    selectedType
                    : {
                        priority: 0
                    }
                }

                onFinish={async (res) => {
                    if (selectedType) {
                        await mRequest("PUT", "/api/searchType", {
                            _id: selectedType._id, ...res
                        })
                    } else {
                        await mRequest("POST", "/api/searchType", {
                            ...res,
                        })

                    }
                    refreshTypeList()
                    setSelectedType(undefined)
                    message.success("操作成功")
                }}
            >
                <Form.Item
                    name="name"
                    label="分类名"
                    rules={[{ required: true, message: "请输入名称" }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="includes"
                    label="启用引擎"

                >
                    <SearchSelect ></SearchSelect>
                </Form.Item>
                <Form.Item
                    name="priority"
                    label="优先级"

                >
                    <InputNumber ></InputNumber>
                </Form.Item>
                {
                    !viewMode &&
                    <Form.Item className="flex justify-end">
                        <Space>
                            <Button>
                                重置
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确认
                            </Button>
                        </Space>

                    </Form.Item>
                }

            </Form>
        </Drawer >
    </>


}