import { useRef, useState } from "react";
import { useApp } from "../AppContext";
import { businesses } from "@/mocks/dshn";
import {
  chatThreads,
  type ChatInvoice,
  type ChatStatusKey,
  type ChatThread,
  type ChatThreadMessage,
} from "@/mocks/dshnChatThreads";
import ChatStatusBadge from "../components/ChatStatusBadge";
import { Btn, cn } from "../components/ui";

function InvoiceBubble({
  invoice,
  time,
  approved,
  showActions,
  onApprove,
  onContinue,
}: {
  invoice: ChatInvoice;
  time: string;
  approved: boolean;
  showActions: boolean;
  onApprove: () => void;
  onContinue: () => void;
}) {
  return (
    <div className="flex justify-end">
      <div className="flex max-w-[94%] flex-col items-end gap-1">
        <div className="w-[330px] max-w-full overflow-hidden rounded-[20px] border border-accent-300 bg-background-100">
          <div className="flex items-center gap-2 border-b border-accent-100 bg-accent-50 px-4 py-3">
            <i className="ri-file-list-3-line text-[18px] leading-none text-accent-800" />
            <span className="text-[14px] font-bold text-foreground-950">الفاتورة</span>
            <span className="mr-auto whitespace-nowrap text-[10.5px] text-foreground-600">
              {invoice.date}
            </span>
          </div>

          <div className="grid grid-cols-[minmax(0,1fr)_34px_54px_66px] gap-1.5 border-b border-background-200 px-4 py-2">
            <span className="text-[10px] font-semibold text-foreground-500">المنتج</span>
            <span className="text-center text-[10px] font-semibold text-foreground-500">الكمية</span>
            <span className="text-center text-[10px] font-semibold text-foreground-500">السعر</span>
            <span className="text-center text-[10px] font-semibold text-foreground-500">الإجمالي</span>
          </div>

          <div className="divide-y divide-background-200">
            {invoice.items.map((it) => (
              <div
                key={it.name}
                className="grid grid-cols-[minmax(0,1fr)_34px_54px_66px] items-start gap-1.5 px-4 py-2.5"
              >
                <span className="text-[11.5px] leading-snug text-foreground-900">{it.name}</span>
                <span className="text-center text-[11.5px] text-foreground-700">{it.qty}</span>
                <span className="whitespace-nowrap text-center text-[11.5px] text-foreground-700">
                  {it.price.toLocaleString("en-US")} ر.س
                </span>
                <span className="whitespace-nowrap text-center text-[11.5px] font-semibold text-foreground-950">
                  {(it.qty * it.price).toLocaleString("en-US")} ر.س
                </span>
              </div>
            ))}
          </div>

          <div className="flex items-center justify-between gap-2 bg-background-200/40 px-4 py-3">
            <span className="text-[12.5px] font-bold text-foreground-900">الإجمالي</span>
            <span className="whitespace-nowrap text-[15px] font-bold text-foreground-950">
              {invoice.total.toLocaleString("en-US")} ر.س
            </span>
          </div>

          <p className="px-4 pt-3 text-[10.5px] leading-relaxed text-foreground-500">
            هذه الفاتورة لتثبيت السعر المتفق عليه ولا تمثل عملية دفع
          </p>

          {approved ? (
            <div className="flex items-center gap-1.5 px-4 pb-4 pt-3 text-accent-700">
              <i className="ri-checkbox-circle-fill text-[16px] leading-none" />
              <span className="text-[12.5px] font-semibold">تمت الموافقة على الفاتورة ✓</span>
            </div>
          ) : showActions ? (
            <div className="flex flex-col gap-2 p-3.5">
              <Btn full onClick={onApprove}>
                موافقة على الفاتورة
              </Btn>
              <button
                type="button"
                onClick={onContinue}
                className="h-[48px] w-full cursor-pointer whitespace-nowrap rounded-[14px] border border-foreground-950 text-[14px] font-semibold text-foreground-950 transition-transform active:scale-[0.98]"
              >
                مواصلة التفاوض
              </button>
            </div>
          ) : (
            <div className="h-3" />
          )}
        </div>
        <span className="px-1 text-[10px] text-foreground-400">{time}</span>
      </div>
    </div>
  );
}

function MessageRow({
  message,
  approved,
  showActions,
  onApprove,
  onContinue,
}: {
  message: ChatThreadMessage;
  approved: boolean;
  showActions: boolean;
  onApprove: () => void;
  onContinue: () => void;
}) {
  if (message.type === "system") {
    return (
      <div className="flex justify-center py-0.5">
        <span className="max-w-[85%] rounded-full bg-background-200 px-3.5 py-1.5 text-center text-[11.5px] leading-snug text-foreground-600">
          {message.text}
        </span>
      </div>
    );
  }

  if (message.type === "invoice" && message.invoice) {
    return (
      <InvoiceBubble
        invoice={message.invoice}
        time={message.time}
        approved={approved}
        showActions={showActions}
        onApprove={onApprove}
        onContinue={onContinue}
      />
    );
  }

  const mine = message.from === "me";
  return (
    <div className={cn("flex", mine ? "justify-start" : "justify-end")}>
      <div className={cn("flex max-w-[78%] min-w-0 flex-col gap-1", mine ? "items-start" : "items-end")}>
        {message.type === "image" ? (
          <div className="h-[150px] w-[200px] overflow-hidden rounded-[16px] border border-background-200 bg-background-200">
            <img src={message.image} alt="مرفق" className="h-full w-full object-cover object-top" />
          </div>
        ) : message.type === "file" ? (
          <div className="flex w-[220px] items-center gap-3 rounded-[16px] border border-background-200 bg-background-100 p-3">
            <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-[10px] bg-background-200">
              <i className="ri-file-pdf-2-line text-[20px] leading-none text-danger-600" />
            </span>
            <div className="min-w-0">
              <p className="text-[12.5px] font-medium leading-snug text-foreground-950">{message.fileName}</p>
              <p className="text-[10.5px] text-foreground-500">ملف مرفق</p>
            </div>
          </div>
        ) : (
          <div
            className={cn(
              "rounded-[18px] px-3.5 py-2.5 text-[13px] leading-relaxed",
              mine
                ? "rounded-tr-[6px] bg-primary-500 text-background-50"
                : "rounded-tl-[6px] border border-background-200 bg-background-100 text-foreground-900",
            )}
          >
            {message.text}
          </div>
        )}
        <span className="px-1 text-[10px] text-foreground-400">{message.time}</span>
      </div>
    </div>
  );
}

export default function Chat({ slug = "al-reem" }: { slug?: string }) {
  const { navigate } = useApp();
  const thread: ChatThread = chatThreads[slug] ?? chatThreads["al-reem"];
  const biz = businesses.find((b) => b.id === thread.businessId)!;

  const [messages, setMessages] = useState<ChatThreadMessage[]>(thread.messages);
  const [approved, setApproved] = useState<boolean>(thread.invoiceApproved ?? false);
  const [input, setInput] = useState("");
  const [pinnedOpen, setPinnedOpen] = useState(true);
  const [menuOpen, setMenuOpen] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  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;
    setMessages((m) => [
      ...m,
      { id: `m${Date.now()}`, from: "me", type: "text", text: input.trim(), time: "الآن" },
    ]);
    setInput("");
  };

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

  return (
    <div
      dir="rtl"
      className="relative flex min-h-full w-full max-w-full flex-col overflow-x-clip bg-background-50 font-body"
    >
      <header className="sticky top-0 z-20 flex shrink-0 items-center gap-3 border-b border-background-200 bg-background-100 px-3 py-2.5">
        <button
          type="button"
          onClick={() => navigate("chats")}
          aria-label="رجوع"
          className="flex h-9 w-9 shrink-0 cursor-pointer items-center justify-center rounded-full text-foreground-950 hover:bg-background-200"
        >
          <i className="ri-arrow-right-line text-[21px] leading-none" />
        </button>
        <div className="h-10 w-10 shrink-0 overflow-hidden rounded-full bg-background-200">
          <img src={biz.logo} alt={biz.name} className="h-full w-full object-cover object-top" />
        </div>
        <div className="min-w-0 flex-1">
          <h1 className="text-[14.5px] font-semibold text-foreground-950">{biz.name}</h1>
          <div className="mt-0.5">
            <ChatStatusBadge status={statusKey} />
          </div>
        </div>
        <button
          type="button"
          onClick={() => setMenuOpen(true)}
          aria-label="خيارات"
          className="flex h-9 w-9 shrink-0 cursor-pointer items-center justify-center rounded-full text-foreground-700 hover:bg-background-200"
        >
          <i className="ri-more-2-fill text-[20px] leading-none" />
        </button>
      </header>

      <div className="mx-3 mt-3 shrink-0 rounded-[16px] border border-accent-200 bg-accent-50 p-3">
        <button
          type="button"
          onClick={() => setPinnedOpen((v) => !v)}
          className="flex w-full cursor-pointer items-center gap-1.5"
        >
          <i className="ri-pin-distance-line text-[15px] leading-none text-accent-800" />
          <span className="text-[12px] font-semibold text-accent-900">المنتجات المطلوبة</span>
          <i
            className={cn(
              "ri-arrow-down-s-line mr-auto text-[18px] leading-none text-accent-800 transition-transform",
              pinnedOpen ? "rotate-180" : "",
            )}
          />
        </button>
        {pinnedOpen && (
          <ul className="mt-2.5 space-y-2">
            {thread.pinned.map((it) => (
              <li key={it.name} className="flex items-center gap-2.5">
                <span className="h-9 w-9 shrink-0 overflow-hidden rounded-[10px] bg-background-200">
                  <img src={it.image} alt={it.name} className="h-full w-full object-cover object-top" />
                </span>
                <span className="min-w-0 flex-1 text-[12.5px] leading-snug text-foreground-800">
                  {it.name}
                </span>
                <span className="shrink-0 whitespace-nowrap text-[12px] font-semibold text-foreground-950">
                  الكمية: {it.qty}
                </span>
              </li>
            ))}
          </ul>
        )}
      </div>

      <div className="flex-1 space-y-3 px-3 py-4">
        {messages.map((m) => (
          <MessageRow
            key={m.id}
            message={m}
            approved={approved}
            showActions={showActions}
            onApprove={() => setConfirmOpen(true)}
            onContinue={() => inputRef.current?.focus()}
          />
        ))}
      </div>

      <div className="sticky bottom-0 z-30 mt-auto shrink-0 border-t border-background-200 bg-background-100 pb-[calc(12px+env(safe-area-inset-bottom))]">
        {showCart && (
          <div className="px-4 pt-3">
            <Btn full onClick={() => navigate("cart")}>
              <i className="ri-shopping-bag-3-line text-[18px] leading-none" />
              الذهاب للسلة
            </Btn>
          </div>
        )}
        <div className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 px-4 py-3">
          <button
            type="button"
            aria-label="إرفاق"
            disabled={isNew}
            className={cn(
              "flex h-12 w-12 shrink-0 items-center justify-center rounded-full",
              isNew ? "text-foreground-300" : "cursor-pointer text-foreground-700 hover:bg-background-200",
            )}
          >
            <i className="ri-attachment-2 text-[19px] leading-none" />
          </button>
          <div
            className={cn(
              "flex h-12 min-w-0 items-center rounded-full px-4",
              isNew ? "bg-background-100 border border-background-200" : "bg-background-200",
            )}
          >
            <input
              ref={inputRef}
              value={input}
              disabled={isNew}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && send()}
              placeholder={isNew ? "ستتمكن من المراسلة بعد قبول الطلب" : "اكتب رسالة..."}
              className="min-w-0 flex-1 bg-transparent font-body text-[13.5px] text-foreground-950 outline-none placeholder:text-foreground-400 disabled:cursor-not-allowed"
            />
          </div>
          <button
            type="button"
            onClick={send}
            disabled={isNew}
            aria-label="إرسال"
            className={cn(
              "flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-primary-500 text-background-50 transition-transform",
              isNew ? "cursor-not-allowed opacity-40" : "cursor-pointer active:scale-95",
            )}
          >
            <i className="ri-send-plane-fill -scale-x-100 text-[19px] leading-none" />
          </button>
        </div>
      </div>

      {menuOpen && (
        <div className="fixed inset-0 z-50 flex items-end">
          <button
            type="button"
            aria-label="إغلاق"
            onClick={() => setMenuOpen(false)}
            className="absolute inset-0 cursor-default bg-black/40"
          />
          <div className="relative w-full rounded-t-[24px] bg-background-50 p-4 pb-[calc(16px+env(safe-area-inset-bottom))] animate-sheet-up">
            <div className="mx-auto mb-3 h-1 w-10 rounded-full bg-background-300" />
            <h3 className="mb-2 px-1 text-[15px] font-bold text-foreground-950">خيارات المحادثة</h3>
            <button
              type="button"
              onClick={() => {
                setMenuOpen(false);
                navigate("dispute", { orderId: "1045" });
              }}
              className="flex w-full cursor-pointer items-center gap-3 rounded-[14px] px-3 py-3.5 text-right text-[14px] text-danger-600 hover:bg-danger-50"
            >
              <i className="ri-error-warning-line text-[20px] leading-none" />
              فتح نزاع
            </button>
          </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-[320px] rounded-[20px] bg-background-100 p-5 animate-fade-in">
            <h3 className="text-center text-[16px] font-bold text-foreground-950">
              هل توافق على الفاتورة؟
            </h3>
            <p className="mt-2 text-center text-[12.5px] leading-relaxed text-foreground-600">
              سيتم تثبيت الأسعار ونقل المنتجات إلى المنتجات المسعّرة في سلتك.
            </p>
            <div className="mt-5 flex flex-col gap-2">
              <Btn full onClick={confirmApprove}>
                تأكيد
              </Btn>
              <button
                type="button"
                onClick={() => setConfirmOpen(false)}
                className="h-[52px] w-full cursor-pointer whitespace-nowrap rounded-[14px] border border-foreground-950 text-[15px] font-semibold text-foreground-950 transition-transform active:scale-[0.98]"
              >
                تراجع
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}