/* global React, I, UI */
// =============== ตรวจสินค้า + รูปก่อน/หลังส่ง + ลายเซ็นลูกค้า ===============
const { useState: useStateChk, useRef: useRefChk, useEffect: useEffectChk } = React;

// ---------- Signature pad ----------
function SignaturePad({ value, onChange }) {
  const canvasRef = useRefChk(null);
  const drawing = useRefChk(false);
  const dirty = useRefChk(false);

  useEffectChk(() => {
    const c = canvasRef.current;
    const ctx = c.getContext("2d");
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.lineWidth = 2.4;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.strokeStyle = "#1c1917";
    if (value) {
      const img = new Image();
      img.onload = () => ctx.drawImage(img, 0, 0, c.width, c.height);
      img.src = value;
    }
  }, []);

  const pos = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    return [(e.clientX - r.left) * (canvasRef.current.width / r.width), (e.clientY - r.top) * (canvasRef.current.height / r.height)];
  };
  const down = (e) => {
    e.preventDefault();
    canvasRef.current.setPointerCapture(e.pointerId);
    drawing.current = true;
    const ctx = canvasRef.current.getContext("2d");
    const [x, y] = pos(e);
    ctx.beginPath(); ctx.moveTo(x, y);
  };
  const move = (e) => {
    if (!drawing.current) return;
    const ctx = canvasRef.current.getContext("2d");
    const [x, y] = pos(e);
    ctx.lineTo(x, y); ctx.stroke();
    dirty.current = true;
  };
  const up = () => {
    if (!drawing.current) return;
    drawing.current = false;
    if (dirty.current) onChange(canvasRef.current.toDataURL("image/png"));
  };
  const clear = () => {
    const c = canvasRef.current;
    const ctx = c.getContext("2d");
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, c.width, c.height);
    dirty.current = false;
    onChange(null);
  };

  return (
    <div style={{display: "flex", flexDirection: "column", gap: 6}}>
      <canvas
        ref={canvasRef} width={620} height={200}
        onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerLeave={up}
        style={{width: "100%", height: 150, background: "white", border: "1.5px dashed var(--line-strong)", borderRadius: 8, cursor: "crosshair", touchAction: "none", display: "block"}}
      ></canvas>
      <div style={{display: "flex", alignItems: "center", justifyContent: "space-between"}}>
        <span style={{fontSize: 11, color: "var(--ink-3)"}}>ให้ลูกค้าเซ็นชื่อในกรอบด้านบน (ใช้นิ้วหรือเมาส์)</span>
        <button className="btn sm" onClick={clear}>ล้างลายเซ็น</button>
      </div>
    </div>
  );
}

// ---------- Photo strip uploader ----------
function PhotoStrip({ label, photos, onChange, hint }) {
  const pick = async (e) => {
    const files = [...e.target.files];
    e.target.value = "";
    const loaded = [];
    for (const f of files) {
      const url = await window.DeliveryStore.resizeImage(f);
      if (url) loaded.push({ url, name: f.name });
    }
    onChange([...photos, ...loaded]);
  };
  return (
    <div className="field">
      <label>{label}</label>
      <div style={{display: "flex", gap: 8, flexWrap: "wrap", alignItems: "flex-start"}}>
        {photos.map((p, i) => (
          <div key={i} style={{position: "relative", width: 76, height: 76}}>
            <img src={p.url} alt={p.name || "photo"} style={{width: 76, height: 76, objectFit: "cover", borderRadius: 6, border: "1px solid var(--line)", display: "block"}}/>
            <button onClick={() => onChange(photos.filter((_, j) => j !== i))} style={{position: "absolute", top: 3, right: 3, width: 18, height: 18, borderRadius: "50%", background: "rgba(0,0,0,0.72)", color: "white", border: 0, cursor: "pointer", fontSize: 11, lineHeight: "16px", padding: 0}}>×</button>
          </div>
        ))}
        <label style={{width: 76, height: 76, border: "1.5px dashed var(--line-strong)", borderRadius: 6, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4, cursor: "pointer", color: "var(--ink-3)", background: "var(--surface-2)"}}>
          <input type="file" accept="image/*" capture="environment" multiple style={{display: "none"}} onChange={pick}></input>
          <I.camera size={18}/>
          <span style={{fontSize: 10}}>ถ่าย/แนบรูป</span>
        </label>
      </div>
      {hint && <div style={{fontSize: 11, color: "var(--ink-3)", marginTop: 4}}>{hint}</div>}
    </div>
  );
}

// ---------- Step header ----------
function StepHead({ n, title, done, right }) {
  return (
    <div style={{display: "flex", alignItems: "center", gap: 10, marginBottom: 8}}>
      <div style={{width: 24, height: 24, borderRadius: "50%", flexShrink: 0, display: "grid", placeItems: "center", fontSize: 12, fontWeight: 700, background: done ? "var(--success)" : "var(--surface-3)", color: done ? "white" : "var(--ink-2)"}}>
        {done ? <I.check size={12}/> : n}
      </div>
      <div style={{fontSize: 13.5, fontWeight: 600, flex: 1}}>{title}</div>
      {right}
    </div>
  );
}

// ---------- Main check modal ----------
function DeliveryCheckModal({ delivery, onClose, onSave }) {
  const { Btn, Badge } = window.UI;
  const d = window.DeliveryStore.normalize(delivery);
  const [items, setItems] = useStateChk(d.items);
  const [photosBefore, setPhotosBefore] = useStateChk(d.photosBefore || []);
  const [photosAfter, setPhotosAfter] = useStateChk(d.photosAfter || []);
  const [signature, setSignature] = useStateChk(d.signature || null);
  const [receiverName, setReceiverName] = useStateChk(d.receiverName || "");
  const [viewer, setViewer] = useStateChk(null);

  const allChecked = items.length > 0 && items.every(it => it.checked);
  const stepsDone = [allChecked, photosBefore.length > 0, photosAfter.length > 0, !!signature && !!receiverName.trim()];
  const doneCount = stepsDone.filter(Boolean).length;
  const canComplete = stepsDone.every(Boolean);

  const toggleItem = (i) => setItems(list => list.map((it, j) => j === i ? { ...it, checked: !it.checked } : it));

  const patch = () => ({ items, photosBefore, photosAfter, signature, receiverName: receiverName.trim() });

  const saveDraft = () => {
    onSave({ ...patch(), status: d.status === "ส่งแล้ว" ? "ส่งแล้ว" : "กำลังจัดส่ง" });
    window.toast && window.toast("บันทึกความคืบหน้าแล้ว");
  };
  const complete = () => {
    if (!canComplete) {
      const missing = [];
      if (!stepsDone[0]) missing.push("ตรวจนับสินค้าให้ครบทุกรายการ");
      if (!stepsDone[1]) missing.push("แนบรูปก่อนส่ง");
      if (!stepsDone[2]) missing.push("แนบรูปหลังส่ง");
      if (!stepsDone[3]) missing.push("ลายเซ็น + ชื่อผู้รับ");
      window.toast && window.toast("ยังขาด: " + missing.join(" · "));
      return;
    }
    const now = new Date();
    const hh = String(now.getHours()).padStart(2, "0");
    const mm = String(now.getMinutes()).padStart(2, "0");
    onSave({ ...patch(), status: "ส่งแล้ว", deliveredAt: `${hh}:${mm}` });
    window.logActivity && window.logActivity("ส่งของสำเร็จ", `${d.no} · ${d.customer}`, "delivery");
    window.toast && window.toast(`ส่งของ ${d.no} สำเร็จ — ลูกค้าเซ็นรับแล้ว`);
  };

  return (
    <div className="scrim" style={{display: "flex", alignItems: "center", justifyContent: "center", padding: 18, zIndex: 220}} onClick={onClose}>
      <div style={{background: "var(--surface)", borderRadius: 14, width: 680, maxWidth: "96vw", maxHeight: "94vh", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "var(--shadow-lg)"}} onClick={e => e.stopPropagation()}>

        {/* Head */}
        <div style={{padding: "16px 20px 12px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12}}>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap"}}>
              <span style={{fontSize: 15, fontWeight: 700}}>ตรวจ + ส่งของ — {d.customer}</span>
              <Badge>{d.status}</Badge>
            </div>
            <div style={{fontSize: 12, color: "var(--ink-3)", marginTop: 2}}>
              <span className="mono">{d.no}</span> · นัดส่ง {d.time} น. · ผู้ส่ง {d.assigneeName}
            </div>
          </div>
          <div style={{fontSize: 11.5, color: doneCount === 4 ? "var(--success)" : "var(--ink-3)", fontWeight: 600, whiteSpace: "nowrap"}}>{doneCount}/4 ขั้นตอน</div>
          <button className="icon-btn" onClick={onClose}><I.close size={14}/></button>
        </div>

        {/* Body */}
        <div style={{padding: "16px 20px", overflow: "auto", display: "flex", flexDirection: "column", gap: 18}}>

          {/* 1: item check */}
          <div>
            <StepHead n={1} title="ตรวจนับสินค้าตามรูป" done={stepsDone[0]}
              right={<button className="btn sm" onClick={() => setItems(list => list.map(it => ({ ...it, checked: true })))}>ติ๊กครบทุกรายการ</button>}/>
            <div style={{display: "flex", flexDirection: "column", gap: 6}}>
              {items.map((it, i) => (
                <label key={i} style={{display: "flex", alignItems: "center", gap: 12, padding: "8px 10px", border: `1px solid ${it.checked ? "var(--success)" : "var(--line)"}`, borderRadius: 8, cursor: "pointer", background: it.checked ? "var(--success-bg)" : "var(--surface)"}}>
                  <input type="checkbox" checked={!!it.checked} onChange={() => toggleItem(i)} style={{width: 17, height: 17, accentColor: "var(--success)", flexShrink: 0}}></input>
                  {it.photo
                    ? <img src={it.photo} alt={it.name} onClick={(e) => { e.preventDefault(); setViewer(it.photo); }} style={{width: 52, height: 52, objectFit: "cover", borderRadius: 6, border: "1px solid var(--line)", flexShrink: 0, cursor: "zoom-in"}}/>
                    : <div style={{width: 52, height: 52, borderRadius: 6, border: "1px dashed var(--line-strong)", display: "grid", placeItems: "center", fontSize: 9, color: "var(--ink-4)", flexShrink: 0, textAlign: "center"}}>ไม่มีรูป</div>}
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 13, fontWeight: 500}}>{it.name}</div>
                    <div style={{fontSize: 11, color: "var(--ink-3)"}}>ตรวจจำนวนให้ตรงตามใบส่งของ</div>
                  </div>
                  <div style={{textAlign: "right", flexShrink: 0}}>
                    <div style={{fontSize: 18, fontWeight: 700}}>{it.qty}</div>
                    <div style={{fontSize: 10.5, color: "var(--ink-3)"}}>{it.unit}</div>
                  </div>
                </label>
              ))}
            </div>
          </div>

          {/* 2: before */}
          <div>
            <StepHead n={2} title="รูปถ่ายก่อนส่ง (ตอนขึ้นของ)" done={stepsDone[1]}/>
            <PhotoStrip label="" photos={photosBefore} onChange={setPhotosBefore} hint="ถ่ายสภาพสินค้าบนรถ / ก่อนออกจากโรงงาน อย่างน้อย 1 รูป"/>
          </div>

          {/* 3: after */}
          <div>
            <StepHead n={3} title="รูปถ่ายหลังส่ง (ถึงหน้างาน)" done={stepsDone[2]}/>
            <PhotoStrip label="" photos={photosAfter} onChange={setPhotosAfter} hint="ถ่ายสินค้าที่ส่งมอบแล้วหน้างานลูกค้า อย่างน้อย 1 รูป"/>
          </div>

          {/* 4: signature */}
          <div>
            <StepHead n={4} title="ลูกค้าเซ็นรับสินค้า" done={stepsDone[3]}/>
            <div style={{display: "flex", flexDirection: "column", gap: 10}}>
              <SignaturePad value={signature} onChange={setSignature}/>
              <div className="field">
                <label>ชื่อผู้รับสินค้า (ตัวบรรจง)</label>
                <input className="input" value={receiverName} onChange={e => setReceiverName(e.target.value)} placeholder="เช่น คุณพัชรา ศิลปกร"></input>
              </div>
            </div>
          </div>
        </div>

        {/* Foot */}
        <div style={{padding: "12px 20px", borderTop: "1px solid var(--line)", background: "var(--surface-2)", display: "flex", gap: 8, justifyContent: "flex-end", flexWrap: "wrap"}}>
          <Btn kind="ghost" onClick={onClose}>ปิด</Btn>
          <Btn icon={I.print} onClick={() => { onSave({ ...patch(), status: d.status }); setTimeout(() => window.printDeliveryA5({ ...d, ...patch() }), 150); }}>พิมพ์ใบส่งของ A5</Btn>
          <Btn onClick={saveDraft}>บันทึกความคืบหน้า</Btn>
          <Btn kind="primary" icon={I.check} onClick={complete} style={canComplete ? {} : {opacity: 0.55}}>ยืนยันส่งสำเร็จ</Btn>
        </div>
      </div>

      {viewer && (
        <div onClick={(e) => { e.stopPropagation(); setViewer(null); }} style={{position: "fixed", inset: 0, zIndex: 300, background: "rgba(0,0,0,0.8)", display: "flex", alignItems: "center", justifyContent: "center", padding: 30, cursor: "zoom-out"}}>
          <img src={viewer} alt="preview" style={{maxWidth: "92%", maxHeight: "92%", borderRadius: 8, boxShadow: "0 20px 60px rgba(0,0,0,0.5)"}}/>
        </div>
      )}
    </div>
  );
}

window.DeliveryCheckModal = DeliveryCheckModal;
window.DeliverySignaturePad = SignaturePad;
window.DeliveryPhotoStrip = PhotoStrip;
