"use client";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { PhoneInput } from "@/components/ui/inputs/phone-input";
import { Textarea } from "@/components/ui/textarea";
import { composeReplyBody, REPLY_CHANNEL_MAP, replyTicket } from "@/lib/api/dashboard/tickets-api";
import { cn } from "@/lib/utils";
import {
  AlignRight,
  Bold,
  Italic,
  Link2,
  List,
  ListOrdered,
  Paperclip,
  Pilcrow,
  Underline,
  X,
} from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useMemo, useState } from "react";
import type {
  DashboardTicketItem,
  TicketReplyChannel,
} from "./tickets-types";

interface TicketReplyDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  ticket: DashboardTicketItem | null;
  channel: TicketReplyChannel;
  onSent: () => void;
}

export function TicketReplyDialog({
  open,
  onOpenChange,
  ticket,
  channel,
  onSent,
}: TicketReplyDialogProps) {
  const t = useTranslations("dashboard.tickets.reply");
  const locale = useLocale();
  const isRtl = locale === "ar";

  const initialRecipient =
    channel === "gmail"
      ? ticket?.email || ""
      : `${ticket?.country_dial_code ?? ""}${ticket?.phone ?? ""}`;

  const [recipient, setRecipient] = useState(initialRecipient);
  const [subject, setSubject] = useState("");
  const [content, setContent] = useState("");

  const title =
    channel === "gmail"
      ? t("channels.gmail")
      : t("channels.whatsapp");

  const [isSubmitting, setIsSubmitting] = useState(false);

  const canSend = Boolean(recipient.trim() && subject.trim() && content.trim());

  const toolbarButtons = useMemo(
    () => [
      { icon: Link2, label: "insert-link" },
      { icon: Paperclip, label: "attach-file" },
      { icon: ListOrdered, label: "ordered-list" },
      { icon: List, label: "unordered-list" },
      { icon: AlignRight, label: "align-right" },
      { icon: Underline, label: "underline" },
      { icon: Italic, label: "italic" },
      { icon: Bold, label: "bold" },
    ],
    []
  );

  useEffect(() => {
    setRecipient(initialRecipient);
  }, [initialRecipient]);

  const handleSend = async () => {
    if (!ticket) return;
    setIsSubmitting(true);
    try {
      await replyTicket(ticket.id, {
        body: composeReplyBody(subject, content),
        channel: REPLY_CHANNEL_MAP[channel],
      });
      onSent();
      onOpenChange(false);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!ticket) {
    return null;
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        showCloseButton={false}
        className="max-w-[760px] gap-0 overflow-hidden rounded-2xl border border-border bg-card p-0"
      >
        <header className="flex h-[72px] items-center justify-between border-b border-border px-6">
          <DialogClose asChild>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="h-8 w-8 rounded-[10px] border border-border text-muted-foreground"
              aria-label="close reply dialog"
            >
              <X className="h-4 w-4" />
            </Button>
          </DialogClose>

          <DialogTitle className="text-xl font-bold text-foreground">
            {title}
          </DialogTitle>
        </header>

        <div className="space-y-6 px-6 py-6">
          <div className="space-y-2">
            <p className="text-sm font-bold text-foreground">
              {t("fields.recipient")} <span className="text-destructive">*</span>
            </p>

            {channel === "whatsapp" ? (
              <PhoneInput
                value={recipient}
                onChange={setRecipient}
                placeholder={t("placeholders.recipientPhone")}
                className="h-12 rounded-xl"
              />
            ) : (
              <Input
                value={recipient}
                onChange={(event) => setRecipient(event.target.value)}
                className="h-12 rounded-xl border-border"
                placeholder={t("placeholders.recipientEmail")}
              />
            )}
          </div>

          <div className="space-y-2">
            <p className="text-sm font-bold text-foreground">
              {t("fields.subject")} <span className="text-destructive">*</span>
            </p>
            <Input
              value={subject}
              onChange={(event) => setSubject(event.target.value)}
              className="h-12 rounded-xl border-border"
              placeholder={t("placeholders.subject")}
            />
          </div>

          <div className="space-y-2">
            <p className="text-sm font-bold text-foreground">
              {t("fields.content")} <span className="text-destructive">*</span>
            </p>

            <div className="overflow-hidden rounded-xl border border-border">
              <div
                className={cn(
                  "flex flex-wrap items-center gap-1 border-b border-border px-2 py-2",
                  isRtl ? "" : "justify-start"
                )}
              >
                {toolbarButtons.map((item) => {
                  const Icon = item.icon;

                  return (
                    <Button
                      key={item.label}
                      type="button"
                      variant="ghost"
                      size="icon-sm"
                      className="h-8 w-8 rounded-lg text-muted-foreground"
                    >
                      <Icon className="h-4 w-4" />
                    </Button>
                  );
                })}

                <div className="flex h-8 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">
                  <span>{t("toolbar.paragraph")}</span>
                  <Pilcrow className="h-3.5 w-3.5" />
                </div>
              </div>

              <Textarea
                value={content}
                onChange={(event) => setContent(event.target.value)}
                className="min-h-[140px] resize-y rounded-none border-0 focus-visible:ring-0"
                placeholder={t("placeholders.content")}
              />
            </div>
          </div>

          <div className="flex items-center gap-3 pb-2">
            <Button
              type="button"
              variant="outline"
              className="h-12 min-w-[96px] rounded-xl border-primary text-primary"
              onClick={() => onOpenChange(false)}
            >
              {t("actions.cancel")}
            </Button>

            <Button
              type="button"
              className="h-12 min-w-[96px] rounded-xl bg-primary text-white hover:bg-primary/90"
              disabled={!canSend || isSubmitting}
              onClick={handleSend}
            >
              {t("actions.send")}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
