import { sendRCIUnitEDM } from "@/lib/features/bookings/query";
import { ActionIcon, Flex, Tooltip } from "@mantine/core";
import { IconCheck, IconSend } from "@tabler/icons-react";
import { toast } from "sonner";
import { useState } from "react";

const SendEDMAction: React.FC<{
  unitId?: string;
  memberRecordID?: number | null;
  onSent?: (memberRecordID: number) => void;
}> = ({ unitId, memberRecordID, onSent }) => {
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  const disabled = !unitId || !memberRecordID || sent;

  const handleClick = async (e: React.MouseEvent) => {
    e.stopPropagation();

    if (!unitId) {
      toast.error("Unit ID missing. Cannot send EDM.");
      return;
    }

    if (!memberRecordID) {
      toast.error("Member record ID missing for this guest.");
      return;
    }

    const toastId = toast.loading("Sending EDM...");

    try {
      setLoading(true);
      const res = await sendRCIUnitEDM(unitId, memberRecordID);

      if (!res?.success) {
        toast.error(res?.message || "Failed to send EDM", { id: toastId });
        return;
      }

      setSent(true);
      onSent?.(memberRecordID);
      toast.success(res?.message || "EDM sent successfully", { id: toastId });
    } catch (err) {
      toast.error((err as Error)?.message ?? "Failed to send EDM", { id: toastId });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Flex justify="center" align="center" w="100%">
      <Tooltip label={sent ? "EDM sent" : "Send EDM"}>
        <ActionIcon
          variant="subtle"
          color={sent ? "green" : "dark"}
          radius="md"
          loading={loading}
          disabled={disabled}
          onClick={handleClick}
        >
          {sent ? <IconCheck size={16} /> : <IconSend size={16} />}
        </ActionIcon>
      </Tooltip>
    </Flex>
  );
};

export default SendEDMAction;