import { DownOutlined } from "@ant-design/icons";
import { Button, Divider, Dropdown, InputNumber, Space, theme } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";

const DISCOUNT_PRESETS = [5, 10, 15, 20, 25, 40];

export default function PartsOrderModalPriceChange({ form, field }) {
  const { t } = useTranslation();
  const { token } = theme.useToken();

  const [open, setOpen] = useState(false);
  const [customPercent, setCustomPercent] = useState(0);

  const applyDiscountPercent = (percent) => {
    const pct = Number(percent) || 0;

    const values = form.getFieldsValue();
    const parts_order_lines = values?.parts_order_lines;
    const data = Array.isArray(parts_order_lines?.data) ? parts_order_lines.data : [];
    if (!data.length) return;

    form.setFieldsValue({
      parts_order_lines: {
        data: data.map((p, idx) => {
          if (idx !== field.name) return p;
          return {
            ...p,
            act_price: (p.act_price || 0) * ((100 - pct) / 100)
          };
        })
      }
    });
  };

  const applyCustom = () => {
    logImEXEvent("parts_order_manual_discount", {});
    applyDiscountPercent(customPercent);
    setCustomPercent(0);
    setOpen(false);
  };

  const menu = {
    // Kill the menu “card” styling so our wrapper becomes the single card.
    style: {
      background: "transparent",
      boxShadow: "none"
    },
    items: DISCOUNT_PRESETS.map((pct) => ({
      key: String(pct),
      label: t("parts_orders.labels.discount", { percent: `${pct}%` })
    })),
    onClick: ({ key }) => {
      logImEXEvent("parts_order_manual_discount", {});
      applyDiscountPercent(key);
      setOpen(false);
    }
  };

  return (
    <Dropdown
      menu={menu}
      trigger={["click"]}
      open={open}
      onOpenChange={(nextOpen) => setOpen(nextOpen)}
      getPopupContainer={(triggerNode) => triggerNode?.parentElement ?? document.body}
      popupRender={(menus) => (
        <div
          // This makes the whole dropdown (menu + footer) look like one panel in both light/dark.
          style={{
            background: token.colorBgElevated,
            borderRadius: token.borderRadiusLG,
            boxShadow: token.boxShadowSecondary,
            overflow: "hidden",
            minWidth: 180
          }}
          onClick={(e) => e.stopPropagation()}
          onKeyDown={(e) => e.stopPropagation()}
        >
          {menus}

          <Divider style={{ margin: 0 }} />

          <div style={{ padding: token.paddingXS }}>
            <Space.Compact style={{ width: "100%" }}>
              <InputNumber
                value={customPercent}
                min={0}
                max={100}
                precision={0}
                controls={false}
                style={{ width: "100%" }}
                formatter={(v) => (v === null || v === undefined ? "" : `${v}%`)}
                parser={(v) =>
                  String(v ?? "")
                    .replace("%", "")
                    .trim()
                }
                onChange={(v) => setCustomPercent(v ?? 0)}
                onKeyDown={(e) => {
                  e.stopPropagation();
                  if (e.key === "Enter") {
                    e.preventDefault();
                    applyCustom();
                  }
                }}
              />
              <Button type="primary" onClick={applyCustom}>
                {t("general.labels.apply")}
              </Button>
            </Space.Compact>
          </div>
        </div>
      )}
    >
      <Space>
        % <DownOutlined />
      </Space>
    </Dropdown>
  );
}
