import { InfoCircleFilled } from "@ant-design/icons";
import {
  Button,
  InputNumber,
  type InputNumberProps,
  Select,
  type SelectProps,
  Tooltip,
} from "antd";
import { useState } from "react";

import { fetchStrings, Region } from "@/api";
import {
  Attribute2StringCodeMap,
  Race2StringCodeMap,
  Type2StringCodeMap,
} from "@/common";
import { FtsConditions } from "@/middleware/sqlite/fts";

import styles from "./Filter.module.scss";

const options: SelectProps["options"] = [];

const levels = Array.from({ length: 12 }).map((_, index) => index + 1);

for (let i = 10; i < 36; i++) {
  options.push({
    label: i.toString(36) + i,
    value: i.toString(36) + i,
  });
}

export const Filter: React.FC<{
  conditions: FtsConditions;
  onConfirm: (newConditons: FtsConditions) => void;
  onCancel: () => void;
}> = ({ conditions, onConfirm, onCancel }) => {
  const [newConditions, setNewConditions] = useState<FtsConditions>(conditions);
  return (
    <>
      <div className={styles.title}>卡片筛选</div>
      <div className={styles.form}>
        <div className={styles.item}>
          <div className={styles["item-name"]}>属性</div>
          <Select
            mode="multiple"
            allowClear
            style={{ width: "100%" }}
            placeholder="请选择"
            options={Array.from(Attribute2StringCodeMap.entries()).map(
              ([key, value]) => ({
                value: key,
                label: fetchStrings(Region.System, value),
              })
            )}
            defaultValue={conditions.attributes ?? []}
            onChange={(values) => {
              // @ts-ignore
              setNewConditions((prev) => {
                prev.attributes = values;
                return prev;
              });
            }}
          />
        </div>
        <div className={styles.item}>
          <div className={styles["item-name"]}>星级</div>
          <Select
            mode="multiple"
            allowClear
            style={{ width: "100%" }}
            placeholder="请选择"
            options={levels.map((level) => ({
              value: level,
              label: level.toString(),
            }))}
            defaultValue={conditions.levels ?? []}
            onChange={(values) => {
              // @ts-ignore
              setNewConditions((prev) => {
                prev.levels = values;
                return prev;
              });
            }}
          />
        </div>
        <div className={styles.item}>
          <div className={styles["item-name"]}>种族</div>
          <Select
            mode="multiple"
            allowClear
            style={{ width: "100%" }}
            placeholder="请选择"
            options={Array.from(Race2StringCodeMap.entries()).map(
              ([key, value]) => ({
                value: key,
                label: fetchStrings(Region.System, value),
              })
            )}
            defaultValue={conditions.races ?? []}
            onChange={(values) => {
              // @ts-ignore
              setNewConditions((prev) => {
                prev.races = values;
                return prev;
              });
            }}
          />
        </div>
        <div className={styles.item}>
          <div className={styles["item-name"]}>类型</div>
          <Select
            mode="multiple"
            allowClear
            style={{ width: "100%" }}
            placeholder="请选择"
            options={Array.from(Type2StringCodeMap.entries()).map(
              ([key, value]) => ({
                value: key,
                label: fetchStrings(Region.System, value),
              })
            )}
            defaultValue={conditions.types ?? []}
            onChange={(values) => {
              // @ts-ignore
              setNewConditions((prev) => {
                prev.types = values;
                return prev;
              });
            }}
          />
        </div>
        <div className={styles.item}>
          <div className={styles["item-name"]}>
            攻击
            <Tooltip title="输入-1即等同于输入“?”">
              <InfoCircleFilled style={{ fontSize: 10 }} />
            </Tooltip>
          </div>
          <div className={styles.number}>
            <CustomInputNumber
              min={-1}
              max={1000000}
              step={100}
              placeholder="最小值"
              defaultValue={conditions.atk?.[0]}
              onChange={(value) => {
                setNewConditions((prev) => {
                  // TODO: 下面这些逻辑有时间可以去重一下
                  if (value === null) {
                    prev.atk = undefined;
                  } else {
                    if (prev.atk) {
                      prev.atk[0] = value;
                    } else {
                      prev.atk = [value, 9999];
                    }
                  }
                  return prev;
                });
              }}
            />
            <span className={styles.divider}>~</span>
            <CustomInputNumber
              min={-1}
              max={1000000}
              step={100}
              placeholder="最大值"
              defaultValue={conditions.atk?.[1]}
              onChange={(value) => {
                setNewConditions((prev) => {
                  if (value === null) {
                    prev.atk = undefined;
                  } else {
                    if (prev.atk) {
                      prev.atk[1] = value;
                    } else {
                      prev.atk = [0, value];
                    }
                  }
                  return prev;
                });
              }}
            />
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles["item-name"]}>守备</div>
          <div className={styles.number}>
            <CustomInputNumber
              min={-1}
              max={1000000}
              step={100}
              placeholder="最小值"
            />
            <span className={styles.divider}>~</span>
            <CustomInputNumber
              min={-1}
              max={1000000}
              step={100}
              placeholder="最大值"
            />
          </div>
        </div>
      </div>
      <div className={styles.btns}>
        <Button type="primary" onClick={() => onConfirm(newConditions)}>
          确定
        </Button>
        <Button type="text" onClick={onCancel}>
          取&nbsp;消
        </Button>
      </div>
    </>
  );
};

/** 只支持输入整数 */
const CustomInputNumber = (props: InputNumberProps) => {
  const [value, setValue] = useState(props.defaultValue);
  const onChange = (newValue: string | number | null) => {
    if (Number.isInteger(newValue)) {
      setValue(newValue as number);
      if (props.onChange) {
        props.onChange(newValue);
      }
    }
  };
  return (
    <InputNumber
      {...props}
      value={value}
      formatter={(value) => (value !== undefined ? String(value) : "")}
      parser={(value) => (value !== undefined ? value.replace(/\D/g, "") : "")}
      onChange={onChange}
      min={-1}
      max={1000000}
      step={100}
    />
  );
};
