import { Popup, SafeArea, SearchBar } from "@nutui/nutui-react-taro";
import { Icon } from "@/components";
import { ScrollView, View } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import { business } from "@/services";

interface IDealerWarehousePickerProps {
  onFinish: (dealerWarehouseVO: BusinessAPI.DealerWarehouseVO) => void;
  trigger: React.ReactNode;
  dealerId?: BusinessAPI.DealerWarehouseVO["dealerId"];
  accountId?: BusinessAPI.DealerWarehouseVO["accountId"];
}

export default function DealerWarehousePicker(
  props: IDealerWarehousePickerProps,
) {
  const { onFinish, trigger, dealerId, accountId } = props;

  const [visible, setVisible] = useState(false);
  const [dealerWarehouseVO, setDealerWarehouseVO] =
    useState<BusinessAPI.DealerWarehouseVO>();
  const [dealerWarehouseList, setDealerWarehouseList] = useState<
    BusinessAPI.DealerWarehouseVO[]
  >([]);
  const [searchText, setSearchText] = useState("");

  useEffect(() => {
    if (visible) {
      handleSearch().then();
    }
  }, [visible]);

  const handleSearch = async (value?: string) => {
    const { data } = await business.dealerWarehouse.listDealerWarehouse({
      dealerWarehouseListQry: {
        name: value || undefined,
        dealerId: dealerId,
        accountId: accountId,
        status: true,
      },
    });

    let dealerWarehouseList = data?.data;
    setDealerWarehouseList(dealerWarehouseList || []);
  };

  return (
    <>
      <View
        className={"flex flex-1 flex-row items-center justify-between px-5"}
        style={{
          color: "var(--nutui-color-title, #1a1a1a)",
        }}
        onClick={(event) => {
          setVisible(true);
          event.stopPropagation();
        }}
      >
        {trigger}
      </View>

      {/* 选择经销商仓库 */}
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        closeable
        destroyOnClose
        visible={visible}
        title="选择仓库"
        position="bottom"
        onClose={async () => {
          if (visible) {
            setDealerWarehouseVO(undefined);
            setSearchText("");
            setVisible(false);
          } else if (dealerWarehouseVO) {
            onFinish(dealerWarehouseVO);
          }
        }}
      >
        <SearchBar
          className={"!px-2.5 !py-1"}
          placeholder="请输入仓库名称搜索"
          value={searchText}
          onChange={(value) => setSearchText(value)}
          onSearch={handleSearch}
          onClear={() => handleSearch("")}
        />
        <ScrollView scrollY className="h-96">
          <View className={"flex flex-col px-2.5"}>
            {dealerWarehouseList?.length === 0 && (
              <View className={"flex flex-col items-center gap-2 p-5"}>
                <View className={"text-sm"}>未找到匹配的仓库</View>
              </View>
            )}
            {dealerWarehouseList?.map((dealerWarehouseVO) => (
              <View
                className={
                  "flex flex-row items-center justify-between gap-2 border-b border-gray-100 p-2.5"
                }
                key={dealerWarehouseVO.warehouseId}
                onClick={async () => {
                  setDealerWarehouseVO(dealerWarehouseVO);
                  setSearchText("");
                  setVisible(false);
                }}
              >
                <View className={"flex flex-1 flex-col gap-1"}>
                  <View className={"text-base font-medium"}>
                    {dealerWarehouseVO.name}
                  </View>
                  <View className={"text-neutral-dark text-xs"}>
                    {dealerWarehouseVO.address}
                  </View>
                </View>

                <Icon name={"chevron-right"} size={16} />
              </View>
            ))}
          </View>
        </ScrollView>

        <SafeArea position={"bottom"} />
      </Popup>
    </>
  );
}
