import { useMemo, useState } from "react";
import { businesses } from "@/mocks/dshn";
import { products, chats } from "@/mocks/dshnCommerce";
import { useWeb } from "../WebContext";
import { Container, WBtn, WCard, StatusPill, EmptyWeb, fmt, cn } from "../WebUI";

type NegStatus = "new" | "talking" | "invoiced";
type PillTone = "success" | "warn" | "danger" | "info" | "neutral" | "blush";

interface PricedLine {
  id: string;
  productId: string;
  qty: number;
}

interface NegLine {
  id: string;
  productId: string;
  qty: number;
  status: NegStatus;
  /** A negotiation request has already been sent to this business. */
  sent: boolean;
}

const INITIAL_PRICED: PricedLine[] = [
  { id: "ci1", productId: "pr1", qty: 2 },
  { id: "ci2", productId: "pr2", qty: 1 },
  { id: "ci3", productId: "pr3", qty: 1 },
];

const INITIAL_NEG: NegLine[] = [
  { id: "ni1", productId: "pr5", qty: 1, status: "new", sent: false },
  { id: "ni2", productId: "pr12", qty: 1, status: "talking", sent: true },
];

const STATUS: Record<NegStatus, { key: string; tone: PillTone }> = {
  new: { key: "negStatusNew", tone: "neutral" },
  talking: { key: "negStatusTalking", tone: "warn" },
  invoiced: { key: "negStatusInvoiced", tone: "success" },
};

function productById(id: string) {
  return products.find((p) => p.id === id)!;
}

function chatIdFor(businessId: string) {
  return chats.find((c) => c.businessId === businessId)?.id;
}

export default function Cart() {
  const { t, navigate, jump } = useWeb();
  const [priced, setPriced] = useState<PricedLine[]>(INITIAL_PRICED);
  const [neg, setNeg] = useState<NegLine[]>(INITIAL_NEG);
  // المنتجات المختارة للدفع (كل المنتجات محددة مبدئيًا)
  const [selected, setSelected] = useState<string[]>(INITIAL_PRICED.map((i) => i.id));

  const pricedGroups = useMemo(
    () =>
      businesses
        .map((b) => ({
          business: b,
          items: priced.filter((i) => productById(i.productId)?.businessId === b.id),
        }))
        .filter((g) => g.items.length > 0),
    [priced],
  );

  const negGroups = useMemo(
    () =>
      businesses
        .map((b) => ({
          business: b,
          items: neg.filter((i) => productById(i.productId)?.businessId === b.id),
        }))
        .filter((g) => g.items.length > 0),
    [neg],
  );

  const groupSubtotal = (items: PricedLine[]) =>
    items.reduce((s, l) => s + (productById(l.productId)?.price ?? 0) * l.qty, 0);

  const isEmpty = priced.length === 0 && neg.length === 0;

  const selectedLines = priced.filter((i) => selected.includes(i.id));
  const selectedTotal = selectedLines.reduce((s, l) => s + (productById(l.productId)?.price ?? 0) * l.qty, 0);
  const allSelected = priced.length > 0 && priced.every((i) => selected.includes(i.id));

  const toggleLine = (id: string) =>
    setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));

  const toggleGroup = (ids: string[]) =>
    setSelected((prev) =>
      ids.every((id) => prev.includes(id)) ? prev.filter((id) => !ids.includes(id)) : Array.from(new Set([...prev, ...ids])),
    );

  const toggleAll = () => setSelected(allSelected ? [] : priced.map((i) => i.id));

  const checkoutSelected = () => {
    if (selectedLines.length === 0) return;
    jump("checkoutAddress", { cartItems: selectedLines.map((i) => `${i.productId}:${i.qty}`).join(",") });
  };

  const changeQty = (id: string, delta: number) =>
    setPriced((prev) => prev.map((i) => (i.id === id ? { ...i, qty: Math.max(1, i.qty + delta) } : i)));
  const removePriced = (id: string) => setPriced((prev) => prev.filter((i) => i.id !== id));

  const changeNegQty = (id: string, delta: number) =>
    setNeg((prev) => prev.map((i) => (i.id === id ? { ...i, qty: Math.max(1, i.qty + delta) } : i)));
  const removeNeg = (id: string) => setNeg((prev) => prev.filter((i) => i.id !== id));

  const openChat = (businessId: string) => {
    const chatId = chatIdFor(businessId);
    if (chatId) navigate("chats", { chatId });
  };

  const orderViaChat = (businessId: string, lines: NegLine[]) => {
    setNeg((prev) => prev.map((i) => (lines.some((x) => x.id === i.id) ? { ...i, sent: true } : i)));
    openChat(businessId);
  };

  return (
    <div className="animate-fade-in">
      <Container className="py-8 md:py-10">
        <header className="mb-7">
          <h1 className="text-[28px] md:text-[34px] font-bold text-foreground-950 font-heading">
            {t("cart")}
          </h1>
          <p className="text-[13.5px] text-foreground-600 mt-2">
            {priced.length} {t("pricedUnit")} &bull; {neg.length} {t("negUnit")}
          </p>
        </header>

        {isEmpty ? (
          <WCard>
            <EmptyWeb
              icon="ri-shopping-bag-3-line"
              title={t("emptyCartTitle")}
              desc={t("emptyCartHint")}
              actionLabel={t("browseProducts")}
              onAction={() => jump("products")}
            />
          </WCard>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 lg:gap-8 items-start">
            {/* MAIN column */}
            <div className="lg:col-span-2 space-y-8">
              {pricedGroups.length > 0 && (
                <section>
                  <div className="flex items-center gap-2.5 mb-4">
                    <span className="w-9 h-9 rounded-full bg-accent-100 text-accent-800 flex items-center justify-center shrink-0">
                      <i className="ri-price-tag-3-line text-[17px] leading-none" />
                    </span>
                    <h2 className="text-[19px] font-bold text-foreground-950">{t("pricedItems")}</h2>
                  </div>

                  <div className="space-y-4">
                    {pricedGroups.map((g) => (
                      <WCard key={g.business.id} className="overflow-hidden">
                        <div className="flex items-center gap-3 px-5 py-4 border-b border-background-200">
                          <CheckBox
                            checked={g.items.every((i) => selected.includes(i.id))}
                            onChange={() => toggleGroup(g.items.map((i) => i.id))}
                            label={`تحديد كل منتجات ${g.business.name}`}
                          />
                          <div className="w-11 h-11 rounded-full overflow-hidden bg-background-200 shrink-0">
                            <img
                              src={g.business.logo}
                              alt={g.business.name}
                              className="w-full h-full object-cover object-top"
                            />
                          </div>
                          <button
                            type="button"
                            onClick={() => navigate("business", { businessId: g.business.id })}
                            className="text-[15px] font-semibold text-foreground-950 hover:underline underline-offset-2 cursor-pointer"
                          >
                            {g.business.name}
                          </button>
                        </div>

                        <div className="divide-y divide-background-200">
                          {g.items.map((l) => {
                            const p = productById(l.productId);
                            return (
                              <div
                                key={l.id}
                                className={cn(
                                  "flex items-center gap-3 md:gap-5 px-5 py-4 transition-colors",
                                  selected.includes(l.id) ? "bg-transparent" : "bg-background-200/40",
                                )}
                              >
                                <CheckBox
                                  checked={selected.includes(l.id)}
                                  onChange={() => toggleLine(l.id)}
                                  label={`تحديد ${p.name}`}
                                />
                                <div className="w-[72px] h-[72px] md:w-[88px] md:h-[88px] rounded-[14px] overflow-hidden bg-background-200 shrink-0">
                                  <img
                                    src={p.image}
                                    alt={p.name}
                                    className="w-full h-full object-cover object-top"
                                  />
                                </div>
                                <button
                                  type="button"
                                  onClick={() => navigate("product", { productId: p.id })}
                                  className="flex-1 min-w-0 text-start cursor-pointer"
                                >
                                  <p className="text-[15px] font-semibold text-foreground-950 leading-snug line-clamp-2">
                                    {p.name}
                                  </p>
                                  <p className="text-[15px] font-bold text-foreground-950 mt-1.5 whitespace-nowrap">
                                    {fmt(p.price)} <span className="text-[12px] font-semibold">ر.س</span>
                                  </p>
                                </button>
                                <QtyControl value={l.qty} onChange={(d) => changeQty(l.id, d)} />
                                <TrashBtn label="حذف المنتج" onClick={() => removePriced(l.id)} />
                              </div>
                            );
                          })}
                        </div>

                        <div className="flex items-center justify-between px-5 py-3.5 bg-background-200/60 border-t border-background-200">
                          <span className="text-[13px] text-foreground-600">{t("itemSubtotal")}</span>
                          <span className="text-[16px] font-bold text-foreground-950 whitespace-nowrap">
                            {fmt(groupSubtotal(g.items))} ر.س
                          </span>
                        </div>
                      </WCard>
                    ))}
                  </div>
                </section>
              )}

              {negGroups.length > 0 && (
                <section>
                  <div className="flex items-center gap-2.5 mb-4 flex-wrap">
                    <span className="w-9 h-9 rounded-full bg-secondary-100 text-secondary-900 flex items-center justify-center shrink-0">
                      <i className="ri-chat-3-line text-[17px] leading-none" />
                    </span>
                    <h2 className="text-[19px] font-bold text-foreground-950">{t("negotiatedItems")}</h2>
                    <span className="inline-flex items-center rounded-full bg-secondary-100 text-secondary-900 px-3 py-1 text-[11.5px] font-semibold whitespace-nowrap">
                      {t("negotiable")}
                    </span>
                  </div>

                  <div className="space-y-4">
                    {negGroups.map((g) => {
                      const allSent = g.items.every((i) => i.sent);
                      return (
                        <WCard key={g.business.id} className="overflow-hidden">
                          <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">
                              <img
                                src={g.business.logo}
                                alt={g.business.name}
                                className="w-full h-full object-cover object-top"
                              />
                            </div>
                            <button
                              type="button"
                              onClick={() => navigate("business", { businessId: g.business.id })}
                              className="text-[15px] font-semibold text-foreground-950 hover:underline underline-offset-2 cursor-pointer"
                            >
                              {g.business.name}
                            </button>
                          </div>

                          <div className="divide-y divide-background-200">
                            {g.items.map((n) => {
                              const p = productById(n.productId);
                              const st = STATUS[n.status];
                              return (
                                <div key={n.id} className="flex items-center gap-4 md:gap-5 px-5 py-4">
                                  <div className="w-[72px] h-[72px] md:w-[88px] md:h-[88px] rounded-[14px] overflow-hidden bg-background-200 shrink-0">
                                    <img
                                      src={p.image}
                                      alt={p.name}
                                      className="w-full h-full object-cover object-top"
                                    />
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <button
                                      type="button"
                                      onClick={() => navigate("product", { productId: p.id })}
                                      className="text-[15px] font-semibold text-foreground-950 leading-snug line-clamp-2 text-start cursor-pointer"
                                    >
                                      {p.name}
                                    </button>
                                    <div className="flex items-center gap-2 flex-wrap mt-2">
                                      <span className="inline-flex items-center rounded-full bg-secondary-100 text-secondary-900 px-2.5 py-1 text-[11px] font-bold whitespace-nowrap">
                                        {t("negotiable")}
                                      </span>
                                      <StatusPill tone={st.tone}>{t(st.key)}</StatusPill>
                                      {n.sent && (
                                        <button
                                          type="button"
                                          onClick={() => openChat(g.business.id)}
                                          className="text-[12.5px] font-semibold text-foreground-950 underline underline-offset-2 hover:text-foreground-700 cursor-pointer whitespace-nowrap"
                                        >
                                          {n.status === "invoiced" ? t("reviewInvoice") : t("openChat")}
                                        </button>
                                      )}
                                    </div>
                                  </div>
                                  <QtyControl value={n.qty} onChange={(d) => changeNegQty(n.id, d)} />
                                  <TrashBtn label="حذف المنتج" onClick={() => removeNeg(n.id)} />
                                </div>
                              );
                            })}
                          </div>

                          <div className="px-5 py-4 border-t border-background-200">
                            <WBtn
                              variant="secondary"
                              full
                              icon="ri-chat-3-line"
                              onClick={() => orderViaChat(g.business.id, g.items)}
                            >
                              {allSent ? t("openChat") : t("orderViaChat")}
                            </WBtn>
                          </div>
                        </WCard>
                      );
                    })}
                  </div>
                </section>
              )}
            </div>

            {/* SIDE column — order summary (always visible in place) */}
            <aside className="lg:col-span-1">
              <WCard className="p-6">
                <div className="flex items-center justify-between gap-3 mb-3">
                  <h3 className="text-[17px] font-bold text-foreground-950">{t("orderSummary")}</h3>
                  <button
                    type="button"
                    onClick={toggleAll}
                    className="text-[12.5px] font-semibold text-primary-600 hover:text-primary-700 cursor-pointer whitespace-nowrap"
                  >
                    {allSelected ? "إلغاء تحديد الكل" : "تحديد الكل"}
                  </button>
                </div>

                <div className="space-y-2.5">
                  {pricedGroups
                    .map((g) => ({ g, items: g.items.filter((i) => selected.includes(i.id)) }))
                    .filter((x) => x.items.length > 0)
                    .map(({ g, items }) => (
                      <div key={g.business.id} className="flex items-center justify-between gap-3">
                        <span className="text-[13.5px] text-foreground-600 truncate">
                          {g.business.name} <span className="text-[12px] text-foreground-500">({items.length})</span>
                        </span>
                        <span className="text-[13.5px] font-semibold text-foreground-950 whitespace-nowrap">
                          {fmt(groupSubtotal(items))} ر.س
                        </span>
                      </div>
                    ))}
                </div>

                <div className="h-px bg-background-200 my-4" />

                <div className="flex items-center justify-between gap-3">
                  <span className="text-[14px] font-semibold text-foreground-950">
                    {t("pricedTotalLabel")}
                    <span className="block text-[11.5px] font-normal text-foreground-500 mt-0.5">
                      المحدد {selectedLines.length} من {priced.length} منتج
                    </span>
                  </span>
                  <span className="text-[22px] font-bold text-foreground-950 whitespace-nowrap">
                    {fmt(selectedTotal)} ر.س
                  </span>
                </div>

                <p className="text-[12px] text-foreground-500 leading-relaxed mt-2.5">{t("summaryNote")}</p>

                <button
                  type="button"
                  disabled={selectedLines.length === 0}
                  onClick={checkoutSelected}
                  className="w-full h-14 mt-5 rounded-[14px] bg-primary-500 text-background-50 text-[15px] font-semibold inline-flex items-center justify-center whitespace-nowrap hover:bg-primary-600 transition-colors cursor-pointer disabled:opacity-40 disabled:pointer-events-none"
                >
                  {t("continuePayment")} {selectedLines.length > 0 ? `(${selectedLines.length})` : ""}
                </button>

                <div className="text-center mt-3.5">
                  <button
                    type="button"
                    onClick={() => jump("products")}
                    className="text-[13px] font-semibold text-foreground-600 hover:text-foreground-950 underline-offset-2 hover:underline cursor-pointer"
                  >
                    {t("continueShopping")}
                  </button>
                </div>

                <div className="mt-5 rounded-[14px] bg-background-50 border border-background-200 p-4 flex items-start gap-2.5">
                  <i className="ri-information-line text-[17px] text-foreground-500 leading-none mt-0.5 shrink-0" />
                  <p className="text-[12px] text-foreground-600 leading-relaxed">{t("negotiationInfo")}</p>
                </div>
              </WCard>
            </aside>
          </div>
        )}
      </Container>
    </div>
  );
}

function CheckBox({ checked, onChange, label }: { checked: boolean; onChange: () => void; label: string }) {
  return (
    <button
      type="button"
      role="checkbox"
      aria-checked={checked}
      aria-label={label}
      onClick={onChange}
      className={cn(
        "w-[22px] h-[22px] rounded-[7px] border flex items-center justify-center shrink-0 transition-colors cursor-pointer",
        checked
          ? "bg-primary-500 border-primary-500 text-background-50"
          : "bg-background-50 border-background-400 text-transparent",
      )}
    >
      <i className="ri-check-line text-[14px] leading-none" />
    </button>
  );
}

function QtyControl({ value, onChange }: { value: number; onChange: (delta: number) => void }) {
  return (
    <div className="flex items-center gap-2.5 md:gap-3 shrink-0">
      <button
        type="button"
        aria-label="زيادة الكمية"
        onClick={() => onChange(1)}
        className="w-9 h-9 rounded-full border border-background-300 flex items-center justify-center text-foreground-950 hover:bg-background-200 transition-colors cursor-pointer"
      >
        <i className="ri-add-line text-[17px] leading-none" />
      </button>
      <span className="w-6 text-center text-[15px] font-semibold text-foreground-950">{value}</span>
      <button
        type="button"
        aria-label="تقليل الكمية"
        onClick={() => onChange(-1)}
        className="w-9 h-9 rounded-full border border-background-300 flex items-center justify-center text-foreground-950 hover:bg-background-200 transition-colors cursor-pointer"
      >
        <i className="ri-subtract-line text-[17px] leading-none" />
      </button>
    </div>
  );
}

function TrashBtn({ onClick, label }: { onClick: () => void; label: string }) {
  return (
    <button
      type="button"
      aria-label={label}
      onClick={onClick}
      className="w-10 h-10 rounded-full flex items-center justify-center text-danger-600 hover:bg-danger-50 transition-colors cursor-pointer shrink-0"
    >
      <i className="ri-delete-bin-6-line text-[19px] leading-none" />
    </button>
  );
}