import { Button, Input, Modal } from "antd";
import WaiterRewardingIcon from "components/Icons/waiter/WaiterRewardingIcon";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAppDispatch } from "redux/hooks";
import { updateTip } from "features/order/orderSlice";

interface TipDialogProps {
  isOpen: boolean;
  onClose: () => void;
  initialValue: string;
}

export function TipDialog({ isOpen, onClose, initialValue }: TipDialogProps) {
  const { t } = useTranslation();
  const [value, setValue] = useState(initialValue);
  const dispatch = useAppDispatch();

  useEffect(() => {
    setValue(initialValue);
  }, [initialValue]);

  const handleSave = () => {
    const numAmount = parseFloat(value) || 0;
    dispatch(updateTip(numAmount.toString()));
    onClose();
  };

  const handleCancel = () => {
    setValue(initialValue);
    onClose();
  };

  return (
    <Modal
      title={t("cart.tip")}
      open={isOpen}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          {t("cart.cancel")}
        </Button>,
        <Button key="save" type="primary" onClick={handleSave}>
          {t("cart.addTip")}
        </Button>,
      ]}
      width={500}
      destroyOnHidden
    >
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <WaiterRewardingIcon />

        <br />

        <Input
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder={t("cart.amount")}
          autoFocus={false}
          size="large"
        />
      </div>
    </Modal>
  );
}
