import { useEffect, useRef, useState } from "react";
import { Input, Text, View } from "@tarojs/components";
import { Icon, IconNames } from "@/components";
import { formatCurrency } from "@/utils";

interface PriceEditorProps {
  value: number;
  onSave: (value: number) => void;
  readOnly?: boolean;
  label?: string;
  unit?: string;
  icon?: IconNames;
  hint?: string;
  // 是否负数
  negative?: boolean;
}

export default function PriceEditor(props: PriceEditorProps) {
  const {
    value,
    onSave,
    readOnly,
    label = "销售单价",
    unit = "元/斤",
    icon = "money-bill",
    hint = "点击销售单价可直接编辑",
    negative = false,
  } = props;

  // 控制区域是否处于编辑状态
  const [isEditing, setIsEditing] = useState(false);
  // 输入值
  const [inputValue, setInputValue] = useState("");
  // 输入框引用
  const inputRef = useRef<any>(null);

  // 当开始编辑时，设置初始值并聚焦输入框
  useEffect(() => {
    if (isEditing) {
      if (value == 0) {
        setInputValue("");
      } else {
        setInputValue(value.toString());
      }
      // 聚焦到输入框
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus();
        }
      }, 0);
    }
  }, [isEditing]);

  // 处理输入变化
  const handleInputChange = (e: any) => {
    const val = e.detail?.value || e.target?.value || "";
    // 只允许数字和小数点
    if (/^\d*\.?\d*$/.test(val) || val === "") {
      setInputValue(val);
    }
  };

  // 保存编辑
  const saveEdit = () => {
    if (inputValue !== "" && !Number.isNaN(Number(inputValue))) {
      const newValue = Number(inputValue);
      onSave(newValue);
    }
    setIsEditing(false);
  };

  // 清空输入
  const clearValue = (e: any) => {
    e.stopPropagation();
    setInputValue("");
    onSave(0);
  };

  return (
    <>
      {!readOnly ? (
        <View className="flex flex-1 flex-col justify-between">
          <View className="mb-2 flex items-center justify-between">
            <Text className="flex flex-row text-sm text-gray-500">
              <Icon name={icon} size={14} className="mr-1" />
              {label}
            </Text>
            <Text className="text-sm text-gray-500">{unit}</Text>
          </View>
          {isEditing ? (
            <View className="relative flex flex-1 items-end">
              <View className="input-bold flex h-10 w-full items-center border-b-2 border-red-500 !pb-2 text-3xl font-bold text-red-500 focus:outline-none">
                {negative && <View>-</View>}
                <Input
                  ref={inputRef}
                  type="digit"
                  value={inputValue}
                  onInput={handleInputChange}
                  onBlur={saveEdit}
                />
                {inputValue !== "" && (
                  <Icon
                    name="circle-xmark"
                    size={20}
                    className="ml-2 cursor-pointer"
                    onClick={clearValue}
                  />
                )}
              </View>
            </View>
          ) : (
            <View
              className="relative flex flex-1 items-end"
              onClick={() => setIsEditing(true)}
            >
              <Text className="h-10 w-full border-b-2 border-red-500 pb-2 text-3xl font-bold text-red-500 focus:outline-none">
                {negative && "-"}
                {formatCurrency(value || 0)}
              </Text>
              <Icon
                name={value !== 0 ? "circle-xmark" : "pen-to-square"}
                size={20}
                className="absolute right-0 bottom-2 ml-2 cursor-pointer"
                onClick={(event) => {
                  if (value !== 0) {
                    clearValue(event);
                  } else {
                    setIsEditing(true);
                  }
                }}
              />
            </View>
          )}
          <View className="mt-1 text-xs text-gray-400">{hint}</View>
        </View>
      ) : (
        <View className="flex flex-1 flex-col justify-between">
          <View className="mb-2 flex items-center justify-between">
            <Text className="flex flex-row text-sm text-gray-500">
              <Icon name={icon} size={14} className="mr-1" />
              {label}
            </Text>
            <Text className="text-sm text-gray-500">{unit}</Text>
          </View>
          <View className="relative">
            <Text className="w-full py-2 text-3xl font-bold text-red-500">
              {Number.isNaN(value) ? "" : formatCurrency(value)}
            </Text>
          </View>
        </View>
      )}
    </>
  );
}
