"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@open-mercato/ui/primitives/dialog";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { RadioGroup } from "@open-mercato/ui/primitives/radio";
import { RadioField } from "@open-mercato/ui/primitives/radio-field";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function parseRecipients(raw) {
  return raw.split(/[,;\s]+/).map((s) => s.trim()).filter(Boolean);
}
function defaultChannelId(channels) {
  const primary = channels.find((c) => c.isPrimary);
  return primary?.id ?? channels[0]?.id ?? "";
}
function deriveComposeInitialState(replyTo, defaultRecipient, channels) {
  const cc = replyTo?.cc && replyTo.cc.length > 0 ? replyTo.cc.join(", ") : "";
  return {
    to: replyTo ? replyTo.to.join(", ") : defaultRecipient ?? "",
    cc,
    showCc: Boolean(cc),
    subject: replyTo?.subject ?? "",
    channelId: defaultChannelId(channels)
  };
}
function ComposeEmailDialog({
  open,
  onOpenChange,
  channels,
  defaultRecipient,
  replyTo,
  onSend
}) {
  const t = useT();
  const initial = React.useMemo(
    () => deriveComposeInitialState(replyTo, defaultRecipient, channels),
    [replyTo, defaultRecipient, channels]
  );
  const [to, setTo] = React.useState(initial.to);
  const [showCc, setShowCc] = React.useState(initial.showCc);
  const [cc, setCc] = React.useState(initial.cc);
  const [subject, setSubject] = React.useState(initial.subject);
  const [body, setBody] = React.useState("");
  const [visibility, setVisibility] = React.useState("private");
  const [channelId, setChannelId] = React.useState(initial.channelId);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    if (!open) return;
    const next = deriveComposeInitialState(replyTo, defaultRecipient, channels);
    setTo(next.to);
    setCc(next.cc);
    setShowCc(next.showCc);
    setSubject(next.subject);
    setBody("");
    setVisibility("private");
    setChannelId(next.channelId);
    setError(null);
    setBusy(false);
  }, [open, replyTo, defaultRecipient, channels]);
  const toList = React.useMemo(() => parseRecipients(to), [to]);
  const isSendDisabled = busy || toList.length === 0 || subject.trim().length === 0 || body.trim().length === 0 || !channelId;
  const handleSend = React.useCallback(async () => {
    setError(null);
    setBusy(true);
    try {
      const ccList = showCc ? parseRecipients(cc) : void 0;
      const values = {
        userChannelId: channelId,
        to: toList,
        cc: ccList && ccList.length > 0 ? ccList : void 0,
        subject: subject.trim(),
        body: body.trim(),
        bodyFormat: "text",
        visibility,
        inReplyTo: replyTo?.inReplyTo,
        references: replyTo?.references,
        parentMessageId: replyTo?.parentMessageId
      };
      await onSend(values);
      onOpenChange(false);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setError(message);
    } finally {
      setBusy(false);
    }
  }, [showCc, cc, channelId, toList, subject, body, visibility, replyTo, onSend, onOpenChange]);
  const handleKeyDown = React.useCallback(
    (event) => {
      if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
        if (!isSendDisabled) {
          void handleSend();
        }
      }
    },
    [isSendDisabled, handleSend]
  );
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-2xl", onKeyDown: handleKeyDown, children: [
    /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: replyTo ? t("customers.email.compose.replyTitle", "Reply") : t("customers.email.compose.title", "Compose email") }) }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "compose-to", children: t("customers.email.compose.to", "To") }),
          !showCc && /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "link",
              size: "2xs",
              className: "text-muted-foreground hover:text-foreground",
              onClick: () => setShowCc(true),
              "aria-label": t("customers.email.compose.addCc.ariaLabel", "Add Cc recipients"),
              children: t("customers.email.compose.addCc", "+ Cc")
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "compose-to",
            value: to,
            onChange: (e) => setTo(e.target.value),
            placeholder: t("customers.email.compose.toPlaceholder", "recipient@example.com"),
            autoComplete: "off"
          }
        )
      ] }),
      showCc && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "compose-cc", children: t("customers.email.compose.cc", "Cc") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "compose-cc",
            value: cc,
            onChange: (e) => setCc(e.target.value),
            placeholder: t("customers.email.compose.ccPlaceholder", "cc@example.com"),
            autoComplete: "off"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "compose-subject", children: t("customers.email.compose.subject", "Subject") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "compose-subject",
            value: subject,
            onChange: (e) => setSubject(e.target.value),
            placeholder: t("customers.email.compose.subjectPlaceholder", "Email subject")
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "compose-body", children: t("customers.email.compose.body", "Body") }),
        /* @__PURE__ */ jsx(
          Textarea,
          {
            id: "compose-body",
            value: body,
            onChange: (e) => setBody(e.target.value),
            placeholder: t("customers.email.compose.bodyPlaceholder", "Write your message..."),
            rows: 8
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
        /* @__PURE__ */ jsx(Label, { children: t("customers.email.compose.visibility", "Visibility") }),
        /* @__PURE__ */ jsxs(
          RadioGroup,
          {
            value: visibility,
            onValueChange: (val) => setVisibility(val),
            className: "flex flex-row gap-4",
            children: [
              /* @__PURE__ */ jsx(
                RadioField,
                {
                  value: "private",
                  label: t("customers.email.compose.visibilityPrivate", "Private to me")
                }
              ),
              /* @__PURE__ */ jsx(
                RadioField,
                {
                  value: "shared",
                  label: t("customers.email.compose.visibilityShared", "Visible to teammates")
                }
              )
            ]
          }
        )
      ] }),
      channels.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "compose-channel", children: t("customers.email.compose.sendAs", "Send as") }),
        /* @__PURE__ */ jsxs(Select, { value: channelId, onValueChange: setChannelId, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { id: "compose-channel", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("customers.email.compose.selectChannel", "Select account") }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: channels.map((ch) => /* @__PURE__ */ jsxs(SelectItem, { value: ch.id, children: [
            ch.displayName,
            ch.externalIdentifier ? ` (${ch.externalIdentifier})` : ""
          ] }, ch.id)) })
        ] })
      ] }),
      error && /* @__PURE__ */ jsx("p", { className: "text-sm text-status-error-text", role: "alert", children: error })
    ] }),
    /* @__PURE__ */ jsxs(DialogFooter, { children: [
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: () => onOpenChange(false),
          disabled: busy,
          children: t("customers.email.compose.cancel", "Cancel")
        }
      ),
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          onClick: () => void handleSend(),
          disabled: isSendDisabled,
          children: busy ? t("customers.email.compose.sending", "Sending...") : t("customers.email.compose.send", "Send")
        }
      )
    ] })
  ] }) });
}
export {
  ComposeEmailDialog
};
//# sourceMappingURL=ComposeEmailDialog.js.map
