import { useState } from "react";
import { investorOpportunities } from "@/mocks/dshnInvestor";
import { useWeb } from "@/pages/web/WebContext";
import { Container, WCard, WBtn, WInput, WTextarea, Field, StatusPill, cn, fmt } from "@/pages/web/WebUI";

export default function InvOffer() {
  const { params, goBack, navigate, requireAuth } = useWeb();
  const opp = investorOpportunities.find((o) => o.id === params.opportunityId) ?? investorOpportunities[0];

  const [stage, setStage] = useState<"form" | "sent" | "counter">("form");
  const [amount, setAmount] = useState(String(opp.amount));
  const [equity, setEquity] = useState(String(opp.equity));
  const [message, setMessage] = useState("");
  const [notes, setNotes] = useState("");
  const [counterDecision, setCounterDecision] = useState<"none" | "accepted" | "negotiating" | "rejected">("none");

  const valid = amount.trim() !== "" && equity.trim() !== "" && message.trim().length > 3;

  if (stage === "sent" && counterDecision === "none") {
    return (
      <div className="animate-fade-in">
        <Container className="py-14 max-w-[560px]">
          <WCard className="p-8 text-center">
            <span className="w-20 h-20 rounded-full bg-accent-100 text-accent-800 flex items-center justify-center mx-auto mb-6">
              <i className="ri-checkbox-circle-line text-[42px] leading-none" />
            </span>
            <h1 className="text-[24px] font-bold text-foreground-950 font-heading">تم إرسال عرضك بنجاح</h1>
            <p className="text-[14px] text-foreground-600 mt-2 leading-relaxed">
              سيتم إشعارك عند مراجعة صاحب المنشأة لعرضك. يمكنك متابعة الحالة من قسم «المتابعة».
            </p>
            <div className="mt-6 rounded-[16px] bg-background-50 border border-background-200 p-5 text-start space-y-3">
              <RowLine label="المنشأة" value={opp.businessName} />
              <RowLine label="قيمة العرض" value={`${fmt(Number(amount) || 0)} ر.س`} />
              <RowLine label="النسبة المطلوبة" value={`${equity}%`} />
            </div>
            <div className="space-y-3 mt-6">
              <WBtn full onClick={() => navigate("chats")}>فتح المحادثة</WBtn>
              <WBtn full variant="secondary" onClick={() => setStage("counter")}>تجربة حالة العرض المقابل</WBtn>
              <button type="button" onClick={() => navigate("invFollowing")} className="w-full text-center text-[13px] font-medium text-foreground-600 hover:text-foreground-950 cursor-pointer">
                الذهاب إلى المتابعة
              </button>
            </div>
          </WCard>
        </Container>
      </div>
    );
  }

  if (stage === "counter") {
    return (
      <div className="animate-fade-in">
        <Container className="py-14 max-w-[620px]">
          <WCard className="p-8">
            <div className="flex items-center gap-2.5">
              <i className="ri-exchange-line text-[21px] text-secondary-800 leading-none" />
              <h1 className="text-[20px] font-bold text-foreground-950 font-heading">مراجعة العرض المقابل</h1>
            </div>
            <p className="text-[13px] text-foreground-600 mt-2">عرض مقابل من {opp.businessName}</p>

            <div className="grid grid-cols-2 gap-3.5 mt-5">
              <div className="rounded-[16px] bg-secondary-50 border border-secondary-200 p-4">
                <p className="text-[11.5px] text-foreground-600">القيمة المطلوبة</p>
                <p className="text-[18px] font-bold text-foreground-950 mt-1">{fmt(opp.amount)} ر.س</p>
              </div>
              <div className="rounded-[16px] bg-secondary-50 border border-secondary-200 p-4">
                <p className="text-[11.5px] text-foreground-600">النسبة المعروضة</p>
                <p className="text-[18px] font-bold text-secondary-900 mt-1">{opp.equity}%</p>
              </div>
            </div>
            <p className="text-[13px] text-foreground-700 mt-4 leading-relaxed">
              عرضك السابق: {fmt(Number(amount) || 0)} ر.س مقابل {equity}%. هل توافق على العرض المقابل؟
            </p>

            {counterDecision === "none" ? (
              <div className="flex flex-col sm:flex-row gap-3 mt-6">
                <WBtn className="flex-1" icon="ri-check-line" onClick={() => setCounterDecision("accepted")}>قبول العرض المقابل</WBtn>
                <WBtn className="flex-1" variant="secondary" icon="ri-chat-3-line" onClick={() => setCounterDecision("negotiating")}>مواصلة التفاوض</WBtn>
                <WBtn className="flex-1" variant="ghost" icon="ri-close-line" onClick={() => setCounterDecision("rejected")}>رفض العرض</WBtn>
              </div>
            ) : (
              <div className="mt-6">
                {counterDecision === "accepted" && (
                  <div className="flex items-center gap-2 rounded-[14px] bg-accent-50 border border-accent-200 px-4 py-3.5 mb-4">
                    <i className="ri-checkbox-circle-fill text-[19px] text-accent-700 leading-none" />
                    <span className="text-[13px] text-accent-800">تم قبول العرض المقابل — سيتم فتح المحادثة لتسجيل القيمة.</span>
                  </div>
                )}
                {counterDecision === "negotiating" && (
                  <div className="flex items-center gap-2 rounded-[14px] bg-secondary-50 border border-secondary-200 px-4 py-3.5 mb-4">
                    <i className="ri-chat-3-line text-[19px] text-secondary-800 leading-none" />
                    <span className="text-[13px] text-secondary-900">تم إرسال طلب مواصلة التفاوض لصاحب المنشأة.</span>
                  </div>
                )}
                {counterDecision === "rejected" && (
                  <div className="flex items-center gap-2 rounded-[14px] bg-danger-50 border border-danger-200 px-4 py-3.5 mb-4">
                    <i className="ri-close-circle-fill text-[19px] text-danger-600 leading-none" />
                    <span className="text-[13px] text-danger-700">تم رفض العرض المقابل.</span>
                  </div>
                )}
                <WBtn full onClick={() => navigate("chats")}>فتح المحادثة</WBtn>
              </div>
            )}

            <button type="button" onClick={() => setStage("form")} className="w-full text-center text-[12.5px] text-foreground-500 hover:text-foreground-800 mt-4 cursor-pointer">
              رجوع للنموذج
            </button>
          </WCard>
        </Container>
      </div>
    );
  }

  return (
    <div className="animate-fade-in">
      <Container className="py-8 max-w-[720px]">
        <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>

        <h1 className="text-[26px] md:text-[30px] font-bold text-foreground-950 font-heading mb-6">تقديم عرض استثمار</h1>

        <WCard className="p-6">
          <div className="flex items-center gap-3.5 pb-5 border-b border-background-200">
            <div className="w-[52px] h-[52px] rounded-full overflow-hidden bg-background-200 shrink-0">
              <img src={opp.businessLogo} alt={opp.businessName} className="w-full h-full object-cover object-top" />
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-[15px] font-semibold text-foreground-950 truncate">{opp.businessName}</h3>
              <p className="text-[12px] text-foreground-600 mt-0.5">{opp.businessActivity} • {opp.businessCity}</p>
            </div>
            <StatusPill tone="success">{opp.equity}% معروضة</StatusPill>
          </div>

          <div className="space-y-5 mt-6">
            <Field label="قيمة الاستثمار المقترحة (ر.س)">
              <WInput dir="ltr" value={amount} onChange={(v) => setAmount(v.replace(/\D/g, ""))} placeholder="0" />
            </Field>
            <Field label="النسبة المطلوبة (%)">
              <WInput dir="ltr" value={equity} onChange={(v) => setEquity(v.replace(/\D/g, "").slice(0, 2))} placeholder="0" />
            </Field>
            <Field label="رسالة لصاحب المشروع">
              <WTextarea value={message} onChange={setMessage} placeholder="اكتب رسالتك لصاحب المنشأة توضح فيها رغبتك وملاحظاتك..." rows={4} />
            </Field>
            <Field label="ملاحظات إضافية" hint="اختياري">
              <WTextarea value={notes} onChange={setNotes} placeholder="أي تفاصيل إضافية ترغب بإضافتها..." rows={3} />
            </Field>
          </div>
        </WCard>

        <div className="flex flex-col sm:flex-row gap-3 mt-6">
          <WBtn
            className="flex-1"
            size="lg"
            disabled={!valid}
            onClick={() => requireAuth("investor", () => setStage("sent"))}
          >
            إرسال العرض
          </WBtn>
          <WBtn className="flex-1" size="lg" variant="secondary" onClick={goBack}>
            إلغاء
          </WBtn>
        </div>
      </Container>
    </div>
  );
}

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