import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { Badge, cn } from "@/pages/app/components/ui";
import Countdown from "@/pages/app/components/bo/Countdown";
import {
  investorCommitmentDetails as D,
  commitmentTimelineOpen,
  commitmentTimelineCancelled,
  type CommitmentStep,
} from "@/mocks/dshnInvestor";

export type CommitmentVariant = "open" | "due" | "cancelled";

function fmt(n: number) {
  return n.toLocaleString("en-US");
}

/** One vertical timeline row. */
function Timeline({ steps }: { steps: CommitmentStep[] }) {
  return (
    <div>
      {steps.map((s, i) => {
        const last = i === steps.length - 1;
        const dot =
          s.state === "current"
            ? "bg-foreground-950 border-foreground-950"
            : s.state === "cancelled"
              ? "bg-danger-50 border-danger-500"
              : "bg-accent-500 border-accent-500";
        return (
          <div key={`${s.label}-${i}`} className="flex gap-3">
            <div className="flex flex-col items-center">
              <span className={cn("w-[14px] h-[14px] rounded-full border-2 mt-0.5 shrink-0", dot)} />
              {!last && <span className="w-[2px] flex-1 bg-background-300 my-1" />}
            </div>
            <div className={cn("flex-1 min-w-0", !last && "pb-5")}>
              <p
                className={cn(
                  "text-[13px] font-semibold leading-tight",
                  s.state === "cancelled"
                    ? "text-danger-700"
                    : s.state === "current"
                      ? "text-foreground-950"
                      : "text-foreground-900",
                )}
              >
                {s.label}
              </p>
              {s.date && <p className="text-[11px] text-foreground-500 mt-1">{s.date}</p>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function InfoRow({ label, value, valueClass = "" }: { label: string; value: string; valueClass?: string }) {
  return (
    <div className="flex items-center justify-between gap-3 py-3.5 border-b border-background-200/70 last:border-b-0">
      <span className="text-[12.5px] text-foreground-600">{label}</span>
      <span className={cn("text-[13px] font-semibold text-foreground-950 text-left", valueClass)}>{value}</span>
    </div>
  );
}

/**
 * Shared co-investment commitment details used by the details, cancel and
 * cancelled screens. The bottom action bar changes with the variant:
 *  - open      → فتح المحادثة + إلغاء الالتزام
 *  - due       → سداد الالتزام ورفع الإثبات (opportunity closed, no cancel)
 *  - cancelled → تصفح فرص أخرى + العودة للمتابعة
 */
export default function CommitmentDetails({
  variant,
  pressed = false,
  toast = false,
}: {
  variant: CommitmentVariant;
  pressed?: boolean;
  toast?: boolean;
}) {
  const { goBack, navigate } = useApp();
  const [menuOpen, setMenuOpen] = useState(false);

  const cancelled = variant === "cancelled";
  const due = variant === "due";
  const progress = Math.round((D.collected / D.target) * 100);
  const steps = cancelled ? commitmentTimelineCancelled : commitmentTimelineOpen;
  const statusLabel = cancelled ? "ملغاة" : due ? "مطلوب السداد" : "قيد التفاوض";
  const statusTone = cancelled ? "danger" : due ? "success" : "warn";

  return (
    <div className="relative min-h-full flex flex-col bg-background-50">
      {/* Top bar */}
      <div className="sticky top-0 z-20 bg-background-50/95 backdrop-blur px-4 pt-3 pb-3 flex items-center gap-2 border-b border-background-200/70">
        <button
          type="button"
          onClick={goBack}
          className="w-10 h-10 rounded-full flex items-center justify-center text-foreground-950 hover:bg-background-200 cursor-pointer shrink-0"
        >
          <i className="ri-arrow-right-line text-[22px] leading-none" />
        </button>
        <h1 className="flex-1 text-[17px] font-semibold text-foreground-950">تفاصيل الالتزام</h1>
        <div className="relative shrink-0">
          <button
            type="button"
            aria-label="خيارات"
            onClick={() => setMenuOpen((v) => !v)}
            className="w-10 h-10 rounded-full flex items-center justify-center text-foreground-950 hover:bg-background-200 cursor-pointer"
          >
            <i className="ri-more-2-fill text-[20px] leading-none" />
          </button>
          {menuOpen && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setMenuOpen(false)} />
              <div className="absolute left-0 top-11 z-20 w-[190px] rounded-[14px] bg-background-50 border border-background-200 shadow-sm overflow-hidden">
                <button
                  type="button"
                  onClick={() => {
                    setMenuOpen(false);
                    navigate("invBusiness", { businessId: D.businessId });
                  }}
                  className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-medium text-foreground-800 hover:bg-background-100 cursor-pointer text-right"
                >
                  <i className="ri-store-2-line text-[17px] leading-none" />
                  عرض صفحة المنشأة
                </button>
                {due && (
                  <button
                    type="button"
                    onClick={() => {
                      setMenuOpen(false);
                      navigate("invDispute");
                    }}
                    className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-medium text-danger-700 hover:bg-danger-50 cursor-pointer text-right border-t border-background-200/70"
                  >
                    <i className="ri-error-warning-line text-[17px] leading-none" />
                    فتح نزاع
                  </button>
                )}
              </div>
            </>
          )}
        </div>
      </div>

      {/* Body */}
      <div className="flex-1 px-4 pt-4 pb-32 space-y-4">
        {/* Business header card */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 overflow-hidden">
          <div className="relative h-[132px] bg-background-200">
            <img src={D.cover} alt={D.businessName} className="w-full h-full object-cover object-top" />
            <div className="absolute inset-0 bg-gradient-to-t from-foreground-950/35 to-transparent" />
          </div>
          <div className="px-4 pb-4">
            <div className="flex items-end gap-3 -mt-8">
              <div className="w-16 h-16 rounded-full overflow-hidden bg-background-200 ring-4 ring-background-100 shrink-0">
                <img src={D.businessLogo} alt={D.businessName} className="w-full h-full object-cover object-top" />
              </div>
              <div className="flex-1 min-w-0 pb-1">
                <h2 className="text-[16px] font-bold text-foreground-950 truncate">{D.businessName}</h2>
                <p className="text-[11.5px] text-foreground-600 mt-0.5 truncate">
                  {D.category} • {D.city}
                </p>
              </div>
            </div>
            <button
              type="button"
              onClick={() => navigate("invBusiness", { businessId: D.businessId })}
              className="mt-3 inline-flex items-center gap-1 text-[12.5px] font-semibold text-foreground-700 hover:text-foreground-950 cursor-pointer"
            >
              عرض صفحة المنشأة
              <i className="ri-arrow-left-s-line text-[16px] leading-none" />
            </button>
          </div>
        </div>

        {/* Status card */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <div className="flex items-center gap-2 flex-wrap">
            <Badge tone="neutral">التزام استثمار تشاركي</Badge>
            <Badge tone={statusTone}>{statusLabel}</Badge>
          </div>

          {cancelled ? (
            <div className="mt-4 flex items-start gap-2.5 rounded-[14px] bg-background-200/70 px-3.5 py-3">
              <i className="ri-information-line text-[17px] text-foreground-500 leading-none mt-0.5" />
              <span className="text-[12px] text-foreground-700 leading-relaxed">
                تم إلغاء هذا الالتزام بتاريخ {D.cancelledDate} ولم يعد ضمن المبالغ المُجمّعة للفرصة.
              </span>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between text-[11.5px] mt-4 mb-2">
                <span className="text-foreground-600">تم جمع {progress}%</span>
                <span className="font-semibold text-foreground-900">
                  {fmt(D.collected)} / {fmt(D.target)} ر.س
                </span>
              </div>
              <div className="h-2 rounded-full bg-accent-100 overflow-hidden">
                <div className="h-full bg-accent-500 rounded-full" style={{ width: `${progress}%` }} />
              </div>

              {!due && (
                <div className="mt-4 pt-4 border-t border-background-200/70">
                  <p className="text-[11.5px] text-foreground-600 mb-2.5">الوقت المتبقي لإغلاق الفرصة</p>
                  <Countdown target={D.endAt} />
                </div>
              )}
            </>
          )}
        </div>

        {/* Commitment details */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <h3 className="text-[14px] font-bold text-foreground-950 mb-1">تفاصيل التزامك</h3>
          <div>
            <InfoRow label="مبلغ الالتزام" value={`${fmt(D.amount)} ر.س`} />
            <InfoRow label="نصيبك المتوقع من النسبة" value={`${D.equity}%`} valueClass="text-accent-700" />
            <InfoRow label="نسبة الاستثمار المعروضة للفرصة" value={`${D.opportunityEquity}%`} />
            <InfoRow label="المبلغ المستهدف" value={`${fmt(D.target)} ر.س`} />
            <InfoRow label="تاريخ تقديم الالتزام" value={D.date} />
            <InfoRow label="حالة الالتزام" value={statusLabel} />
          </div>
        </div>

        {/* Status log */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <h3 className="text-[14px] font-bold text-foreground-950 mb-4">سجل الحالة</h3>
          <Timeline steps={steps} />
        </div>

        {/* Note */}
        {!cancelled && !due && (
          <div className="flex items-start gap-2.5 rounded-[14px] bg-background-200/70 px-3.5 py-3">
            <i className="ri-information-line text-[17px] text-foreground-500 leading-none mt-0.5" />
            <span className="text-[12px] text-foreground-700 leading-relaxed">
              يمكنك إلغاء التزامك في أي وقت قبل اكتمال الفرصة أو إغلاقها.
            </span>
          </div>
        )}

        {/* Inset following-card preview (cancelled only) */}
        {cancelled && (
          <div className="pt-1">
            <p className="text-[11.5px] text-foreground-500 mb-2">كما تظهر في المتابعة</p>
            <div className="rounded-[18px] bg-background-100 border border-background-200 p-3.5 opacity-90">
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-full overflow-hidden bg-background-200 shrink-0">
                  <img src={D.businessLogo} alt={D.businessName} className="w-full h-full object-cover object-top" />
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="text-[13.5px] font-semibold text-foreground-950 truncate">{D.businessName}</h3>
                  <p className="text-[10.5px] text-foreground-600 mt-0.5">{D.date}</p>
                </div>
                <i className="ri-arrow-left-s-line text-[20px] text-foreground-400 leading-none shrink-0" />
              </div>
              <div className="flex items-center gap-2 mt-3 flex-wrap">
                <Badge tone="neutral">التزام استثمار تشاركي</Badge>
                <Badge tone="danger">ملغاة</Badge>
              </div>
              <div className="grid grid-cols-2 gap-2.5 mt-3">
                <div className="rounded-[12px] bg-background-200/70 p-2.5">
                  <p className="text-[10px] text-foreground-600">قيمة العرض</p>
                  <p className="text-[13px] font-bold text-foreground-400 mt-0.5 line-through">{fmt(D.amount)} ر.س</p>
                </div>
                <div className="rounded-[12px] bg-background-200/70 p-2.5">
                  <p className="text-[10px] text-foreground-600">النسبة</p>
                  <p className="text-[13px] font-bold text-foreground-400 mt-0.5 line-through">{D.equity}%</p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Bottom action bar */}
      <div className="sticky bottom-0 z-30 px-4 py-4 bg-background-50 border-t border-background-200/70 space-y-2.5">
        {variant === "open" && (
          <>
            <button
              type="button"
              onClick={() => navigate("invChat")}
              className="w-full h-[52px] rounded-[14px] bg-primary-500 text-background-50 text-[15px] font-semibold flex items-center justify-center gap-2 cursor-pointer active:scale-[0.98] transition-transform whitespace-nowrap"
            >
              <i className="ri-chat-3-line text-[18px] leading-none" />
              فتح المحادثة
            </button>
            <button
              type="button"
              onClick={() => navigate("invCommitmentCancel")}
              className={cn(
                "w-full h-[52px] rounded-[14px] border text-[14px] font-semibold flex items-center justify-center gap-2 cursor-pointer whitespace-nowrap active:scale-[0.98] transition-all",
                pressed
                  ? "bg-danger-100 border-danger-200 text-danger-700"
                  : "bg-background-50 border-danger-200 text-danger-700 hover:bg-danger-50",
              )}
            >
              <i className="ri-close-circle-line text-[17px] leading-none" />
              إلغاء الالتزام
            </button>
          </>
        )}

        {variant === "due" && (
          <button
            type="button"
            onClick={() => navigate("invPayment")}
            className="w-full h-[52px] rounded-[14px] bg-primary-500 text-background-50 text-[15px] font-semibold flex items-center justify-center gap-2 cursor-pointer active:scale-[0.98] transition-transform whitespace-nowrap"
          >
            <i className="ri-upload-2-line text-[18px] leading-none" />
            سداد الالتزام ورفع الإثبات
          </button>
        )}

        {variant === "cancelled" && (
          <>
            <button
              type="button"
              onClick={() => navigate("invOpportunities")}
              className="w-full h-[52px] rounded-[14px] bg-primary-500 text-background-50 text-[15px] font-semibold flex items-center justify-center gap-2 cursor-pointer active:scale-[0.98] transition-transform whitespace-nowrap"
            >
              <i className="ri-compass-3-line text-[18px] leading-none" />
              تصفح فرص أخرى
            </button>
            <button
              type="button"
              onClick={() => navigate("invFollowing")}
              className="w-full h-[46px] rounded-[14px] text-[14px] font-semibold text-foreground-700 hover:text-foreground-950 cursor-pointer whitespace-nowrap"
            >
              العودة للمتابعة
            </button>
          </>
        )}
      </div>

      {/* Success toast */}
      {toast && (
        <div className="absolute top-3 inset-x-4 z-40 animate-fade-in">
          <div className="mx-auto max-w-[420px] flex items-center gap-3 rounded-[16px] bg-accent-700 px-4 py-3.5">
            <span className="w-8 h-8 rounded-full bg-background-50/20 flex items-center justify-center shrink-0">
              <i className="ri-check-line text-[18px] text-background-50 leading-none" />
            </span>
            <span className="text-[13px] font-semibold text-background-50">تم إلغاء التزامك بنجاح</span>
          </div>
        </div>
      )}
    </div>
  );
}