import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Btn, Badge } from "@/pages/app/components/ui";
import { partnerBusinesses } from "@/mocks/dshnBusiness";
import { useProductStore } from "@/pages/product/store";
import type { BizPartnershipRow } from "@/mocks/dshnBizPartners";
import { partnerChatScreen, partnerRequestStamp } from "@/pages/app/lib/partnerRequest";

/**
 * Another business's page opened from "استكشاف المنشآت للشراكة" (section 2.16).
 * Sending a partnership request requires confirmation, creates a real
 * "قيد التفاوض" record, and is blocked when one already exists.
 */
export default function BizPartnerPage() {
  const { goBack, navigate, params } = useApp();
  const { activePartnershipFor, sendPartnerRequest } = useProductStore();
  const biz = partnerBusinesses.find((b) => b.id === params.businessId) ?? partnerBusinesses[1];
  const partners = partnerBusinesses.filter((b) => b.id !== biz.id).slice(0, 3);

  const existing = biz.isOwn ? null : activePartnershipFor(biz.id);

  const [sheetOpen, setSheetOpen] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [created, setCreated] = useState<BizPartnershipRow | null>(null);
  const [createdAt, setCreatedAt] = useState("");

  const confirmRequest = () => {
    const result = sendPartnerRequest(biz, message);
    setSheetOpen(false);
    if (result.ok) {
      setCreated(result.row);
      setCreatedAt(partnerRequestStamp(new Date()));
      setError("");
      setMessage("");
      return;
    }
    setError("لديك طلب شراكة قائم مع هذه المنشأة بالفعل — تابع الطلب بدل إنشاء طلب جديد.");
    setMessage("");
  };

  const openChat = (row: BizPartnershipRow) =>
    navigate(partnerChatScreen(row.status, row.role === "requester"), {
      partnerId: row.id,
      businessId: biz.id,
    });

  return (
    <div className="relative min-h-full flex flex-col bg-background-50">
      <BackHeader title="المنشأة" onBack={goBack} />

      <div className="flex-1 px-4 pt-4 pb-5 space-y-4">
        {/* Identity card */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-5">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 rounded-[18px] overflow-hidden bg-background-200 shrink-0">
              <img src={biz.logo} alt={biz.name} className="w-full h-full object-cover object-top" />
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-1.5">
                <h1 className="text-[17px] font-bold text-foreground-950 truncate">{biz.name}</h1>
                {biz.verified && (
                  <i className="ri-verified-badge-fill text-[16px] text-accent-600 leading-none shrink-0" />
                )}
              </div>
              <p className="text-[12.5px] text-foreground-600 mt-1 truncate">{biz.activity}</p>
              <p className="text-[11.5px] text-foreground-500 mt-1 flex items-center gap-1">
                <i className="ri-map-pin-line text-[13px] leading-none" />
                {biz.city}
              </p>
            </div>
          </div>
        </div>

        {/* Duplicate guard notice */}
        {existing && (
          <div className="rounded-[16px] bg-secondary-100 border border-secondary-200 px-4 py-3 flex items-start gap-2.5">
            <i className="ri-information-line text-[17px] text-secondary-900 leading-none shrink-0 mt-0.5" />
            <div className="min-w-0">
              <p className="text-[12.5px] font-semibold text-secondary-900">لديك طلب شراكة قائم مع هذه المنشأة</p>
              <p className="text-[11.5px] text-foreground-700 mt-0.5">
                شراكة #{existing.number} · {existing.statusLabel}
              </p>
            </div>
          </div>
        )}

        {/* About */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <h2 className="text-[14px] font-semibold text-foreground-950">نبذة عن المنشأة</h2>
          <p className="text-[12.5px] text-foreground-700 leading-relaxed mt-1.5">{biz.description}</p>
        </div>

        {/* Public "الشراكات" section */}
        <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">
            {partners.map((p) => (
              <div key={p.id} className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-[12px] overflow-hidden bg-background-200 shrink-0">
                  <img src={p.logo} alt={p.name} className="w-full h-full object-cover object-top" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-1.5">
                    <p className="text-[13px] font-semibold text-foreground-950 truncate">{p.name}</p>
                    {p.verified && (
                      <i className="ri-verified-badge-fill text-[13px] text-accent-600 leading-none shrink-0" />
                    )}
                  </div>
                  <p className="text-[11px] text-foreground-600 mt-0.5 truncate">{p.field}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Sticky bottom action — hidden on the owner's own business */}
      {!biz.isOwn && (
        <div className="sticky bottom-0 z-20 bg-background-50/95 backdrop-blur border-t border-background-200/70 px-4 py-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)]">
          {created ? (
            <>
              <div className="flex items-start gap-2.5 mb-2.5">
                <span className="w-8 h-8 rounded-full bg-accent-100 text-accent-800 flex items-center justify-center shrink-0">
                  <i className="ri-check-line text-[16px] leading-none" />
                </span>
                <div className="min-w-0">
                  <p className="text-[12.5px] font-semibold text-foreground-950">تم إرسال طلب الشراكة</p>
                  <p className="text-[11px] text-foreground-600 mt-0.5">
                    رقم الطلب #{created.number} · {createdAt}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Btn full onClick={() => openChat(created)}>فتح المحادثة</Btn>
                <Btn
                  full
                  variant="secondary"
                  onClick={() => navigate("bizPartnership", { partnerId: created.id })}
                >
                  عرض الطلب
                </Btn>
              </div>
            </>
          ) : existing ? (
            <>
              <div className="flex items-center justify-between mb-2">
                <span className="text-[11.5px] text-foreground-600">
                  شراكة #{existing.number} · {existing.date}
                </span>
                <Badge tone={existing.statusTone}>{existing.statusLabel}</Badge>
              </div>
              <div className="flex items-center gap-2">
                <Btn full onClick={() => openChat(existing)}>
                  {existing.status === "negotiating" ? "فتح المحادثة" : "متابعة الشراكة"}
                </Btn>
                <Btn
                  full
                  variant="secondary"
                  onClick={() => navigate("bizPartnership", { partnerId: existing.id })}
                >
                  التفاصيل
                </Btn>
              </div>
            </>
          ) : (
            <>
              {error && (
                <div className="rounded-[12px] bg-danger-50 border border-danger-200 px-3 py-2 mb-2">
                  <p className="text-[11.5px] text-danger-700 leading-relaxed">{error}</p>
                </div>
              )}
              <div className="flex items-center gap-2 mb-2">
                <Badge tone="info">سيُنشأ طلب شراكة بحالة قيد التفاوض</Badge>
              </div>
              <Btn full onClick={() => setSheetOpen(true)}>
                طلب شراكة
              </Btn>
            </>
          )}
        </div>
      )}

      {/* Confirmation sheet */}
      {sheetOpen && (
        <div className="fixed inset-0 z-50 flex items-end justify-center">
          <button
            type="button"
            aria-label="إغلاق"
            onClick={() => setSheetOpen(false)}
            className="absolute inset-0 bg-black/40 cursor-default"
          />
          <div className="relative w-full max-w-[520px] rounded-t-[24px] bg-background-50 border-t border-background-200 p-5 pb-[calc(env(safe-area-inset-bottom)+1.25rem)]">
            <div className="w-10 h-1 rounded-full bg-background-300 mx-auto mb-4" />
            <h2 className="text-[16px] font-bold text-foreground-950">إرسال طلب شراكة</h2>
            <p className="text-[12px] text-foreground-600 leading-relaxed mt-1.5">
              سيتم إنشاء طلب شراكة مع <strong className="text-foreground-900">{biz.name}</strong> بحالة
              «قيد التفاوض»، ونفتح لك محادثة مباشرة مع المنشأة لمناقشة التفاصيل.
            </p>

            <div className="rounded-[14px] bg-background-100 border border-background-200 p-3.5 mt-4 flex items-center gap-3">
              <div className="w-11 h-11 rounded-[13px] overflow-hidden bg-background-200 shrink-0">
                <img src={biz.logo} alt={biz.name} className="w-full h-full object-cover object-top" />
              </div>
              <div className="min-w-0">
                <p className="text-[13px] font-semibold text-foreground-950 truncate">{biz.name}</p>
                <p className="text-[11.5px] text-foreground-600 mt-0.5 truncate">
                  {biz.field} · {biz.city}
                </p>
              </div>
            </div>

            <div className="mt-4">
              <label
                htmlFor="partner-request-message"
                className="block text-[12px] font-semibold text-foreground-900 mb-1.5"
              >
                رسالة أولية (اختياري)
              </label>
              <textarea
                id="partner-request-message"
                value={message}
                onChange={(event) => setMessage(event.target.value.slice(0, 500))}
                rows={3}
                maxLength={500}
                placeholder="مثال: نرغب بشراكة توزيع لمنتجاتنا في منطقتكم."
                className="w-full rounded-[12px] bg-background-100 border border-background-200 p-3 text-[12.5px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 resize-none"
              />
              <p className="text-[10.5px] text-foreground-500 mt-1 text-end">{message.length}/500</p>
            </div>

            <div className="flex items-center gap-2 mt-4">
              <Btn full variant="secondary" onClick={() => setSheetOpen(false)}>
                إلغاء
              </Btn>
              <Btn full onClick={confirmRequest}>
                تأكيد إرسال الطلب
              </Btn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}