import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Btn } from "@/pages/app/components/ui";
import { SuccessBlock } from "@/pages/app/components/bo/BoUI";
import { fmt } from "@/pages/app/components/biz/BizUI";
import { bizNegotiations } from "@/mocks/dshnBizDeals";

export default function BizInvoiceForm() {
  const { goBack, params, navigate } = useApp();
  const req = bizNegotiations.find((n) => n.id === params.requestId) ?? bizNegotiations[0];

  const [prices, setPrices] = useState<string[]>(req.items.map(() => ""));
  const [sent, setSent] = useState(false);

  const setPrice = (i: number, v: string) => {
    setPrices((p) => {
      const next = [...p];
      next[i] = v.replace(/\D/g, "");
      return next;
    });
  };

  const lineTotal = (i: number) => (Number(prices[i]) || 0) * req.items[i].qty;
  const total = req.items.reduce((sum, _it, i) => sum + lineTotal(i), 0);
  const valid = prices.every((p) => Number(p) > 0);

  if (sent) {
    return (
      <div className="min-h-full flex flex-col bg-background-50">
        <BackHeader title="رفع فاتورة" onBack={goBack} />
        <div className="flex-1 flex flex-col">
          <SuccessBlock
            title="تم رفع الفاتورة"
            desc={`أُرسلت الفاتورة بقيمة ${fmt(total)} ر.س إلى العميل ${req.customer}.`}
          >
            <div className="w-full max-w-[300px] mt-5 space-y-2 text-right">
              <div className="flex items-center gap-2 rounded-[14px] bg-accent-50 border border-accent-200 px-3.5 py-3">
                <i className="ri-checkbox-circle-fill text-[18px] text-accent-600 leading-none" />
                <span className="text-[12.5px] text-accent-800">تم رفع الفاتورة</span>
              </div>
              <div className="flex items-center gap-2 rounded-[14px] bg-secondary-50 border border-secondary-200 px-3.5 py-3">
                <i className="ri-time-line text-[18px] text-secondary-800 leading-none" />
                <span className="text-[12.5px] text-secondary-900">
                  بعد موافقة العميل تتحول الحالة إلى «تم الاتفاق»
                </span>
              </div>
            </div>
          </SuccessBlock>
        </div>
        <div className="sticky bottom-0 z-30 px-4 py-4 bg-background-50 border-t border-background-200/70">
          <Btn full onClick={() => navigate("bizNegotiationChat", { requestId: req.id })}>
            الرجوع للمحادثة
          </Btn>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title="رفع فاتورة" onBack={goBack} />

      <div className="flex-1 px-4 py-5 space-y-4">
        <div className="rounded-[16px] bg-background-100 border border-background-200 p-3.5 flex items-center gap-3">
          <div className="w-11 h-11 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">
            <p className="text-[13px] font-semibold text-foreground-950 truncate">{req.customer}</p>
            <p className="text-[11px] text-foreground-600 mt-0.5">{req.city}</p>
          </div>
        </div>

        <div className="space-y-3">
          {req.items.map((it, i) => (
            <div key={it.name} className="rounded-[18px] bg-background-100 border border-background-200 p-4">
              <div className="flex items-start justify-between gap-2">
                <p className="text-[13px] font-semibold text-foreground-950 leading-snug">{it.name}</p>
                <span className="shrink-0 whitespace-nowrap text-[11.5px] font-medium text-foreground-600">
                  الكمية: {it.qty}
                </span>
              </div>

              <div className="mt-3">
                <label className="block text-[12px] font-semibold text-foreground-900 mb-1.5">
                  السعر المتفق عليه للوحدة (ر.س)
                </label>
                <input
                  value={prices[i]}
                  onChange={(e) => setPrice(i, e.target.value)}
                  placeholder="0"
                  dir="ltr"
                  inputMode="numeric"
                  className="w-full h-[52px] px-4 rounded-[13px] bg-background-50 border border-background-200 text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 transition-colors font-body"
                />
              </div>

              <div className="flex items-center justify-between mt-3 rounded-[12px] bg-background-200/70 px-3.5 py-2.5">
                <span className="text-[12px] text-foreground-600">إجمالي السطر</span>
                <span className="text-[13.5px] font-bold text-foreground-950">{fmt(lineTotal(i))} ر.س</span>
              </div>
            </div>
          ))}
        </div>

        <div className="rounded-[18px] bg-primary-500 p-4 flex items-center justify-between">
          <span className="text-[13.5px] font-semibold text-background-50">إجمالي الفاتورة</span>
          <span className="text-[20px] font-bold text-background-50 whitespace-nowrap">{fmt(total)} ر.س</span>
        </div>

        <div className="flex items-start gap-2 rounded-[14px] bg-background-100 border border-background-200 px-3.5 py-3">
          <i className="ri-information-line text-[17px] text-foreground-500 leading-none mt-0.5" />
          <span className="text-[11.5px] text-foreground-600 leading-relaxed">
            الفاتورة لتثبيت السعر المتفق عليه ولا تمثل عملية دفع. إن لم يوافق العميل، يمكنك رفع فاتورة معدّلة.
          </span>
        </div>
      </div>

      <div className="sticky bottom-0 z-30 px-4 py-4 bg-background-50 border-t border-background-200/70">
        <Btn full disabled={!valid} onClick={() => setSent(true)}>
          إرسال الفاتورة للعميل
        </Btn>
      </div>
    </div>
  );
}