/* global React, Icon, Modal, Pill, StatusPill, Field, formatBaht, formatDateTH, DATA, DB */
const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP } = React;

function Parking({ onOpenReceipt }) {
  const [tab, setTab] = useStateP("all");
  const [spots, setSpots] = useStateP([]);
  const [loading, setLoading] = useStateP(true);
  const [active, setActive] = useStateP(null);
  const [adding, setAdding] = useStateP(false);
  const [newSpot, setNewSpot] = useStateP({ zone: "A", no: "", size: "มาตรฐาน", monthly: "1500" });
  const [daily, setDaily] = useStateP(false);
  const [editPriceFor, setEditPriceFor] = useStateP(null);

  useEffectP(() => {
    DB.loadParking().then(data => { setSpots(data); setLoading(false); }).catch(() => setLoading(false));
  }, []);

  const filtered = useMemoP(() => spots.filter(s => {
    if (tab === "vacant" && s.status !== "vacant") return false;
    if (tab === "occupied" && !(s.status === "occupied" || s.status === "overdue")) return false;
    if (tab === "daily" && s.status !== "daily") return false;
    if (tab === "overdue" && s.status !== "overdue") return false;
    return true;
  }), [spots, tab]);

  const byZone = useMemoP(() => {
    const out = { A: [], B: [], C: [], D: [] };
    filtered.forEach(s => { out[s.zone].push(s); });
    return out;
  }, [filtered]);

  const counts = useMemoP(() => ({
    all: spots.length,
    vacant: spots.filter(s => s.status === "vacant").length,
    occupied: spots.filter(s => s.status === "occupied" || s.status === "overdue").length,
    daily: spots.filter(s => s.status === "daily").length,
    overdue: spots.filter(s => s.status === "overdue").length,
  }), [spots]);

  const updateSpot = (no, patch) => {
    setSpots(ss => ss.map(s => s.no === no ? { ...s, ...patch } : s));
    if (active && active.no === no) setActive(a => ({ ...a, ...patch }));
    DB.updateSpot(no, patch).catch(console.error);
  };
  const deleteSpot = (no) => {
    if (!confirm(`ลบช่องจอด ${no}?`)) return;
    setSpots(ss => ss.filter(s => s.no !== no)); setActive(null);
    DB.deleteSpot(no).catch(console.error);
  };

  const saveNewSpot = () => {
    const { zone, no, size, monthly } = newSpot;
    const spotNo = no.trim() || `${zone}${String(spots.filter(s => s.zone === zone).length + 1).padStart(2,"0")}`;
    if (spots.some(s => s.no === spotNo)) { alert(`ช่องจอด ${spotNo} มีอยู่แล้ว`); return; }
    const spot = {
      no: spotNo, zone, status: "vacant", type: "monthly",
      customer: null, plate: null,
      monthly: parseFloat(monthly) || 1500,
      endDate: null, size: size || "มาตรฐาน",
    };
    setSpots(ss => [...ss, spot].sort((a, b) => a.no.localeCompare(b.no)));
    setNewSpot({ zone: "A", no: "", size: "มาตรฐาน", monthly: "1500" });
    setAdding(false);
    DB.addSpot(spot).catch(console.error);
  };

  if (loading) return <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>กำลังโหลดข้อมูลที่จอดรถ...</div>;

  return (
    <div className="grid" style={{ gap: 18 }}>
      <div className="row" style={{ flexWrap: "wrap", gap: 12 }}>
        <div className="tabs">
          <button className={"tab " + (tab === "all" ? "active" : "")} onClick={() => setTab("all")}>ทั้งหมด <span style={{opacity:0.6, marginLeft:4}}>{counts.all}</span></button>
          <button className={"tab " + (tab === "occupied" ? "active" : "")} onClick={() => setTab("occupied")}>รายเดือน <span style={{opacity:0.6, marginLeft:4}}>{counts.occupied}</span></button>
          <button className={"tab " + (tab === "daily" ? "active" : "")} onClick={() => setTab("daily")}>รายวัน <span style={{opacity:0.6, marginLeft:4}}>{counts.daily}</span></button>
          <button className={"tab " + (tab === "vacant" ? "active" : "")} onClick={() => setTab("vacant")}>ว่าง <span style={{opacity:0.6, marginLeft:4}}>{counts.vacant}</span></button>
          <button className={"tab " + (tab === "overdue" ? "active" : "")} onClick={() => setTab("overdue")}>ค้างชำระ <span style={{opacity:0.6, marginLeft:4}}>{counts.overdue}</span></button>
        </div>
        <div className="spacer" style={{ flex: 1 }} />
        <button className="btn" onClick={() => setDaily(true)}><Icon name="car" size={16}/> รถจอดรายวัน</button>
        <button className="btn primary" onClick={() => setAdding(true)}><Icon name="plus" size={16}/> เพิ่มช่องจอด</button>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>แผนผังลานจอดรถ</h3>
          <div className="spacer" />
          <div className="legend">
            <span className="item"><span className="swatch" style={{ background: "var(--ok-soft)", borderColor: "var(--ok)" }}/> มีผู้เช่ารายเดือน</span>
            <span className="item"><span className="swatch" style={{ background: "var(--info-soft)", borderColor: "var(--accent)" }}/> รายวัน</span>
            <span className="item"><span className="swatch" style={{ background: "var(--warn-soft)", borderColor: "var(--warn)" }}/> จอง</span>
            <span className="item"><span className="swatch" style={{ background: "var(--danger-soft)", borderColor: "var(--danger)" }}/> ค้างชำระ</span>
            <span className="item"><span className="swatch" style={{ background: "var(--surface)" }}/> ว่าง</span>
          </div>
        </div>

        <div className="lot">
          {Object.keys(byZone).map(z => (
            byZone[z].length > 0 && (
              <div className="lot-row" key={z}>
                <div className="lot-label">โซน {z}</div>
                <div className="spots">
                  {byZone[z].map(s => (
                    <button className="spot" data-status={s.status} key={s.no} onClick={() => setActive(s)}>
                      <span className="no">{s.no}</span>
                      <span className="plate">{s.plate || "ว่าง"}</span>
                    </button>
                  ))}
                </div>
              </div>
            )
          ))}
        </div>
      </div>

      {/* Spot detail */}
      <Modal open={!!active} onClose={() => setActive(null)} size="lg"
             title={active ? `ช่องจอด ${active.no} · โซน ${active.zone} · ขนาด${active.size}` : ""}>
        {active && (
          <div className="grid" style={{ gap: 16 }}>
            <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
              <StatusPill status={active.status}/>
              {active.type === "monthly" ? <Pill>รายเดือน · {formatBaht(active.monthly)}</Pill> : <Pill tone="info">รายวัน</Pill>}
            </div>
            {active.customer ? (
              <div className="card" style={{ background: "var(--surface-2)" }}>
                <div className="card-head"><h3>ผู้เช่า</h3><div className="spacer"/><button className="btn sm"><Icon name="edit" size={14}/> แก้ไข</button></div>
                <div className="grid cols-2" style={{ gap: 10 }}>
                  <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>ชื่อ</div><div style={{ fontWeight: 600 }}>{active.customer.name}</div></div>
                  <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>โทรศัพท์</div><div className="num">{active.customer.phone}</div></div>
                  <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>ทะเบียนรถ</div><div className="mono" style={{ fontSize: "1.1rem", fontWeight: 600 }}>{active.plate}</div></div>
                  <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>หมดอายุ</div><div>{formatDateTH(active.endDate)}</div></div>
                </div>
              </div>
            ) : (
              <div className="card" style={{ borderStyle: "dashed", textAlign: "center", padding: 24 }}>
                <div style={{ color: "var(--ink-3)" }}>ช่องนี้ว่าง</div>
                <div className="row" style={{ justifyContent: "center", marginTop: 12 }}>
                  <button className="btn primary"><Icon name="plus" size={16}/> เช็คอินรายเดือน</button>
                  <button className="btn" onClick={() => { setDaily(true); setActive(null); }}><Icon name="car" size={16}/> รถรายวัน</button>
                </div>
              </div>
            )}

            <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
              <button className="btn primary" onClick={() => onOpenReceipt(active)}><Icon name="printer" size={16}/> พิมพ์ใบเสร็จ</button>
              <button className="btn" onClick={() => setEditPriceFor(active)}><Icon name="money" size={16}/> ตั้งราคา/ส่วนลด</button>
              <button className="btn"><Icon name="qr" size={16}/> สร้าง QR ชำระ</button>
              <div className="spacer"/>
              <button className="btn danger" onClick={() => deleteSpot(active.no)}><Icon name="trash" size={16}/> ลบช่องจอด</button>
            </div>
          </div>
        )}
      </Modal>

      {/* Add */}
      <Modal open={adding} onClose={() => setAdding(false)} title="เพิ่มช่องจอดใหม่"
             footer={<>
               <button className="btn" onClick={() => setAdding(false)}>ยกเลิก</button>
               <button className="btn primary" onClick={saveNewSpot}><Icon name="check" size={16}/> บันทึก</button>
             </>}>
        <div className="grid cols-2" style={{ gap: 14 }}>
          <Field label="โซน">
            <select className="select" value={newSpot.zone} onChange={e => setNewSpot(s => ({ ...s, zone: e.target.value }))}>
              <option>A</option><option>B</option><option>C</option><option>D</option>
            </select>
          </Field>
          <Field label="หมายเลขช่อง (เว้นว่าง = auto)">
            <input className="input" placeholder={`${newSpot.zone}${String(spots.filter(s => s.zone === newSpot.zone).length + 1).padStart(2,"0")}`}
              value={newSpot.no} onChange={e => setNewSpot(s => ({ ...s, no: e.target.value }))}/>
          </Field>
          <Field label="ขนาด">
            <select className="select" value={newSpot.size} onChange={e => setNewSpot(s => ({ ...s, size: e.target.value }))}>
              <option>มาตรฐาน</option><option>ใหญ่</option>
            </select>
          </Field>
          <Field label="ค่าเช่ารายเดือน (บาท)">
            <input className="input num" value={newSpot.monthly} onChange={e => setNewSpot(s => ({ ...s, monthly: e.target.value }))}/>
          </Field>
        </div>
      </Modal>

      {/* Daily parking log */}
      <Modal open={daily} onClose={() => setDaily(false)} size="xl"
             title="บันทึกค่าจอดรถรายวัน"
             footer={<button className="btn primary" onClick={() => setDaily(false)}>เสร็จสิ้น</button>}>
        <DailyParkingPanel onReceipt={(rec) => { onOpenReceipt({ ...rec, _isDailyPark: true }); setDaily(false); }}/>
      </Modal>

      {/* Edit price */}
      <Modal open={!!editPriceFor} onClose={() => setEditPriceFor(null)}
             title={editPriceFor ? `ตั้งราคา ช่อง ${editPriceFor.no}` : ""}
             footer={<>
               <button className="btn" onClick={() => setEditPriceFor(null)}>ยกเลิก</button>
               <button className="btn primary" onClick={() => setEditPriceFor(null)}>บันทึก</button>
             </>}>
        {editPriceFor && (
          <div className="grid" style={{ gap: 14 }}>
            <div className="grid cols-2" style={{ gap: 14 }}>
              <Field label="ค่าเช่า/เดือน"><input className="input num" defaultValue={editPriceFor.monthly}/></Field>
              <Field label="ส่วนลดเหมาจ่าย">
                <select className="select">
                  <option>ไม่มี</option>
                  <option>3 เดือน ลด 10%</option>
                  <option>6 เดือน ลด 18%</option>
                  <option>12 เดือน ลด 25%</option>
                  <option>กำหนดเอง</option>
                </select>
              </Field>
              <Field label="ส่วนลดรายบุคคล (%)"><input className="input num" defaultValue="0"/></Field>
              <Field label="หมายเหตุ"><input className="input" placeholder="เช่น พนักงานประจำ"/></Field>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

function DailyParkingPanel({ onReceipt }) {
  const [log, setLog] = useStateP(DATA.parkDaily);
  const [plate, setPlate] = useStateP("");
  const [spot, setSpot] = useStateP("");
  const [hours, setHours] = useStateP(8);

  const rate = (h) => h <= 4 ? 60 : h <= 8 ? 80 : h <= 12 ? 100 : 120;
  const amount = rate(hours);

  const todayTotal = log.filter(l => l.date === "2026-05-11").reduce((s,x) => s + x.amount, 0);

  const submit = () => {
    if (!plate || !spot) return;
    const rec = { id: "PD" + (log.length + 1), date: "2026-05-11", plate, spot, hours, amount, method: "เงินสด" };
    setLog([rec, ...log]);
    setPlate(""); setSpot(""); setHours(8);
    onReceipt(rec);
  };

  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="card" style={{ background: "var(--surface-2)" }}>
        <div className="card-head"><h3>บันทึกใหม่</h3><div className="spacer"/><Pill tone="info">วันนี้: {formatBaht(todayTotal)}</Pill></div>
        <div className="grid cols-4" style={{ gap: 12 }}>
          <Field label="ทะเบียนรถ"><input className="input mono" placeholder="1กข 1234" value={plate} onChange={e=>setPlate(e.target.value)}/></Field>
          <Field label="ช่องจอด"><input className="input" placeholder="A05" value={spot} onChange={e=>setSpot(e.target.value)}/></Field>
          <Field label="ระยะเวลา (ชม.)">
            <select className="select" value={hours} onChange={e => setHours(+e.target.value)}>
              <option value="4">≤ 4 ชม. (60฿)</option>
              <option value="8">≤ 8 ชม. (80฿)</option>
              <option value="12">≤ 12 ชม. (100฿)</option>
              <option value="24">24 ชม. (120฿)</option>
            </select>
          </Field>
          <Field label="ยอดชำระ">
            <div className="row">
              <input className="input num" value={amount} readOnly style={{ fontWeight: 600 }}/>
              <button className="btn primary" onClick={submit}><Icon name="check" size={16}/></button>
            </div>
          </Field>
        </div>
      </div>

      <div>
        <div style={{ fontWeight: 600, marginBottom: 8 }}>ประวัติรายวัน</div>
        <div className="table-wrap">
          <table className="table">
            <thead><tr><th>วันที่</th><th>ทะเบียน</th><th>ช่อง</th><th>ระยะเวลา</th><th>ช่องทาง</th><th className="num">จำนวน</th><th></th></tr></thead>
            <tbody>
              {log.map(l => (
                <tr key={l.id}>
                  <td className="num">{l.date}</td>
                  <td className="mono">{l.plate}</td>
                  <td>{l.spot}</td>
                  <td>{l.hours} ชม.</td>
                  <td style={{ color: "var(--ink-3)" }}>{l.method}</td>
                  <td className="num" style={{ fontWeight: 600 }}>{formatBaht(l.amount)}</td>
                  <td><button className="btn sm ghost" onClick={() => onReceipt(l)}><Icon name="printer" size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

window.Parking = Parking;
