import { useState } from "react";
import { businesses } from "@/mocks/dshn";
import {
  chatListItems,
  chatThreads,
  type ChatStatusKey,
  type ChatThread,
  type ChatThreadMessage,
} from "@/mocks/dshnChatThreads";
import { useWeb } from "../WebContext";
import { WBtn, WCard, EmptyWeb, cn } from "../WebUI";
import ChatStatusBadge from "@/pages/app/components/ChatStatusBadge";
import ChatMessageRow from "../components/ChatMessageRow";

const FALLBACK_SLUG = "al-reem";

export default function Chats() {
  const { t, params, navigate } = useWeb();
  const [activeId, setActiveId] = useState(params.chatId ?? FALLBACK_SLUG);
  const thread: ChatThread = chatThreads[activeId] ?? chatThreads[FALLBACK_SLUG];
  const activeBiz = businesses.find((b) => b.id === thread.businessId);

  const [msgMap, setMsgMap] = useState<Record<string, ChatThreadMessage[]>>(() =>
    Object.fromEntries(Object.entries(chatThreads).map(([k, v]) => [k, v.messages])),
  );
  const [approvedMap, setApprovedMap] = useState<Record<string, boolean>>(() =>
    Object.fromEntries(Object.entries(chatThreads).map(([k, v]) => [k, v.invoiceApproved ?? false])),
  );

  const [input, setInput] = useState("");
  const [pinnedOpen, setPinnedOpen] = useState(true);
  const [menu, setMenu] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);

  const messages = msgMap[activeId] ?? [];
  const approved = approvedMap[activeId] ?? false;
  const isNew = thread.mode === "new";
  const showActions = thread.mode === "invoiced" && !approved;
  const showCart = approved || thread.mode === "agreed";
  const statusKey: ChatStatusKey = approved ? "agreed" : thread.status;

  const send = () => {
    if (isNew || !input.trim()) return;
    setMsgMap((m) => ({
      ...m,
      [activeId]: [
        ...(m[activeId] ?? []),
        { id: `m${Date.now()}`, from: "me", type: "text", text: input.trim(), time: "الآن" },
      ],
    }));
    setInput("");
  };

  const confirmApprove = () => {
    setApprovedMap((a) => ({ ...a, [activeId]: true }));
    setMsgMap((m) => ({
      ...m,
      [activeId]: [
        ...(m[activeId] ?? []),
        {
          id: `sys${Date.now()}`,
          from: "them",
          type: "system",
          text: "تم الاتفاق — تم نقل المنتجات للسلة بسعر الفاتورة",
          time: "الآن",
        },
      ],
    }));
    setConfirmOpen(false);
  };

  if (chatListItems.length === 0) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <WCard className="w-full max-w-[420px]">
          <EmptyWeb
            icon="ri-chat-3-line"
            title={t("noChatsTitle")}
            desc={t("noChatsDesc")}
            actionLabel={t("browseProducts")}
            onAction={() => navigate("products")}
          />
        </WCard>
      </div>
    );
  }

  return (
    <div className="h-screen flex flex-col animate-fade-in">
      <div className="flex-1 min-h-0 w-full px-4 md:px-8 py-6">
        <div className="h-full max-w-[1320px] mx-auto flex flex-col lg:flex-row gap-6">
          {/* list */}
          <aside className="w-full lg:w-[360px] shrink-0 flex flex-col">
            <h1 className="text-[22px] font-bold text-foreground-950 font-heading">{t("chats")}</h1>
            <p className="text-[12.5px] text-foreground-600 mt-1 mb-4">{t("chatsSubtitle")}</p>
            <WCard className="flex-1 overflow-y-auto p-2">
              {chatListItems.map((c) => {
                const b = businesses.find((x) => x.id === c.businessId);
                return (
                  <button
                    key={c.slug}
                    type="button"
                    onClick={() => {
                      setActiveId(c.slug);
                      setMenu(false);
                      setInput("");
                    }}
                    className={cn(
                      "w-full flex items-start gap-3 rounded-[16px] p-3 text-start cursor-pointer transition-colors",
                      activeId === c.slug ? "bg-background-200" : "hover:bg-background-100",
                    )}
                  >
                    <div className="relative w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
                      {b && <img src={b.logo} alt={b.name} className="w-full h-full object-cover object-top" />}
                      {c.unread > 0 && (
                        <span className="absolute -top-0.5 -start-0.5 min-w-[18px] h-[18px] px-1 rounded-full bg-primary-500 text-background-50 text-[10px] font-bold flex items-center justify-center">
                          {c.unread}
                        </span>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-2">
                        <p className="text-[14px] font-semibold text-foreground-950 truncate">{b?.name}</p>
                        <span className="text-[11px] text-foreground-500 shrink-0 whitespace-nowrap">{c.time}</span>
                      </div>
                      <div className="mt-1.5">
                        <ChatStatusBadge status={c.status} />
                      </div>
                      <p
                        className={cn(
                          "text-[12px] truncate mt-1.5",
                          c.lastMessageMuted ? "text-foreground-500" : "text-foreground-600",
                        )}
                      >
                        {c.lastMessage}
                      </p>
                    </div>
                  </button>
                );
              })}
            </WCard>
          </aside>

          {/* conversation */}
          <section className="flex-1 min-w-0 flex flex-col">
            <WCard className="flex-1 min-h-0 flex flex-col overflow-hidden">
              {/* header */}
              <div className="flex items-center gap-3 px-5 py-4 border-b border-background-200">
                <div className="w-11 h-11 rounded-full overflow-hidden bg-background-200 shrink-0">
                  {activeBiz && (
                    <img src={activeBiz.logo} alt={activeBiz.name} className="w-full h-full object-cover object-top" />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[15px] font-semibold text-foreground-950 truncate">{activeBiz?.name}</p>
                  <div className="mt-0.5">
                    <ChatStatusBadge status={statusKey} />
                  </div>
                </div>
                <div className="relative">
                  <button
                    type="button"
                    onClick={() => setMenu((m) => !m)}
                    className="w-10 h-10 rounded-full hover:bg-background-200 flex items-center justify-center cursor-pointer"
                  >
                    <i className="ri-more-2-fill text-[18px] leading-none" />
                  </button>
                  {menu && (
                    <div className="absolute end-0 top-[calc(100%+6px)] w-52 bg-background-100 border border-background-200 rounded-[14px] p-1.5 z-20">
                      <button
                        type="button"
                        onClick={() => {
                          setMenu(false);
                          navigate("business", { businessId: thread.businessId });
                        }}
                        className="w-full h-9 px-3 rounded-[10px] flex items-center gap-2 text-[13px] font-medium text-foreground-800 hover:bg-background-200 cursor-pointer"
                      >
                        <i className="ri-store-2-line text-[16px] leading-none" />
                        {t("reviewBusinessPage")}
                      </button>
                      <button
                        type="button"
                        onClick={() => {
                          setMenu(false);
                          navigate("dispute", { orderId: "1045" });
                        }}
                        className="w-full h-9 px-3 rounded-[10px] flex items-center gap-2 text-[13px] font-medium text-danger-600 hover:bg-danger-50 cursor-pointer"
                      >
                        <i className="ri-alert-line text-[16px] leading-none" />
                        {t("openDispute")}
                      </button>
                    </div>
                  )}
                </div>
              </div>

              {/* pinned products */}
              <div className="px-5 py-3 border-b border-background-200 bg-accent-50">
                <button
                  type="button"
                  onClick={() => setPinnedOpen((v) => !v)}
                  className="flex w-full items-center gap-1.5 cursor-pointer"
                >
                  <i className="ri-pin-distance-line text-[15px] leading-none text-accent-800" />
                  <span className="text-[12.5px] font-semibold text-accent-900">{t("requestedProducts")}</span>
                  <i
                    className={cn(
                      "ri-arrow-down-s-line ms-auto text-[18px] leading-none text-accent-800 transition-transform",
                      pinnedOpen ? "rotate-180" : "",
                    )}
                  />
                </button>
                {pinnedOpen && (
                  <ul className="mt-2.5 flex flex-wrap gap-2.5">
                    {thread.pinned.map((it) => (
                      <li
                        key={it.name}
                        className="flex items-center gap-2.5 rounded-full border border-accent-200 bg-background-100 ps-1.5 pe-3.5 py-1.5"
                      >
                        <span className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-background-200">
                          <img src={it.image} alt={it.name} className="h-full w-full object-cover object-top" />
                        </span>
                        <span className="text-[12.5px] leading-snug text-foreground-800">{it.name}</span>
                        <span className="shrink-0 whitespace-nowrap text-[12px] font-semibold text-foreground-950">
                          {t("quantity")}: {it.qty}
                        </span>
                      </li>
                    ))}
                  </ul>
                )}
              </div>

              {/* messages */}
              <div className="flex-1 overflow-y-auto px-5 py-5 space-y-4 bg-background-50">
                {messages.map((m) => (
                  <ChatMessageRow
                    key={m.id}
                    message={m}
                    approved={approved}
                    showActions={showActions}
                    onApprove={() => setConfirmOpen(true)}
                    onContinue={() => setInput("")}
                  />
                ))}
              </div>

              {/* input */}
              <div className="border-t border-background-200">
                {showCart && (
                  <div className="px-5 pt-3">
                    <WBtn full icon="ri-shopping-bag-3-line" onClick={() => navigate("cart")}>
                      {t("goToCart")}
                    </WBtn>
                  </div>
                )}
                <div className="flex items-center gap-3 px-5 py-4">
                  <button
                    type="button"
                    disabled={isNew}
                    className={cn(
                      "w-10 h-10 rounded-full flex items-center justify-center shrink-0",
                      isNew ? "text-foreground-300" : "cursor-pointer text-foreground-600 hover:bg-background-200",
                    )}
                  >
                    <i className="ri-attachment-2 text-[20px] leading-none" />
                  </button>
                  <input
                    value={input}
                    disabled={isNew}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyDown={(e) => e.key === "Enter" && send()}
                    placeholder={isNew ? t("messageLocked") : t("typeMessage")}
                    className="flex-1 h-11 px-4 rounded-[12px] bg-background-50 border border-background-200 text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 transition-colors font-body disabled:cursor-not-allowed"
                  />
                  <WBtn icon="ri-send-plane-fill" disabled={isNew || !input.trim()} onClick={send}>
                    {t("send")}
                  </WBtn>
                </div>
              </div>
            </WCard>
          </section>
        </div>
      </div>

      {confirmOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center px-6">
          <button
            type="button"
            aria-label="إغلاق"
            onClick={() => setConfirmOpen(false)}
            className="absolute inset-0 cursor-default bg-black/40"
          />
          <div className="relative w-full max-w-[360px] rounded-[20px] bg-background-100 p-6 animate-fade-in">
            <h3 className="text-center text-[17px] font-bold text-foreground-950">{t("approveInvoiceQ")}</h3>
            <p className="mt-2 text-center text-[13px] leading-relaxed text-foreground-600">
              {t("approveInvoiceDesc")}
            </p>
            <div className="mt-5 flex flex-col gap-2.5">
              <WBtn full onClick={confirmApprove}>
                {t("confirm")}
              </WBtn>
              <WBtn full variant="secondary" onClick={() => setConfirmOpen(false)}>
                {t("cancel")}
              </WBtn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}