import { useState } from "react";
import { investorRequestDetails, investorCounterOffer } from "@/mocks/dshnInvestor";
import { useWeb } from "@/pages/web/WebContext";
import { Container, WCard, WBtn, StatusPill, cn, fmt } from "@/pages/web/WebUI";
import type { WebParams } from "@/pages/web/types";

type RDState = "new" | "talking" | "negotiating" | "counter" | "agreed" | "rejected" | "cancelled";

const META: Record<RDState, { label: string; tone: "success" | "warn" | "danger" | "info" | "neutral" }> = {
  new: { label: "طلب جديد", tone: "info" },
  talking: { label: "جاري التواصل", tone: "warn" },
  negotiating: { label: "تفاوض", tone: "warn" },
  counter: { label: "عرض مقابل", tone: "info" },
  agreed: { label: "تم الاتفاق", tone: "success" },
  rejected: { label: "مرفوضة", tone: "danger" },
  cancelled: { label: "ملغاة", tone: "neutral" },
};

const CAN_CHAT: RDState[] = ["talking", "negotiating", "agreed", "counter"];
const CAN_CANCEL: RDState[] = ["new", "talking", "negotiating", "counter"];

const STEPS = ["طلب جديد", "جاري التواصل", "تفاوض", "تم الاتفاق"];

export default function InvRequestDetails() {
  const { params, navigate, goBack } = useWeb();
  const state = ((params.state as RDState) ?? "talking") as RDState;
  const meta = META[state];
  const detail = investorRequestDetails;
  const counter = investorCounterOffer;
  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelled, setCancelled] = useState(false);

  const currentState: RDState = cancelled ? "cancelled" : state;
  const currentMeta = META[currentState];
  const stepIndex = STEPS.indexOf(META[currentState].label);

  return (
    <div className="relative animate-fade-in bg-background-50">
      <Container className="py-8">
        <button
          type="button"
          onClick={goBack}
          className="inline-flex items-center gap-2 text-[13px] font-medium text-foreground-600 hover:text-foreground-950 cursor-pointer mb-5"
        >
          <i className="ri-arrow-right-line text-[17px] leading-none" />
          رجوع إلى المتابعة
        </button>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
          {/* Main */}
          <div className="lg:col-span-2 space-y-6">
            <WCard className="p-6">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 rounded-full overflow-hidden bg-background-200 shrink-0">
                  <img src={detail.businessLogo} alt={detail.businessName} className="w-full h-full object-cover object-top" />
                </div>
                <div className="flex-1 min-w-0">
                  <h1 className="text-[21px] font-bold text-foreground-950 font-heading truncate">{detail.businessName}</h1>
                  <p className="text-[13px] text-foreground-600 mt-0.5">عرض استثماري • {detail.date}</p>
                </div>
                <StatusPill tone={currentMeta.tone}>{currentMeta.label}</StatusPill>
              </div>
            </WCard>

            {/* Timeline */}
            <WCard className="p-6">
              <h2 className="text-[16px] font-bold text-foreground-950 mb-5">حالة الطلب</h2>
              <div className="flex items-center">
                {STEPS.map((s, i) => {
                  const done = stepIndex >= i && currentState !== "rejected" && currentState !== "cancelled";
                  return (
                    <div key={s} className="flex items-center flex-1 last:flex-none">
                      <div className="flex flex-col items-center gap-2">
                        <span
                          className={cn(
                            "w-9 h-9 rounded-full flex items-center justify-center text-[14px] font-bold shrink-0",
                            done ? "bg-accent-500 text-accent-950" : "bg-background-200 text-foreground-500",
                          )}
                        >
                          {done ? <i className="ri-check-line text-[16px] leading-none" /> : i + 1}
                        </span>
                        <span className={cn("text-[11.5px] font-medium whitespace-nowrap", done ? "text-foreground-900" : "text-foreground-500")}>{s}</span>
                      </div>
                      {i < STEPS.length - 1 && <span className={cn("flex-1 h-1 rounded-full mx-1.5 mb-6", stepIndex > i && currentState !== "rejected" && currentState !== "cancelled" ? "bg-accent-500" : "bg-background-200")} />}
                    </div>
                  );
                })}
              </div>
            </WCard>

            {/* Offer details */}
            <WCard className="p-6">
              <h2 className="text-[16px] font-bold text-foreground-950 mb-4">تفاصيل العرض</h2>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <Info label="قيمة العرض" value={`${fmt(detail.amount)} ر.س`} />
                <Info label="النسبة المطلوبة" value={`${detail.equity}%`} valueClass="text-accent-700" />
                <Info label="تاريخ التقديم" value={detail.date} />
                <Info label="نوع الطلب" value="استثمار مباشر" />
              </div>

              {currentState === "counter" && (
                <div className="mt-5 rounded-[16px] bg-secondary-50 border border-secondary-200 p-5">
                  <div className="flex items-center gap-2 mb-3">
                    <i className="ri-exchange-line text-[19px] text-secondary-800 leading-none" />
                    <h3 className="text-[14.5px] font-bold text-foreground-950">عرض مقابل من المنشأة</h3>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-[11.5px] text-foreground-600">القيمة المطلوبة</p>
                      <p className="text-[17px] font-bold text-foreground-950 mt-1">{fmt(counter.counterAmount)} ر.س</p>
                    </div>
                    <div>
                      <p className="text-[11.5px] text-foreground-600">النسبة المعروضة</p>
                      <p className="text-[17px] font-bold text-secondary-900 mt-1">{counter.counterEquity}%</p>
                    </div>
                  </div>
                </div>
              )}

              {currentState === "rejected" && (
                <div className="mt-5 rounded-[16px] bg-danger-50 border border-danger-200 p-4">
                  <p className="text-[12px] font-semibold text-danger-700 mb-1">سبب الرفض</p>
                  <p className="text-[13px] text-foreground-700 leading-relaxed">
                    تم رفض العرض من قبل صاحب المنشأة دون فتح محادثة.
                  </p>
                </div>
              )}
            </WCard>

            {currentState === "agreed" && (
              <WCard className="p-6 border-accent-200 bg-accent-50">
                <div className="flex items-center gap-2.5">
                  <span className="w-9 h-9 rounded-[11px] bg-accent-100 text-accent-800 flex items-center justify-center shrink-0">
                    <i className="ri-file-shield-2-line text-[18px] leading-none" />
                  </span>
                  <div>
                    <h2 className="text-[16px] font-bold text-foreground-950">ملخص الاتفاق — سجل مرجعي</h2>
                    <p className="text-[11.5px] text-foreground-600 mt-1">تم تثبيت هذا الملخص بعد الاتفاق، ويمكنك الرجوع له في أي وقت</p>
                  </div>
                </div>

                <div className="mt-4 rounded-[14px] bg-background-100 border border-accent-200/70 p-4 space-y-2.5">
                  <RowLine label="الطرف الأول (المنشأة)" value={detail.businessName} />
                  <RowLine label="الطرف الثاني (المستثمر)" value="أنت" />
                  <div className="h-px bg-background-200" />
                  <RowLine label="قيمة الاستثمار" value={`${fmt(counter.counterAmount)} ر.س`} />
                  <RowLine label="النسبة المتفق عليها" value={`${counter.counterEquity}%`} />
                  <RowLine label="تاريخ الاتفاق" value={detail.date} />
                </div>

                <div className="mt-3 rounded-[12px] bg-background-100/70 border border-accent-200/60 p-3.5">
                  <p className="text-[11px] font-semibold text-foreground-600 mb-1">آخر ملاحظة متفق عليها</p>
                  <p className="text-[12.5px] text-foreground-800 leading-relaxed">
                    تم الاتفاق على الشروط النهائية والجدول الزمني لضخ مبلغ الاستثمار مقابل نسبة الملكية المذكورة أعلاه.
                  </p>
                </div>
              </WCard>
            )}

            <WCard className="p-6">
              <h2 className="text-[16px] font-bold text-foreground-950 mb-3">الرسالة المرفقة</h2>
              <p className="text-[14px] text-foreground-700 leading-relaxed">
                أرغب بالاستثمار في المنشأة ضمن خطتها للتوسع، مع الإسهام في تطوير العمليات وزيادة قاعدة العملاء.
              </p>
            </WCard>
          </div>

          {/* Sticky side card */}
          <div className=" space-y-4">
            <WCard className="p-6">
              <h3 className="text-[16px] font-bold text-foreground-950">ملخص الطلب</h3>
              <div className="mt-4 space-y-3">
                <RowLine label="قيمة العرض" value={`${fmt(detail.amount)} ر.س`} />
                <RowLine label="النسبة المطلوبة" value={`${detail.equity}%`} />
                <RowLine label="الحالة" value={currentMeta.label} />
              </div>

              <div className="space-y-3 mt-6">
                {CAN_CHAT.includes(currentState) && (
                  <WBtn full icon="ri-chat-3-line" onClick={() => navigate("invChats", { chatId: "ic2" } as WebParams)}>
                    فتح المحادثة
                  </WBtn>
                )}
                {CAN_CANCEL.includes(currentState) && (
                  <WBtn full variant="secondary" icon="ri-close-circle-line" onClick={() => setCancelOpen(true)}>
                    إلغاء العرض
                  </WBtn>
                )}
                <WBtn full variant="ghost" icon="ri-store-2-line" onClick={() => navigate("business", { businessId: detail.businessId })}>
                  صفحة المنشأة
                </WBtn>
              </div>
            </WCard>

            <WCard className="p-5">
              <StatusPill tone="info" icon="ri-shield-check-line">عرضك محمي بسياسة النزاعات</StatusPill>
            </WCard>
          </div>
        </div>
      </Container>

      {cancelOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40">
          <div className="w-full max-w-[480px] bg-background-50 rounded-[20px] border border-background-200 p-6 text-center">
            <span className="w-14 h-14 rounded-full bg-danger-100 text-danger-600 flex items-center justify-center mx-auto mb-4">
              <i className="ri-error-warning-line text-[28px] leading-none" />
            </span>
            <h3 className="text-[18px] font-bold text-foreground-950 font-heading">إلغاء العرض؟</h3>
            <p className="text-[13.5px] text-foreground-600 mt-2 leading-relaxed">
              يمكنك إلغاء العرض فقط قبل «تم الاتفاق». سيتم إبلاغ صاحب المنشأة.
            </p>
            <div className="flex gap-3 mt-6">
              <WBtn className="flex-1" variant="secondary" onClick={() => setCancelOpen(false)}>
                تراجع
              </WBtn>
              <WBtn
                className="flex-1"
                variant="danger"
                onClick={() => {
                  setCancelled(true);
                  setCancelOpen(false);
                }}
              >
                إلغاء العرض
              </WBtn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Info({ label, value, valueClass = "" }: { label: string; value: string; valueClass?: string }) {
  return (
    <div className="rounded-[14px] bg-background-50 border border-background-200 p-4">
      <p className="text-[11.5px] text-foreground-600">{label}</p>
      <p className={cn("text-[15px] font-bold text-foreground-950 mt-1", valueClass)}>{value}</p>
    </div>
  );
}

function RowLine({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-2">
      <span className="text-[12.5px] text-foreground-600">{label}</span>
      <span className="text-[13.5px] font-semibold text-foreground-950">{value}</span>
    </div>
  );
}