"use client";
import ViewCustomerDetail from "@/components/manage-customer/view-customer-detail";
import AppInput from "@/components/ui/input";
import AppModal from "@/components/ui/modal";
import AppTable, {ColumnsType} from "@/components/ui/table";
import useFetchCustomer from "@/hooks/useFetchCustomer";
import {SortDirection, SortField} from "@/types/common";
import {Customer, CustomerQueryParams} from "@/types/customer";
import {SearchOutlined} from "@ant-design/icons";
import React, {useEffect, useState} from "react";
import {debounce} from "lodash";
import AppTypography from "@/components/ui/typography";
import {useTranslations} from "next-intl";
import {renderSorterTooltip} from "@/lib/utils";

type ManageCustomerTableProps = {
    appId: string;
};

const ManageCustomerTable = ({appId}: ManageCustomerTableProps) => {
    const t = useTranslations("AppPage.customer");

    const [isOpenViewCustomerModal, setIsOpenViewCustomerModal] = useState(false);

    const [sortState, setSortState] = useState<{
        columnKey: string | null;
        order: 'ascend' | 'descend' | null;
    }>({
        columnKey: null,
        order: null,
    });

    const defaultQueryParams: CustomerQueryParams = {
        pageNumber: 1,
        pageSize: 10,
        sortField: SortField.createdTime,
        sortDirection: SortDirection.DESC,
    };

    const {
        customers,
        customerPaging,
        isFetchingCustomer,
        fetchCustomerPaging,
        customerQuery,
        setCustomerQuery,
    } = useFetchCustomer(defaultQueryParams);

    useEffect(() => {
        (async () => {
            if (!appId) {
                return;
            }
            await fetchCustomerPaging({...customerQuery, appsId: appId});
        })();
    }, [appId, customerQuery]);

    const handleSearch = debounce((e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value.trim();
        setCustomerQuery({...customerQuery, searchKeyEmail: value, pageNumber: 1});
    }, 500);

    const handleTableChange = (pagination: any, filters: any, sorter: any) => {
        let queryParams = {...customerQuery};
        if (sorter && sorter.columnKey && sorter.order) {
            setSortState({
                columnKey: sorter.columnKey,
                order: sorter.order,
            })
            queryParams = {
                ...queryParams,
                sortField: sorter.columnKey,
                sortDirection:
                    sorter.order === "ascend" ? SortDirection.ASC : SortDirection.DESC,
            };
        } else {
            setSortState({
                order: null,
                columnKey: null,
            });
        }
        queryParams = {
            ...queryParams,
            pageNumber: pagination.current,
            pageSize: pagination.pageSize,
        };
        setCustomerQuery(queryParams);
    };

    const handleCloseViewCustomerModal = () => {
        setIsOpenViewCustomerModal(false);
    };

    const columns: ColumnsType<Customer> = [
        {
            title: t("email"),
            dataIndex: "email",
            key: "email",
            sorter: true,
            showSorterTooltip: {
                title: renderSorterTooltip(t, sortState, "email"),
            },
        },
        {
            title: t("full_name"),
            dataIndex: "username",
            key: "username",
            sorter: true,
            showSorterTooltip: {
                title: renderSorterTooltip(t, sortState, "username"),
            },
            render: (_, {firstName, lastName}) => {
                return `${firstName || ""} ${lastName || ""}`;
            },
        },
        {
            title: t("created_time"),
            dataIndex: "createdTime",
            key: "createdTime",
            sorter: true,
            showSorterTooltip: {
                title: renderSorterTooltip(t, sortState, "createdTime"),
            },
            render: (time: number) => {
                return new Date(time).toLocaleString();
            },
        },
    ];
    return (
        <>
            <AppTypography type="title" level={3}>
                {t("title")}
            </AppTypography>
            <div className="max-w-[300px] mb-4">
                <AppInput
                    placeholder={t("email_placeholder")}
                    prefix={<SearchOutlined/>}
                    onChange={handleSearch}
                    allowClear
                />
            </div>
            <AppTable<Customer>
                columns={columns}
                dataSource={customers}
                loading={isFetchingCustomer}
                pagination={{
                    current: customerPaging.pageNumber,
                    pageSize: customerPaging.pageSize,
                    total: customerPaging.totalElements,
                }}
                rowKey="id"
                scroll={{x: 1000}}
                onChange={handleTableChange}
            />

            <AppModal
                title="Customer detail"
                isOpen={isOpenViewCustomerModal}
                handleCancel={() => handleCloseViewCustomerModal()}
            >
                <ViewCustomerDetail/>
            </AppModal>
        </>
    );
};

export default ManageCustomerTable;
