import { useState } from "react";
import { useApp } from "../AppContext";
import { businesses } from "@/mocks/dshn";
import { products } from "@/mocks/dshnCommerce";
import { Badge, Btn, Card, Stepper, cn } from "../components/ui";

interface Line {
  productId: string;
  qty: number;
}

const NEGOTIATION_STATUS: Record<string, { label: string; tone: "success" | "warn" | "danger" | "neutral" }> = {
  new: { label: "طلب تفاوض جديد", tone: "neutral" },
  talking: { label: "قيد التواصل والتفاوض", tone: "warn" },
  invoiced: { label: "تم رفع الفاتورة", tone: "success" },
  rejected: { label: "مرفوض", tone: "danger" },
};

const EMPTY_IMAGE =
  "https://readdy.ai/api/search-image?query=Minimal%20illustration%20of%20an%20empty%20shopping%20bag%20on%20soft%20cream%20background%2C%20gentle%20pastel%20mint%20and%20neutral%20tones%2C%20simple%20flat%20modern%20style%2C%20clean%20composition&width=300&height=300&seq=dshn-empty-cart&orientation=squarish";

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>
  );
}

export default function Cart() {
  const { navigate, goBack } = useApp();
  const [lines, setLines] = useState<Line[]>([
    { productId: "pr1", qty: 2 },
    { productId: "pr2", qty: 1 },
    { productId: "pr3", qty: 1 },
  ]);
  const [negotiation, setNegotiation] = useState([
    { id: "n1", productId: "pr5", businessId: "biz-fashion", status: "new" },
    { id: "n2", productId: "pr12", businessId: "biz-factory", status: "talking" },
  ]);
  // المنتجات المختارة للدفع (كل المنتجات محددة مبدئيًا)
  const [selected, setSelected] = useState<string[]>(["pr1", "pr2", "pr3"]);

  const pricedItems = lines
    .map((l) => ({ ...l, product: products.find((p) => p.id === l.productId)! }))
    .filter((l) => l.product);

  const groups = Array.from(new Set(pricedItems.map((l) => l.product.businessId))).map((bid) => ({
    business: businesses.find((b) => b.id === bid)!,
    items: pricedItems.filter((l) => l.product.businessId === bid),
  }));

  const negotiationGroups = Array.from(new Set(negotiation.map((n) => n.businessId))).map((bid) => ({
    business: businesses.find((b) => b.id === bid)!,
    items: negotiation.filter((n) => n.businessId === bid),
  }));

  const total = pricedItems.reduce((sum, l) => sum + (l.product.price ?? 0) * l.qty, 0);
  const isEmpty = pricedItems.length === 0 && negotiation.length === 0;

  const selectedLines = pricedItems.filter((l) => selected.includes(l.productId));
  const selectedTotal = selectedLines.reduce((sum, l) => sum + (l.product.price ?? 0) * l.qty, 0);
  const allSelected = pricedItems.length > 0 && pricedItems.every((l) => selected.includes(l.productId));

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

  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 ? [] : pricedItems.map((l) => l.productId));

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

  if (isEmpty) {
    return (
      <div className="min-h-full flex flex-col items-center justify-center px-6 py-16 text-center">
        <div className="w-32 h-32 rounded-[28px] overflow-hidden bg-background-200 mb-6">
          <img src={EMPTY_IMAGE} alt="سلة فارغة" className="w-full h-full object-cover object-top" />
        </div>
        <h2 className="text-[18px] font-bold text-foreground-950">سلتك فارغة</h2>
        <p className="text-[13px] text-foreground-600 mt-2 max-w-[250px] leading-relaxed">
          لم تقم بإضافة أي منتجات بعد. تصفّح المنتجات وابدأ التسوق.
        </p>
        <div className="mt-6 w-full max-w-[240px]">
          <Btn full onClick={() => navigate("products")}>تصفح المنتجات</Btn>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-full flex-col pb-6">
      <div className="px-4">
        <h1 className="text-[24px] font-bold text-foreground-950">سلة المشتريات</h1>
        <p className="text-[12.5px] text-foreground-600 mt-1">
          {pricedItems.length} منتج مسعّر • {negotiation.length} طلب تفاوض
        </p>
      </div>

      {groups.length > 0 && (
        <div className="px-4 mt-4 space-y-3">
          <h2 className="text-[15px] font-semibold text-foreground-950">المنتجات المسعّرة</h2>
          {groups.map((g) => {
            const sub = g.items.reduce((s, l) => s + (l.product.price ?? 0) * l.qty, 0);
            return (
              <Card key={g.business.id} className="p-0 overflow-hidden">
                <div className="flex items-center gap-2.5 px-4 py-3 border-b border-background-200">
                  <CheckBox
                    checked={g.items.every((l) => selected.includes(l.productId))}
                    onChange={() => toggleGroup(g.items.map((l) => l.productId))}
                    label={`تحديد كل منتجات ${g.business.name}`}
                  />
                  <div className="w-9 h-9 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-[13.5px] font-semibold text-foreground-950 cursor-pointer"
                  >
                    {g.business.name}
                  </button>
                </div>
                <div className="divide-y divide-background-200">
                  {g.items.map((l) => (
                    <div
                      key={l.productId}
                      className={cn(
                        "flex gap-3 p-3.5 transition-colors",
                        selected.includes(l.productId) ? "bg-transparent" : "bg-background-200/30",
                      )}
                    >
                      <div className="pt-6">
                        <CheckBox
                          checked={selected.includes(l.productId)}
                          onChange={() => toggleLine(l.productId)}
                          label={`تحديد ${l.product.name}`}
                        />
                      </div>
                      <div className="w-[70px] h-[70px] rounded-[14px] overflow-hidden bg-background-200 shrink-0">
                        <img src={l.product.image} alt={l.product.name} className="w-full h-full object-cover object-top" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="text-[13px] font-semibold text-foreground-950 leading-snug line-clamp-2">
                          {l.product.name}
                        </h3>
                        <p className="text-[13px] font-bold text-foreground-950 mt-1.5">
                          {l.product.price?.toLocaleString("en-US")} ر.س
                        </p>
                        <div className="flex items-center justify-between mt-2">
                          <Stepper
                            value={l.qty}
                            min={1}
                            onChange={(v) =>
                              setLines((prev) => prev.map((x) => (x.productId === l.productId ? { ...x, qty: v } : x)))
                            }
                          />
                          <button
                            type="button"
                            onClick={() => setLines((prev) => prev.filter((x) => x.productId !== l.productId))}
                            className="w-8 h-8 rounded-full flex items-center justify-center text-danger-500 hover:bg-danger-50 cursor-pointer"
                          >
                            <i className="ri-delete-bin-6-line text-[17px] leading-none" />
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="flex items-center justify-between px-4 py-3 bg-background-200/40">
                  <span className="text-[12.5px] text-foreground-600">الإجمالي الفرعي</span>
                  <span className="text-[14px] font-bold text-foreground-950">{sub.toLocaleString("en-US")} ر.س</span>
                </div>
              </Card>
            );
          })}

          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-[12px] text-foreground-600">إجمالي المنتجات المختارة</p>
                <p className="text-[20px] font-bold text-foreground-950 mt-0.5">
                  {selectedTotal.toLocaleString("en-US")} ر.س
                </p>
              </div>
              <button
                type="button"
                onClick={toggleAll}
                className="text-[12px] font-semibold text-primary-600 hover:text-primary-700 cursor-pointer whitespace-nowrap"
              >
                {allSelected ? "إلغاء تحديد الكل" : "تحديد الكل"}
              </button>
            </div>
            <p className="text-[11px] text-foreground-500 mt-1.5">
              {selectedLines.length} من {pricedItems.length} منتج — إجمالي السلة {total.toLocaleString("en-US")} ر.س
            </p>
          </Card>
        </div>
      )}

      {negotiationGroups.length > 0 && (
        <div className="px-4 mt-6 space-y-3">
          <div className="flex items-center gap-2">
            <h2 className="text-[15px] font-semibold text-foreground-950">منتجات التفاوض</h2>
            <Badge tone="warn">سعر حسب التفاوض</Badge>
          </div>
          {negotiationGroups.map((g) => (
            <Card key={g.business.id} className="p-0 overflow-hidden">
              <div className="flex items-center gap-3 px-4 py-3 border-b border-background-200">
                <div className="w-9 h-9 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>
                <span className="text-[13.5px] font-semibold text-foreground-950">{g.business.name}</span>
              </div>
              <div className="divide-y divide-background-200">
                {g.items.map((n) => {
                  const product = products.find((p) => p.id === n.productId)!;
                  const st = NEGOTIATION_STATUS[n.status];
                  return (
                    <div key={n.id} className="flex gap-3 p-3.5">
                      <div className="w-[70px] h-[70px] rounded-[14px] overflow-hidden bg-background-200 shrink-0">
                        <img src={product.image} alt={product.name} className="w-full h-full object-cover object-top" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="text-[13px] font-semibold text-foreground-950 leading-snug line-clamp-2">{product.name}</h3>
                        <div className="mt-1.5">
                          <span className="inline-flex items-center rounded-full bg-secondary-100 text-secondary-900 px-2.5 py-1 text-[10.5px] font-semibold">
                            السعر حسب التفاوض
                          </span>
                        </div>
                        <div className="mt-2 flex items-center gap-2 flex-wrap">
                          <Badge tone={st.tone}>{st.label}</Badge>
                          <button
                            type="button"
                            onClick={() => navigate("chat", { chatId: "al-reem" })}
                            className="text-[11.5px] font-semibold text-foreground-950 underline underline-offset-2 cursor-pointer"
                          >
                            فتح المحادثة
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="p-3.5">
                <button
                  type="button"
                  onClick={() => navigate("chat", { chatId: "al-reem" })}
                  className="w-full h-[46px] rounded-[14px] border border-foreground-950 text-foreground-950 text-[14px] font-semibold flex items-center justify-center gap-2 cursor-pointer active:scale-[0.98] transition-transform"
                >
                  <i className="ri-chat-3-line text-[17px] leading-none" />
                  طلب عن طريق المحادثة
                </button>
              </div>
            </Card>
          ))}
        </div>
      )}

      <div className="sticky bottom-0 z-30 mt-auto p-4 bg-background-50/95 backdrop-blur border-t border-background-200/70">
        <div className="flex items-center justify-between mb-2.5">
          <button
            type="button"
            onClick={toggleAll}
            className="text-[12px] font-semibold text-foreground-700 hover:text-foreground-950 underline underline-offset-2 cursor-pointer whitespace-nowrap"
          >
            {allSelected ? "إلغاء تحديد الكل" : "تحديد الكل"}
          </button>
          <p className="text-[12.5px] text-foreground-600">
            المحدد ({selectedLines.length}) •{" "}
            <span className="font-bold text-foreground-950">{selectedTotal.toLocaleString("en-US")} ر.س</span>
          </p>
        </div>
        <button
          type="button"
          disabled={selectedLines.length === 0}
          onClick={checkoutSelected}
          className="w-full h-[52px] rounded-[14px] bg-primary-500 text-background-50 text-[15px] font-semibold cursor-pointer active:scale-[0.98] transition-transform disabled:opacity-40 disabled:pointer-events-none"
        >
          متابعة للدفع {selectedLines.length > 0 ? `(${selectedLines.length})` : ""}
        </button>
      </div>
    </div>
  );
}