// ============================================================
// entity-forms.jsx — CRUD forms for Products, Warehouses, Locations
// ============================================================

// ============ Product Form ============
function ProductForm({ open, onClose, onSave, initial, state }) {
  const isEdit = !!initial?._existing;
  const defaults = {
    sku: "", barcode: "", name: "", category: "", unit: "ขวด",
    reorderPoint: 50, costPrice: 0, sellPrice: 0, supplier: "", shelfLife: 180,
  };
  const [p, setP] = useState({ ...defaults, ...(initial || {}) });
  useEffect(() => { setP({ ...defaults, ...(initial || {}) }); }, [initial]);

  const categories = [...new Set(state.products.map(x => x.category))];
  const units = ["ขวด", "กระป๋อง", "ถุง", "แพ็ค", "ห่อ", "ถ้วย", "ชิ้น", "กล่อง"];

  const save = () => {
    if (!p.sku.trim() || !p.name.trim()) return alert("กรุณากรอก SKU และชื่อสินค้า");
    if (!isEdit && state.products.some(x => x.sku === p.sku.trim())) return alert("SKU นี้มีในระบบแล้ว");
    onSave({
      ...p,
      sku: p.sku.trim(),
      reorderPoint: Number(p.reorderPoint) || 0,
      costPrice: Number(p.costPrice) || 0,
      sellPrice: Number(p.sellPrice) || 0,
      shelfLife: Number(p.shelfLife) || 0,
    });
  };

  return (
    <Modal open={open} onClose={onClose}
      title={isEdit ? "แก้ไขสินค้า" : "เพิ่มสินค้าใหม่"} size="lg"
      footer={<>
        <button className="btn btn-secondary" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-accent" onClick={save}><Icon name="check" size={14}/> บันทึก</button>
      </>}>
      <div className="col" style={{ gap: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.5fr", gap: 12 }}>
          <div className="field">
            <label className="label">SKU {isEdit && <span className="muted">(แก้ไขไม่ได้)</span>}</label>
            <input className="input mono" value={p.sku} disabled={isEdit}
              onChange={e => setP({ ...p, sku: e.target.value.toUpperCase() })} placeholder="MLK-099"/>
          </div>
          <div className="field">
            <label className="label">ชื่อสินค้า</label>
            <input className="input" value={p.name} onChange={e => setP({ ...p, name: e.target.value })} placeholder="เช่น นมสดยูเอชที 1L"/>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <div className="field">
            <label className="label">บาร์โค้ด</label>
            <input className="input mono" value={p.barcode} onChange={e => setP({ ...p, barcode: e.target.value })} placeholder="8851234500000"/>
          </div>
          <div className="field">
            <label className="label">หมวดหมู่</label>
            <input className="input" list="cat-list" value={p.category}
              onChange={e => setP({ ...p, category: e.target.value })} placeholder="เช่น นม, น้ำผลไม้"/>
            <datalist id="cat-list">{categories.map(c => <option key={c} value={c}/>)}</datalist>
          </div>
          <div className="field">
            <label className="label">หน่วยนับ</label>
            <select className="select" value={p.unit} onChange={e => setP({ ...p, unit: e.target.value })}>
              {units.map(u => <option key={u}>{u}</option>)}
            </select>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <div className="field">
            <label className="label">ราคาทุน (฿)</label>
            <input type="number" className="input tnum" value={p.costPrice} onChange={e => setP({ ...p, costPrice: e.target.value })}/>
          </div>
          <div className="field">
            <label className="label">ราคาขาย (฿)</label>
            <input type="number" className="input tnum" value={p.sellPrice} onChange={e => setP({ ...p, sellPrice: e.target.value })}/>
          </div>
          <div className="field">
            <label className="label">จุดสั่งซื้อใหม่ (ต่ำสุด)</label>
            <input type="number" className="input tnum" value={p.reorderPoint} onChange={e => setP({ ...p, reorderPoint: e.target.value })}/>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 12 }}>
          <div className="field">
            <label className="label">Supplier</label>
            <input className="input" value={p.supplier} onChange={e => setP({ ...p, supplier: e.target.value })} placeholder="ผู้จัดจำหน่าย"/>
          </div>
          <div className="field">
            <label className="label">อายุการเก็บ (วัน)</label>
            <input type="number" className="input tnum" value={p.shelfLife} onChange={e => setP({ ...p, shelfLife: e.target.value })}/>
          </div>
        </div>

        {!isEdit && (
          <div className="hint" style={{ padding: 10, background: "var(--accent-soft)", color: "var(--accent)", borderRadius: 6 }}>
            <Icon name="info" size={13}/> สินค้าใหม่จะมีสต๊อก 0 — ใช้หน้า "รับเข้าสินค้า" เพื่อเติมสต๊อก
          </div>
        )}
      </div>
    </Modal>
  );
}

// ============ Warehouse Form ============
function WarehouseForm({ open, onClose, onSave, initial }) {
  const isEdit = !!initial?._existing;
  const defaults = { id: "", code: "", name: "", type: "อุณหภูมิห้อง", temp: "25°C" };
  const [w, setW] = useState({ ...defaults, ...(initial || {}) });
  useEffect(() => { setW({ ...defaults, ...(initial || {}) }); }, [initial]);

  const save = () => {
    if (!(w.code || "").trim() || !(w.name || "").trim()) return alert("กรุณากรอกรหัสและชื่อคลัง");
    const cleanCode = (w.code || "").trim().toUpperCase().replace(/^WH-/, "");
    onSave({
      ...w,
      id: isEdit ? w.id : `WH-${cleanCode}`,
      code: `WH-${cleanCode}`,
    });
  };

  return (
    <Modal open={open} onClose={onClose}
      title={isEdit ? "แก้ไขคลังสินค้า" : "เพิ่มคลังสินค้าใหม่"}
      footer={<>
        <button className="btn btn-secondary" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-accent" onClick={save}><Icon name="check" size={14}/> บันทึก</button>
      </>}>
      <div className="col" style={{ gap: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12 }}>
          <div className="field">
            <label className="label">รหัสคลัง {isEdit && <span className="muted">(แก้ไม่ได้)</span>}</label>
            <div className="input-with-prefix">
              <span className="input-prefix mono text-xs" style={{ left: 12 }}>WH-</span>
              <input className="input mono" style={{ paddingLeft: 42 }}
                disabled={isEdit}
                value={(w.code || "").replace(/^WH-/, "")}
                onChange={e => setW({ ...w, code: e.target.value.toUpperCase() })}
                placeholder="E"/>
            </div>
          </div>
          <div className="field">
            <label className="label">ชื่อคลัง</label>
            <input className="input" value={w.name} onChange={e => setW({ ...w, name: e.target.value })} placeholder="เช่น คลังภาคตะวันออก ระยอง"/>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div className="field">
            <label className="label">ประเภทคลัง</label>
            <select className="select" value={w.type} onChange={e => setW({ ...w, type: e.target.value })}>
              <option>อุณหภูมิห้อง</option>
              <option>ห้องเย็น</option>
              <option>ห้องแช่แข็ง</option>
              <option>คลังแห้ง</option>
            </select>
          </div>
          <div className="field">
            <label className="label">อุณหภูมิ</label>
            <input className="input" value={w.temp} onChange={e => setW({ ...w, temp: e.target.value })} placeholder="25°C"/>
          </div>
        </div>

        {!isEdit && (
          <div className="hint" style={{ padding: 10, background: "var(--accent-soft)", color: "var(--accent)", borderRadius: 6 }}>
            <Icon name="info" size={13}/> คลังใหม่จะมีโซน A พร้อมช่อง A1-A4 ให้เริ่มต้นใช้งาน
          </div>
        )}
      </div>
    </Modal>
  );
}

// ============ Location Form (single rack within a zone) ============
function LocationForm({ open, onClose, onSave, initial, warehouseId, existingLocations }) {
  const isEdit = !!initial?._existing;
  const defaults = { zone: "A", rack: 1, capacity: 500 };
  const [l, setL] = useState({ ...defaults, ...(initial || {}) });
  useEffect(() => { setL({ ...defaults, ...(initial || {}) }); }, [initial]);

  const save = () => {
    const zone = String(l.zone).toUpperCase().slice(0, 1);
    const rack = Number(l.rack);
    if (!zone || !rack) return alert("กรุณากรอกโซนและหมายเลขช่อง");
    const newId = `${warehouseId}-${zone}${rack}`;
    if (!isEdit && existingLocations.some(x => x.id === newId)) return alert(`ช่อง ${newId} มีอยู่แล้ว`);
    onSave({
      ...l,
      id: isEdit ? l.id : newId,
      warehouseId,
      zone, rack,
      code: `${zone}${rack}`,
      capacity: Number(l.capacity) || 500,
    });
  };

  return (
    <Modal open={open} onClose={onClose}
      title={isEdit ? "แก้ไขช่องเก็บสินค้า" : "เพิ่มช่องเก็บสินค้า"}
      footer={<>
        <button className="btn btn-secondary" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-accent" onClick={save}><Icon name="check" size={14}/> บันทึก</button>
      </>}>
      <div className="col" style={{ gap: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <div className="field">
            <label className="label">โซน (1 ตัวอักษร)</label>
            <input className="input mono" maxLength={1} disabled={isEdit}
              value={l.zone} onChange={e => setL({ ...l, zone: e.target.value.toUpperCase() })} placeholder="A"/>
          </div>
          <div className="field">
            <label className="label">หมายเลขช่อง</label>
            <input type="number" className="input tnum" disabled={isEdit} min="1"
              value={l.rack} onChange={e => setL({ ...l, rack: e.target.value })}/>
          </div>
          <div className="field">
            <label className="label">ความจุ (Capacity)</label>
            <input type="number" className="input tnum" min="1"
              value={l.capacity} onChange={e => setL({ ...l, capacity: e.target.value })}/>
          </div>
        </div>
        <div className="hint">
          รหัสช่อง: <span className="mono" style={{ color: "var(--fg)" }}>{warehouseId}-{String(l.zone || "").toUpperCase()}{l.rack || ""}</span>
        </div>
      </div>
    </Modal>
  );
}

// ============ Zone Form (bulk-create racks for a new zone) ============
function ZoneForm({ open, onClose, onSave, warehouseId, existingZones }) {
  const [zone, setZone] = useState("");
  const [racks, setRacks] = useState(4);
  const [capacity, setCapacity] = useState(500);

  useEffect(() => { if (open) { setZone(""); setRacks(4); setCapacity(500); } }, [open]);

  const save = () => {
    const z = zone.toUpperCase().slice(0, 1);
    if (!z) return alert("กรุณากรอกชื่อโซน (A-Z)");
    if (existingZones.includes(z)) return alert(`โซน ${z} มีอยู่แล้ว`);
    const n = Math.max(1, Math.min(20, Number(racks) || 1));
    const newLocs = [];
    for (let i = 1; i <= n; i++) {
      newLocs.push({
        id: `${warehouseId}-${z}${i}`,
        warehouseId, zone: z, rack: i,
        code: `${z}${i}`,
        capacity: Number(capacity) || 500,
      });
    }
    onSave(newLocs);
  };

  return (
    <Modal open={open} onClose={onClose}
      title="เพิ่มโซนใหม่"
      footer={<>
        <button className="btn btn-secondary" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-accent" onClick={save}><Icon name="check" size={14}/> สร้างโซน</button>
      </>}>
      <div className="col" style={{ gap: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <div className="field">
            <label className="label">ชื่อโซน (A-Z)</label>
            <input className="input mono" maxLength={1} value={zone}
              onChange={e => setZone(e.target.value.toUpperCase())} placeholder="E" autoFocus/>
          </div>
          <div className="field">
            <label className="label">จำนวนช่อง</label>
            <input type="number" className="input tnum" min="1" max="20"
              value={racks} onChange={e => setRacks(e.target.value)}/>
          </div>
          <div className="field">
            <label className="label">ความจุ/ช่อง</label>
            <input type="number" className="input tnum" min="1"
              value={capacity} onChange={e => setCapacity(e.target.value)}/>
          </div>
        </div>
        <div className="hint">
          ระบบจะสร้าง {Math.max(1, Math.min(20, Number(racks) || 1))} ช่อง:
          <span className="mono" style={{ color: "var(--fg)", marginLeft: 6 }}>
            {Array.from({ length: Math.min(8, Math.max(1, Number(racks) || 1)) }).map((_, i) =>
              `${warehouseId}-${zone || "?"}${i + 1}`).join(", ")}
            {Number(racks) > 8 ? "..." : ""}
          </span>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { ProductForm, WarehouseForm, LocationForm, ZoneForm });
