import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Badge, Btn, cn } from "@/pages/app/components/ui";
import { KvRow } from "@/pages/app/components/bo/BoUI";
import PartnerStatusTrack from "@/pages/app/components/biz/PartnerStatusTrack";
import { bizPartnerTermsList, bizPartnershipSides } from "@/mocks/dshnBizPartners";
import { useProductStore } from "@/pages/product/store";
import { partnerChatScreen, partnershipBusinessId } from "@/pages/app/lib/partnerRequest";
import { partnerNextAction } from "@/pages/app/lib/partnerStatus";

/**
 * Partnership details (section 2.22): both businesses, live status track,
 * contract terms, invoice, chat, and actions driven by role + status.
 */
export default function BizPartnership() {
  const { goBack, navigate, params } = useApp();
  const {
    partnerships,
    approvePartnership,
    rejectPartnership,
    completePartnerAdminReview,
    cancelPartnership,
  } = useProductStore();
  const p = partnerships.find((row) => row.id === params.partnerId) ?? partnerships[0];
  const isRequester = p.role === "requester";
  const businessId = partnershipBusinessId(p);
  const chatTarget = partnerChatScreen(p.status, isRequester);
  const valueLabel = p.value > 0 ? `${p.value.toLocaleString("en-US")} ر.س` : "حسب الاتفاق";
  const next = partnerNextAction(p);

  const [rejectOpen, setRejectOpen] = useState(false);
  const [cancelOpen, setCancelOpen] = useState(false);
  const [reason, setReason] = useState("");
  const [banner, setBanner] = useState(params.flash === "1" ? "تم تحديث حالة الشراكة" : "");

  const runReject = () => {
    if (!reason.trim()) return;
    rejectPartnership(p.id, reason);
    setRejectOpen(false);
    setReason("");
    setBanner("تم رفض عقد الشراكة وإبلاغ الطرف الآخر بالسبب");
  };

  const runCancel = () => {
    cancelPartnership(p.id, reason);
    setCancelOpen(false);
    setReason("");
    setBanner("تم إلغاء طلب الشراكة");
  };

  const runAdminApprove = () => {
    completePartnerAdminReview(p.id);
    setBanner("تم اعتماد الدفعة من إدارة المنصة وأصبحت الشراكة سارية");
  };

  const openChat = () =>
    navigate(chatTarget, { partnerId: p.id, businessId: businessId ?? undefined });

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title="تفاصيل الشراكة" subtitle={`شراكة #${p.number}`} onBack={goBack} />

      <div className="flex-1 px-4 pt-5 pb-6 space-y-4">
        {banner && (
          <div className="rounded-[14px] bg-accent-100 border border-accent-200 px-4 py-3 flex items-start gap-2.5">
            <i className="ri-checkbox-circle-fill text-[18px] text-accent-700 leading-none mt-0.5" />
            <p className="flex-1 text-[12px] font-medium text-accent-900 leading-relaxed">{banner}</p>
            <button type="button" onClick={() => setBanner("")} className="shrink-0 cursor-pointer">
              <i className="ri-close-line text-[16px] text-accent-700 leading-none" />
            </button>
          </div>
        )}

        {/* Both businesses (tappable) */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4 space-y-3">
          <button
            type="button"
            onClick={() => navigate("bizPartnerPage", { businessId: businessId ?? p.id })}
            className="w-full flex items-center gap-3 text-right cursor-pointer"
          >
            <div className="w-11 h-11 rounded-[13px] overflow-hidden bg-background-200 shrink-0">
              <img src={p.partnerLogo} alt={p.partnerName} className="w-full h-full object-cover object-top" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-[13.5px] font-semibold text-foreground-950 truncate">{p.partnerName}</p>
              <p className="text-[11px] text-foreground-600 mt-0.5">
                {bizPartnershipSides.partner.field} · {p.partnerCity}
              </p>
            </div>
            <i className="ri-arrow-left-s-line text-[18px] text-foreground-400 leading-none shrink-0" />
          </button>
          <div className="h-px bg-background-200" />
          <div className="flex items-center gap-3">
            <div className="w-11 h-11 rounded-[13px] bg-background-200 flex items-center justify-center shrink-0">
              <i className="ri-store-3-line text-[18px] text-foreground-800 leading-none" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-[13.5px] font-semibold text-foreground-950 truncate">
                {bizPartnershipSides.mine.name}
              </p>
              <p className="text-[11px] text-foreground-600 mt-0.5">
                {bizPartnershipSides.mine.field} · {bizPartnershipSides.mine.city}
              </p>
            </div>
            <span className="shrink-0">
              <Badge tone={isRequester ? "info" : "neutral"}>
                {isRequester ? "طالب الشراكة" : "الطرف الآخر"}
              </Badge>
            </span>
          </div>
        </div>

        {/* Live status track */}
        <PartnerStatusTrack row={p} />

        {/* Contract terms */}
        <button
          type="button"
          onClick={() => navigate("bizPartnerTerms", { partnerId: p.id })}
          className="w-full rounded-[16px] bg-background-100 border border-background-200 px-4 py-3.5 flex items-center gap-3 text-right cursor-pointer hover:border-background-300 transition-colors"
        >
          <span className="w-9 h-9 rounded-[11px] bg-background-200 flex items-center justify-center shrink-0">
            <i className="ri-file-text-line text-[17px] text-foreground-800 leading-none" />
          </span>
          <span className="flex-1 min-w-0">
            <span className="block text-[13px] font-semibold text-foreground-950">بنود عقد الشراكة</span>
            <span className="block text-[11px] text-foreground-600 mt-0.5">
              {bizPartnerTermsList.length} بنود متفق عليها
            </span>
          </span>
          <i className="ri-arrow-left-s-line text-[18px] text-foreground-400 leading-none shrink-0" />
        </button>

        {/* Invoice */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <h2 className="text-[14px] font-semibold text-foreground-950 mb-3">الفاتورة</h2>
          <div className="space-y-2.5">
            <KvRow label="رقم الفاتورة" value={`INV-${p.number}`} />
            <KvRow label="قيمة الشراكة" value={valueLabel} strong />
            <KvRow label="التاريخ" value={p.date} />
            {p.updatedAt && <KvRow label="آخر تحديث" value={p.updatedAt} />}
          </div>
        </div>

        {/* Actions by role + status */}
        <div className="pt-1 space-y-3">
          {next === "invoice" && (
            <Btn full onClick={() => navigate("bizPartnerInvoice", { partnerId: p.id })}>
              إعداد فاتورة الشراكة
            </Btn>
          )}

          {next === "approve" && (
            <>
              <Btn full onClick={() => navigate("bizPartnerReview", { partnerId: p.id })}>
                مراجعة الطلب والموافقة
              </Btn>
              <Btn full variant="danger" onClick={() => { setReason(""); setRejectOpen(true); }}>
                رفض الطلب
              </Btn>
            </>
          )}

          {next === "pay" && (
            <>
              <Btn full onClick={() => navigate("bizPartnerPay", { partnerId: p.id })}>
                إتمام الدفع
              </Btn>
              <Btn full variant="secondary" onClick={() => navigate("bizPartnerTransfer", { partnerId: p.id })}>
                تحويل بنكي ورفع إثبات
              </Btn>
            </>
          )}

          {next === "waitAdmin" && (
            <>
              <div className="rounded-[14px] bg-secondary-100 border border-secondary-200 px-4 py-3">
                <p className="text-[12px] text-foreground-800 leading-relaxed">
                  تم رفع إثبات السداد. فريق المنصة يراجع الدفعة الآن، وستتحول الشراكة إلى «حالية» بعد الاعتماد.
                </p>
              </div>
              <Btn full variant="secondary" onClick={runAdminApprove}>
                اعتماد الدفعة (محاكاة الإدارة)
              </Btn>
            </>
          )}

          {next === "done" && (
            <Btn full variant="secondary" onClick={() => navigate("bizPartnerInvoice", { partnerId: p.id })}>
              عرض الفاتورة
            </Btn>
          )}

          {next === "closed" && (
            <Btn full variant="secondary" onClick={() => navigate("bizPartnersExplore")}>
              بدء طلب شراكة جديد
            </Btn>
          )}

          {(next === "waitApproval" || next === "waitPayment") && (
            <div className="rounded-[14px] bg-background-100 border border-background-200 px-4 py-3">
              <p className="text-[12px] text-foreground-700 leading-relaxed">
                {next === "waitApproval"
                  ? "الطلب عند الطرف الآخر للمراجعة والموافقة على العقد."
                  : "بانتظار قيام الطرف الآخر بسداد قيمة الشراكة."}
              </p>
            </div>
          )}

          {next === "waitApproval" && (
            <Btn full variant="secondary" onClick={() => { approvePartnership(p.id); setBanner("تمت الموافقة على العقد — الشراكة الآن «قيد الدفع»"); }}>
              محاكاة موافقة الطرف الآخر
            </Btn>
          )}

          <button
            type="button"
            onClick={openChat}
            className="w-full h-[52px] rounded-[14px] bg-background-50 border border-foreground-950 text-foreground-950 flex items-center justify-center gap-2 whitespace-nowrap text-[16px] transition-all duration-200 cursor-pointer active:scale-[0.98]"
          >
            <i className="ri-chat-3-line text-[19px] leading-none" />
            فتح المحادثة
          </button>

          {next !== "closed" && next !== "done" && (
            <button
              type="button"
              onClick={() => { setReason(""); setCancelOpen(true); }}
              className={cn(
                "w-full h-[48px] rounded-[14px] text-[14px] font-semibold cursor-pointer transition-colors",
                "bg-danger-50 border border-danger-200 text-danger-700 hover:bg-danger-100",
              )}
            >
              إلغاء الشراكة
            </button>
          )}
        </div>
      </div>

      {rejectOpen && (
        <ReasonSheet
          title="رفض عقد الشراكة"
          desc="اكتب سبب الرفض ليصل للطرف الآخر داخل المحادثة."
          tone="danger"
          value={reason}
          onChange={setReason}
          confirmLabel="تأكيد الرفض"
          onCancel={() => setRejectOpen(false)}
          onConfirm={runReject}
        />
      )}

      {cancelOpen && (
        <ReasonSheet
          title="إلغاء الشراكة"
          desc="سيتم إلغاء طلب الشراكة نهائيًا ولا يمكن التراجع بعد التأكيد."
          tone="danger"
          value={reason}
          onChange={setReason}
          confirmLabel="تأكيد الإلغاء"
          onCancel={() => setCancelOpen(false)}
          onConfirm={runCancel}
        />
      )}
    </div>
  );
}

function ReasonSheet({
  title,
  desc,
  tone,
  value,
  onChange,
  confirmLabel,
  onCancel,
  onConfirm,
}: {
  title: string;
  desc: string;
  tone: "danger";
  value: string;
  onChange: (value: string) => void;
  confirmLabel: string;
  onCancel: () => void;
  onConfirm: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[60] flex items-end sm:items-center justify-center px-0 sm:px-6">
      <button type="button" aria-label="إغلاق" onClick={onCancel} className="absolute inset-0 bg-foreground-950/45 cursor-default" />
      <div className="relative w-full sm:max-w-[380px] rounded-t-[22px] sm:rounded-[22px] bg-background-50 p-5 animate-fade-in">
        <h3 className="text-[16px] font-bold text-foreground-950">{title}</h3>
        <p className="text-[12px] text-foreground-600 mt-1.5 leading-relaxed">{desc}</p>
        <textarea
          value={value}
          onChange={(event) => onChange(event.target.value.slice(0, 500))}
          rows={3}
          maxLength={500}
          placeholder="اكتب السبب هنا..."
          className="mt-4 w-full rounded-[12px] bg-background-100 border border-background-200 p-3 text-[13px] outline-none focus:border-foreground-400 resize-none"
        />
        <p className="text-[10.5px] text-foreground-500 mt-1 text-end">{value.length}/500</p>
        <div className="space-y-2.5 mt-3">
          <button
            type="button"
            onClick={onConfirm}
            disabled={value.trim() === ""}
            className={cn(
              "w-full h-[48px] rounded-[13px] text-[14px] font-semibold text-background-50 bg-danger-500 hover:bg-danger-600 cursor-pointer transition-colors",
              value.trim() === "" && "opacity-40 pointer-events-none",
              tone === "danger",
            )}
          >
            {confirmLabel}
          </button>
          <button
            type="button"
            onClick={onCancel}
            className="w-full h-[48px] rounded-[13px] text-[14px] font-semibold text-foreground-900 border border-background-300 hover:bg-background-200 cursor-pointer"
          >
            تراجع
          </button>
        </div>
      </div>
    </div>
  );
}