import {
  Dialog,
  Input,
  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 IDealerPickerProps {
  onFinish: (dealerVO: BusinessAPI.DealerVO) => void;
  trigger: React.ReactNode;
  enableManualInput?: boolean;
}

export default function DealerPicker(props: IDealerPickerProps) {
  const { onFinish, trigger, enableManualInput = true } = props;

  const [visible, setVisible] = useState(false);
  const [dealerVO, setDealerVO] = useState<BusinessAPI.DealerVO>();
  const [dealerList, setDealerList] = useState<BusinessAPI.DealerVO[]>([]);
  const [searchText, setSearchText] = useState("");
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState("");

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

  const handleSearch = async (value?: string) => {
    const { data } = await business.dealer.listDealer({
      dealerListQry: {
        shortName: value || undefined,
        status: true,
      },
    });

    console.log("data", data);

    let dealerList = data?.data;
    setDealerList(dealerList || []);
  };

  const handleConfirm = () => {
    if (inputValue.trim()) {
      // 创建一个模拟的DealerVO对象，只包含用户输入的名称
      const mockDealer: any = {
        dealerId: "",
        shortName: inputValue.trim(),
        status: true,
      };
      onFinish(mockDealer);
      setSearchText("");
      setInputVisible(false);
      setVisible(false);
    }
  };

  return (
    <>
      <View
        className={"flex flex-1 flex-row items-center justify-between"}
        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) {
            setDealerVO(undefined);
            setSearchText("");
            setVisible(false);
          } else if (dealerVO) {
            onFinish(dealerVO);
          }
        }}
      >
        <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"}>
            {dealerList?.length === 0 && (
              <View className={"flex flex-col items-center gap-2 p-5"}>
                <View className={"text-sm"}>未找到匹配的经销商</View>
              </View>
            )}
            {dealerList?.map((dealer) => (
              <View
                className={
                  "flex flex-row items-center justify-between gap-2 border-b border-gray-100 p-2.5"
                }
                key={dealer.dealerId}
                onClick={async () => {
                  setDealerVO(dealer);
                  setSearchText("");
                  setVisible(false);
                }}
              >
                <View className={"flex flex-1 flex-col gap-1"}>
                  <View className={"text-base font-medium"}>
                    {dealer.shortName}
                  </View>
                </View>

                <Icon name={"chevron-right"} size={16} />
              </View>
            ))}
            {enableManualInput && (
              <View
                className={
                  "flex flex-row items-center justify-center gap-2 border-b border-gray-100 p-4"
                }
                onClick={() => setInputVisible(true)}
              >
                <View className={"text-primary cursor-pointer text-sm"}>
                  没有找到目标经销商？点击这里手动输入
                </View>
              </View>
            )}
          </View>
        </ScrollView>
        <SafeArea position={"bottom"} />
      </Popup>

      <Dialog
        visible={inputVisible}
        title="手动输入经销商"
        content={
          <View
            className={`flex h-10 w-full items-center rounded-md border-4 border-gray-300`}
          >
            <Input
              clearable
              type="text"
              placeholder="请输入经销商名称"
              value={inputValue}
              onChange={(value) => setInputValue(value)}
            />
          </View>
        }
        onCancel={() => setInputVisible(false)}
        onConfirm={handleConfirm}
      />
    </>
  );
}
