import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Badge, Btn } from "@/pages/app/components/ui";
import { Field, TextArea } from "@/pages/app/components/bo/BoUI";
import NegStatusFlow from "@/pages/app/components/biz/NegStatusFlow";
import { bizNegotiations, bizNegStatusLabel, bizNegStatusTone, type BizNegStatus } from "@/mocks/dshnBizDeals";

export default function BizNegotiation() {
  const { goBack, params, navigate } = useApp();
  const req = bizNegotiations.find((n) => n.id === params.requestId) ?? bizNegotiations[0];
  const [status, setStatus] = useState<BizNegStatus>(req.status);
  const [rejectOpen, setRejectOpen] = useState(params.openReject === "1");
  const [reason, setReason] = useState("");

  const closed = status === "rejected";

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

      <div className="px-4 py-5 space-y-4">
        <NegStatusFlow status={status} />

        <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.customer} 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.customer}</h2>
              <p className="text-[11.5px] text-foreground-600 mt-0.5">عميل • {req.city}</p>
            </div>
            <Badge tone={bizNegStatusTone[status]}>{bizNegStatusLabel[status]}</Badge>
          </div>

          <div className="grid grid-cols-2 gap-2 mt-3">
            <div className="rounded-[12px] bg-background-200/70 p-2.5">
              <p className="text-[10px] text-foreground-600">رقم الجوال</p>
              <p className="text-[12.5px] font-semibold text-foreground-950 mt-0.5" dir="ltr">{req.phone}</p>
            </div>
            <div className="rounded-[12px] bg-background-200/70 p-2.5">
              <p className="text-[10px] text-foreground-600">تاريخ الطلب</p>
              <p className="text-[12.5px] font-semibold text-foreground-950 mt-0.5">{req.date}</p>
            </div>
          </div>

          {req.note && (
            <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.note}</p>
            </div>
          )}
        </div>

        <div className="rounded-[18px] bg-background-100 border border-background-200 p-4">
          <p className="text-[13px] font-semibold text-foreground-950 mb-3">المنتجات والكميات المطلوبة</p>
          <div className="divide-y divide-background-200">
            {req.items.map((it) => (
              <div key={it.name} className="flex items-center justify-between gap-3 py-2.5">
                <span className="text-[12.5px] text-foreground-800 leading-snug">{it.name}</span>
                <span className="shrink-0 whitespace-nowrap text-[12.5px] font-semibold text-foreground-950">
                  الكمية: {it.qty}
                </span>
              </div>
            ))}
          </div>
        </div>

        {status === "talking" && (
          <div className="rounded-[14px] bg-secondary-50 border border-secondary-200 px-3.5 py-3 flex items-center gap-2">
            <i className="ri-chat-3-line text-[18px] text-secondary-800 leading-none" />
            <span className="text-[12.5px] text-secondary-900">تم القبول — الحالة «قيد التواصل والتفاوض».</span>
          </div>
        )}
        {closed && (
          <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>
        )}

        {rejectOpen && !closed && (
          <div className="rounded-[18px] bg-background-100 border border-danger-200 p-4 space-y-3">
            <p className="text-[13px] font-semibold text-foreground-950">رفض الطلب</p>
            <Field label="سبب الرفض (اختياري)">
              <TextArea value={reason} onChange={setReason} placeholder="اكتب سبب الرفض..." rows={3} max={200} />
            </Field>
            <div className="grid grid-cols-2 gap-2.5">
              <Btn variant="secondary" onClick={() => setRejectOpen(false)}>
                إلغاء
              </Btn>
              <Btn
                variant="danger"
                onClick={() => {
                  setStatus("rejected");
                  setRejectOpen(false);
                }}
              >
                تأكيد الرفض
              </Btn>
            </div>
          </div>
        )}

        {!rejectOpen && status === "new" && (
          <div className="grid grid-cols-1 gap-2.5">
            <Btn
              onClick={() => {
                setStatus("talking");
                navigate("bizNegotiationChat", { requestId: req.id });
              }}
            >
              <i className="ri-chat-3-line text-[17px] leading-none" />
              قبول والدخول في التفاوض
            </Btn>
            <Btn variant="secondary" onClick={() => setRejectOpen(true)}>
              <i className="ri-close-line text-[17px] leading-none" />
              رفض الطلب
            </Btn>
          </div>
        )}

        {!rejectOpen && status === "talking" && (
          <div className="grid grid-cols-1 gap-2.5">
            <Btn onClick={() => navigate("bizNegotiationChat", { requestId: req.id })}>
              <i className="ri-chat-3-line text-[17px] leading-none" />
              فتح المحادثة
            </Btn>
            <Btn variant="secondary" onClick={() => navigate("bizInvoiceForm", { requestId: req.id })}>
              <i className="ri-file-add-line text-[17px] leading-none" />
              رفع فاتورة
            </Btn>
          </div>
        )}

        {!rejectOpen && status === "invoiced" && (
          <div className="grid grid-cols-1 gap-2.5">
            <Btn onClick={() => navigate("bizNegotiationChatInvoiced", { requestId: req.id })}>
              <i className="ri-chat-3-line text-[17px] leading-none" />
              عرض المحادثة
            </Btn>
            <Btn variant="secondary" onClick={() => navigate("bizNegotiationInvoiced", { requestId: req.id })}>
              <i className="ri-file-list-3-line text-[17px] leading-none" />
              عرض الفاتورة
            </Btn>
          </div>
        )}

        {!rejectOpen && status === "agreed" && (
          <Btn full onClick={() => navigate("bizNegotiationChatAgreed", { requestId: req.id })}>
            <i className="ri-chat-3-line text-[17px] leading-none" />
            فتح المحادثة
          </Btn>
        )}

        {!rejectOpen && status === "paid" && (
          <div className="grid grid-cols-1 gap-2.5">
            <Btn onClick={() => navigate("bizOrder", { orderId: req.paidOrderNumber })}>
              <i className="ri-shopping-bag-3-line text-[17px] leading-none" />
              عرض الطلب المدفوع
            </Btn>
            <Btn variant="secondary" onClick={() => navigate("bizNegotiationPaid", { requestId: req.id })}>
              <i className="ri-file-list-3-line text-[17px] leading-none" />
              تفاصيل الدفع
            </Btn>
          </div>
        )}
      </div>
    </div>
  );
}