import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Btn, cn } from "@/pages/app/components/ui";
import { fmt } from "@/pages/app/components/biz/BizUI";
import { commissionRows } from "@/mocks/dshnBizPartners";

const DUE = commissionRows.filter((c) => c.status === "due");

/** Commission settlement — select due deals and request a batch settlement (section 2.24). */
export default function BizSettlement() {
  const { goBack, navigate, params } = useApp();
  const [selected, setSelected] = useState<string[]>([]);

  // Coming from «تم تسجيل الصفقة»: one specific deal commission is pre-selected.
  const dealRef = params.dealRef ? String(params.dealRef) : "";
  const dealAmount = Number(params.amount) || 0;
  const singleDeal = Boolean(dealRef) && dealAmount > 0;

  const allSelected = selected.length === DUE.length && DUE.length > 0;
  const total =
    DUE.filter((d) => selected.includes(d.id)).reduce((sum, d) => sum + d.commission, 0) +
    (singleDeal ? dealAmount : 0);

  const toggle = (id: string) =>
    setSelected((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));
  const toggleAll = () => setSelected(allSelected ? [] : DUE.map((d) => d.id));

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title="تسويات العمولة" onBack={goBack} />

      <div className="flex-1 px-4 py-5 space-y-4">
        {singleDeal && (
          <div className="rounded-[16px] border border-accent-200 bg-accent-50 p-3.5">
            <div className="flex items-center gap-2">
              <i className="ri-secure-payment-line text-[17px] text-accent-700 leading-none" />
              <p className="text-[12.5px] font-bold text-foreground-950">عمولة الصفقة المحددة</p>
              <span className="ms-auto text-[13px] font-bold text-foreground-950 whitespace-nowrap">
                {fmt(dealAmount)} ر.س
              </span>
            </div>
            <p className="text-[11px] text-foreground-600 mt-1.5 leading-relaxed">
              {dealRef} — محددة تلقائيًا من شاشة تسجيل الصفقة. يمكنك إضافة عمولات أخرى من القائمة
              أدناه لسدادها معًا.
            </p>
          </div>
        )}

        {/* Tabs */}
        <div className="flex gap-1 bg-background-100 border border-background-200 rounded-full p-1">
          <button
            type="button"
            onClick={() => navigate("bizCommissions")}
            className="flex-1 h-11 rounded-full text-[12.5px] font-medium whitespace-nowrap cursor-pointer text-foreground-700 hover:bg-background-200 transition-colors"
          >
            سجل العمليات
          </button>
          <span className="flex-1 h-11 rounded-full text-[12.5px] font-medium flex items-center justify-center whitespace-nowrap bg-primary-500 text-background-50">
            تسويات العمولة
          </span>
        </div>

        {DUE.length === 0 ? (
          <div className="py-10 flex flex-col items-center text-center">
            <div className="w-16 h-16 rounded-full bg-background-100 border border-background-200 flex items-center justify-center mb-4">
              <i className="ri-receipt-line text-[28px] text-foreground-400 leading-none" />
            </div>
            <p className="text-[14px] font-medium text-foreground-700">
              {singleDeal ? "لا توجد عمولات مستحقة أخرى" : "لا توجد عمولات مستحقة"}
            </p>
          </div>
        ) : (
          <>
            {/* Select all */}
            <button
              type="button"
              onClick={toggleAll}
              className="w-full flex items-center gap-2.5 px-1 py-1 cursor-pointer"
            >
              <span
                className={cn(
                  "w-5 h-5 rounded-[6px] border flex items-center justify-center shrink-0 transition-colors",
                  allSelected ? "bg-primary-500 border-primary-500" : "bg-background-100 border-background-300",
                )}
              >
                {allSelected && <i className="ri-check-line text-[14px] text-background-50 leading-none" />}
              </span>
              <span className="text-[13px] font-medium text-foreground-900">تحديد الكل</span>
            </button>

            {/* Due deals */}
            <div className="space-y-2.5">
              {DUE.map((d) => {
                const on = selected.includes(d.id);
                return (
                  <button
                    key={d.id}
                    type="button"
                    onClick={() => toggle(d.id)}
                    className={cn(
                      "w-full text-right rounded-[16px] border p-3.5 flex items-center gap-3 cursor-pointer transition-colors",
                      on ? "bg-primary-50 border-primary-300" : "bg-background-100 border-background-200",
                    )}
                  >
                    <span
                      className={cn(
                        "w-5 h-5 rounded-[6px] border flex items-center justify-center shrink-0 transition-colors",
                        on ? "bg-primary-500 border-primary-500" : "bg-background-50 border-background-300",
                      )}
                    >
                      {on && <i className="ri-check-line text-[14px] text-background-50 leading-none" />}
                    </span>
                    <span className="flex-1 min-w-0">
                      <span className="block text-[13px] font-semibold text-foreground-950 truncate">
                        {d.dealNumber}
                      </span>
                      <span className="block text-[10.5px] text-foreground-500 mt-0.5">{d.date}</span>
                    </span>
                    <span className="text-[13px] font-bold text-foreground-950 shrink-0">
                      {fmt(d.commission)} ر.س
                    </span>
                  </button>
                );
              })}
            </div>
          </>
        )}
      </div>

      {/* Summary + action */}
      <div className="sticky bottom-0 z-30 bg-background-50 border-t border-background-200/70 px-4 py-4 pb-[calc(env(safe-area-inset-bottom)+0.75rem)]">
        <div className="flex items-center justify-between mb-3">
          <span className="text-[12.5px] text-foreground-600">إجمالي المبلغ المختار</span>
          <span className="text-[15px] font-bold text-foreground-950">{fmt(total)} ر.س</span>
        </div>
        <Btn
          full
          disabled={selected.length === 0 && !singleDeal}
          onClick={() =>
            navigate("bizSettlementSent", singleDeal ? { dealRef, amount: String(total) } : undefined)
          }
        >
          {singleDeal && selected.length === 0
            ? "سداد عمولة هذه الصفقة"
            : selected.length === 0
              ? "طلب تسوية الدفعات المحددة"
              : `سداد ${selected.length + (singleDeal ? 1 : 0)} عمولة الآن`}
        </Btn>
      </div>
    </div>
  );
}