import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Badge, Btn } from "@/pages/app/components/ui";
import { ConfirmModal, KvRow } from "@/pages/app/components/bo/BoUI";
import { fmt } from "@/pages/app/components/biz/BizUI";
import DealAgreementCard from "@/pages/app/components/biz/DealAgreementCard";
import { myBusiness } from "@/mocks/dshnBusiness";
import {
  bizInvestRequests,
  bizDealStatusLabel,
  bizDealStatusTone,
  bizCommissionRate,
  type BizDealStatus,
} from "@/mocks/dshnBizDeals";

export default function BizInvestRequest() {
  const { goBack, params, navigate } = useApp();
  const req = bizInvestRequests.find((r) => r.id === params.requestId) ?? bizInvestRequests[0];
  const [status, setStatus] = useState<BizDealStatus>(req.status);
  const [rejectConfirm, setRejectConfirm] = useState(false);
  const commission = Math.round((req.amount * bizCommissionRate) / 100);
  const agreedAmount = req.counterAmount ?? req.amount;
  const agreedEquity = req.counterEquity ?? req.equity;
  const showAgreement = ["agreed", "awaitValue", "registered", "commission", "done"].includes(status);
  const showActions = status === "new" || status === "talking" || status === "negotiating";

  return (
    <div className="min-h-full pb-8 bg-background-50">
      <BackHeader title="تفاصيل طلب الاستثمار" onBack={goBack} />

      <div className="px-4 py-5 space-y-4">
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <div className="flex items-center gap-3">
            <div className="w-14 h-14 rounded-full overflow-hidden bg-background-200 shrink-0">
              <img src={req.avatar} alt={req.investor} className="w-full h-full object-cover object-top" />
            </div>
            <div className="min-w-0 flex-1">
              <h2 className="text-[15px] font-semibold text-foreground-950">{req.investor}</h2>
              <p className="text-[11.5px] text-foreground-600 mt-0.5">مستثمر • {req.city}</p>
            </div>
            <Badge tone={bizDealStatusTone[status]}>{bizDealStatusLabel[status]}</Badge>
          </div>

          <div className="mt-3 rounded-[14px] bg-background-200/60 p-3">
            <p className="text-[11px] font-semibold text-foreground-700 mb-1">رسالة المستثمر</p>
            <p className="text-[12.5px] text-foreground-700 leading-relaxed">{req.message}</p>
          </div>
        </div>

        <div className="rounded-[18px] bg-background-100 border border-background-200 p-4 space-y-3">
          <KvRow label="المنشأة" value={myBusiness.name} />
          <div className="h-px bg-background-200" />
          <KvRow label="المبلغ المقترح" value={`${fmt(req.amount)} ر.س`} strong />
          <div className="h-px bg-background-200" />
          <KvRow label="النسبة المطلوبة" value={`${req.equity}%`} />
          <div className="h-px bg-background-200" />
          <KvRow label="تقييم المنشأة" value={`${fmt(myBusiness.currentValue)} ر.س`} />
          <div className="h-px bg-background-200" />
          <KvRow label="تاريخ الطلب" value={req.date} />
        </div>

        {showAgreement && (
          <DealAgreementCard
            reference={`DEAL-${req.id.toUpperCase()}`}
            businessName={myBusiness.name}
            investorName={req.investor}
            amount={req.dealValue ?? agreedAmount}
            equity={agreedEquity}
            date={req.date}
            note={
              req.message ||
              `تم الاتفاق على ضخ ${fmt(agreedAmount)} ر.س مقابل ${agreedEquity}% من المنشأة، مع تثبيت الشروط والجدول الزمني كما ورد في المحادثة.`
            }
            commission={req.commission ?? Math.round(agreedAmount * (bizCommissionRate / 100))}
          />
        )}

        {status === "talking" && (
          <div className="rounded-[14px] bg-accent-50 border border-accent-200 px-3.5 py-3 flex items-center gap-2">
            <i className="ri-checkbox-circle-fill text-[18px] text-accent-600 leading-none" />
            <span className="text-[12.5px] text-accent-800">
              تم القبول المبدئي — الحالة الآن «جاري التواصل». تتحول إلى «تفاوض» بعد تبادل الرسائل.
            </span>
          </div>
        )}
        {status === "rejected" && (
          <div className="rounded-[14px] bg-danger-50 border border-danger-200 px-3.5 py-3 flex items-center gap-2">
            <i className="ri-close-circle-fill text-[18px] text-danger-500 leading-none" />
            <span className="text-[12.5px] text-danger-700">تم رفض الطلب وإغلاقه، ولم تُفتح أي محادثة.</span>
          </div>
        )}

        {status === "agreed" && (
          <Btn full onClick={() => navigate("bizDealRecord", { requestId: req.id })}>
            <i className="ri-check-double-line text-[17px] leading-none" />
            تأكيد الاتفاق وتسجيل الصفقة
          </Btn>
        )}

        {status === "awaitValue" && (
          <>
            <div className="rounded-[14px] bg-secondary-50 border border-secondary-200 px-3.5 py-3 flex items-center gap-2">
              <i className="ri-hourglass-line text-[18px] text-secondary-900 leading-none" />
              <span className="text-[12.5px] text-secondary-900">بانتظار تسجيل قيمة الصفقة النهائية.</span>
            </div>
            <Btn full onClick={() => navigate("bizDealRecord", { requestId: req.id })}>
              <i className="ri-file-list-3-line text-[17px] leading-none" />
              تسجيل قيمة الصفقة
            </Btn>
          </>
        )}

        {(status === "registered" || status === "commission") && (
          <>
            <div className="rounded-[18px] bg-background-100 border border-background-200 p-4 space-y-3">
              <KvRow label="قيمة الصفقة" value={`${fmt(req.amount)} ر.س`} strong />
              <div className="h-px bg-background-200" />
              <KvRow label="نسبة العمولة" value={`${bizCommissionRate}%`} />
              <div className="h-px bg-background-200" />
              <KvRow label="قيمة العمولة المستحقة" value={`${fmt(commission)} ر.س`} strong />
            </div>
            <Btn full onClick={() => navigate("bizCommissions")}>
              <i className="ri-wallet-3-line text-[17px] leading-none" />
              متابعة العمولات المستحقة
            </Btn>
          </>
        )}

        {showActions && (
          <div className="grid grid-cols-2 gap-3">
            <Btn onClick={() => setStatus("talking")}>
              <i className="ri-check-line text-[17px] leading-none" />
              قبول مبدئي
            </Btn>
            <Btn variant="secondary" onClick={() => setRejectConfirm(true)}>
              <i className="ri-close-line text-[17px] leading-none" />
              رفض
            </Btn>
            <Btn variant="secondary" onClick={() => navigate("bizInvestCounter", { requestId: req.id })}>
              <i className="ri-exchange-line text-[17px] leading-none" />
              إرسال عرض مقابل
            </Btn>
            <Btn variant="secondary" onClick={() => navigate("bizInvestChat", { requestId: req.id })}>
              <i className="ri-chat-3-line text-[17px] leading-none" />
              بدء التواصل
            </Btn>
          </div>
        )}
      </div>

      <ConfirmModal
        open={rejectConfirm}
        title="رفض طلب الاستثمار؟"
        desc="سيتم إبلاغ المستثمر برفض طلبه وإغلاق الطلب دون فتح محادثة. لا يمكن التراجع."
        confirmLabel="رفض الطلب"
        danger
        onConfirm={() => {
          setStatus("rejected");
          setRejectConfirm(false);
        }}
        onCancel={() => setRejectConfirm(false)}
      />
    </div>
  );
}