/* global React, Icon, Modal, Pill, Field, formatBaht, formatDateTH, downloadCSV, DATA */
const { useState: useStateC, useMemo: useMemoC } = React;

function Customers({ rooms }) {
  const [type, setType] = useStateC("room");
  const [query, setQuery] = useStateC("");
  const [adding, setAdding] = useStateC(false);
  const [editing, setEditing] = useStateC(null);

  const roomCustomers = useMemoC(() => {
    const seen = new Set();
    return rooms
      .filter(r => r.customer)
      .map(r => ({ ...r.customer, room: r.no, rent: r.rent, type: r.type, status: r.status, floor: r.floor }))
      .filter(c => { if (seen.has(c.id)) return false; seen.add(c.id); return true; });
  }, [rooms]);

  const parkCustomers = useMemoC(() => {
    const seen = new Set();
    return DATA.parking
      .filter(p => p.customer)
      .map(p => ({ ...p.customer, spot: p.no, zone: p.zone, monthly: p.monthly, status: p.status, type: p.type }))
      .filter(c => { if (seen.has(c.id)) return false; seen.add(c.id); return true; });
  }, []);

  const filtered = (type === "room" ? roomCustomers : parkCustomers).filter(c =>
    !query || c.name.includes(query) || (c.phone||"").includes(query) || (c.plate||"").includes(query) || (c.room||"").includes(query) || (c.spot||"").includes(query)
  );

  const exportList = () => {
    const rows = filtered.map(c => type === "room"
      ? { รหัส: c.id, ชื่อ: c.name, โทรศัพท์: c.phone, ห้อง: c.room, ประเภท: c.type === "monthly" ? "รายเดือน" : "รายวัน", ค่าเช่า: c.rent, เข้าพัก: c.since, สถานะ: c.status }
      : { รหัส: c.id, ชื่อ: c.name, โทรศัพท์: c.phone, ทะเบียน: c.plate, ช่อง: c.spot, โซน: c.zone, ค่าเช่า: c.monthly, สถานะ: c.status }
    );
    downloadCSV(`customers-${type}.csv`, rows);
  };

  return (
    <div className="grid" style={{ gap: 18 }}>
      <div className="row" style={{ flexWrap: "wrap", gap: 12 }}>
        <div className="tabs">
          <button className={"tab " + (type === "room" ? "active" : "")} onClick={() => setType("room")}>ลูกค้าห้องพัก <span style={{opacity:0.6, marginLeft:4}}>{roomCustomers.length}</span></button>
          <button className={"tab " + (type === "park" ? "active" : "")} onClick={() => setType("park")}>ลูกค้าที่จอดรถ <span style={{opacity:0.6, marginLeft:4}}>{parkCustomers.length}</span></button>
        </div>
        <div style={{ position: "relative" }}>
          <input className="input" style={{ width: 280, paddingLeft: 36 }} placeholder="ค้นหาชื่อ / เบอร์ / ทะเบียน / ห้อง" value={query} onChange={e=>setQuery(e.target.value)}/>
          <Icon name="search" style={{ position: "absolute", left: 10, top: 10, color: "var(--ink-3)" }} />
        </div>
        <div className="spacer" style={{ flex: 1 }} />
        <button className="btn" onClick={exportList}><Icon name="download" size={16}/> Export CSV</button>
        <button className="btn primary" onClick={() => setAdding(true)}><Icon name="plus" size={16}/> เพิ่มลูกค้า</button>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div className="table-wrap" style={{ border: "none" }}>
          <table className="table">
            {type === "room" ? (
              <>
                <thead><tr>
                  <th>รหัส</th><th>ชื่อ</th><th>โทรศัพท์</th><th>ห้อง</th><th>ประเภท</th>
                  <th className="num">ค่าเช่า</th><th>เข้าพักตั้งแต่</th><th></th>
                </tr></thead>
                <tbody>
                  {filtered.map(c => (
                    <tr key={c.id}>
                      <td className="num" style={{ color: "var(--ink-3)" }}>{c.id}</td>
                      <td style={{ fontWeight: 600 }}>{c.name}</td>
                      <td className="num">{c.phone}</td>
                      <td>{c.room} <span style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>ชั้น {c.floor}</span></td>
                      <td>{c.type === "monthly" ? "รายเดือน" : "รายวัน"}</td>
                      <td className="num">{formatBaht(c.rent)}</td>
                      <td>{formatDateTH(c.since)}</td>
                      <td>
                        <div className="row" style={{ gap: 4 }}>
                          <button className="btn sm ghost" onClick={() => setEditing(c)}><Icon name="edit" size={14}/></button>
                          <button className="btn sm ghost"><Icon name="phone" size={14}/></button>
                          <button className="btn sm ghost"><Icon name="trash" size={14}/></button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </>
            ) : (
              <>
                <thead><tr>
                  <th>รหัส</th><th>ชื่อ</th><th>โทรศัพท์</th><th>ทะเบียนรถ</th><th>ช่อง</th>
                  <th>ประเภท</th><th className="num">ค่าเช่า</th><th></th>
                </tr></thead>
                <tbody>
                  {filtered.map(c => (
                    <tr key={c.id}>
                      <td className="num" style={{ color: "var(--ink-3)" }}>{c.id}</td>
                      <td style={{ fontWeight: 600 }}>{c.name}</td>
                      <td className="num">{c.phone}</td>
                      <td className="mono" style={{ fontWeight: 600 }}>{c.plate}</td>
                      <td>{c.spot} <span style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>โซน {c.zone}</span></td>
                      <td>{c.type === "monthly" ? "รายเดือน" : "รายวัน"}</td>
                      <td className="num">{formatBaht(c.monthly)}</td>
                      <td>
                        <div className="row" style={{ gap: 4 }}>
                          <button className="btn sm ghost" onClick={() => setEditing(c)}><Icon name="edit" size={14}/></button>
                          <button className="btn sm ghost"><Icon name="phone" size={14}/></button>
                          <button className="btn sm ghost"><Icon name="trash" size={14}/></button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </>
            )}
          </table>
        </div>
      </div>

      <Modal open={adding} onClose={() => setAdding(false)} size="lg" title={"เพิ่มลูกค้า" + (type === "room" ? "ห้องพัก" : "ที่จอดรถ")}
        footer={<><button className="btn" onClick={() => setAdding(false)}>ยกเลิก</button><button className="btn primary" onClick={() => setAdding(false)}><Icon name="check" size={16}/> บันทึก</button></>}>
        <div className="grid cols-2" style={{ gap: 14 }}>
          <Field label="ชื่อ-นามสกุล"><input className="input" placeholder="สมชาย ใจดี"/></Field>
          <Field label="โทรศัพท์"><input className="input" placeholder="08X-XXX-XXXX"/></Field>
          <Field label="เลขบัตรประชาชน"><input className="input"/></Field>
          <Field label="อีเมล"><input className="input"/></Field>
          {type === "room" ? (
            <>
              <Field label="ห้องพัก"><select className="select">{rooms.filter(r => !r.customer).slice(0,30).map(r => <option key={r.no}>{r.no} (ชั้น {r.floor})</option>)}</select></Field>
              <Field label="ประเภท"><select className="select"><option>รายเดือน</option><option>รายวัน</option></select></Field>
              <Field label="เข้าพักวันที่"><input className="input" type="date" defaultValue="2026-05-11"/></Field>
              <Field label="เงินมัดจำ"><input className="input num" defaultValue="9000"/></Field>
            </>
          ) : (
            <>
              <Field label="ช่องจอด"><select className="select">{DATA.parking.filter(p => !p.customer).slice(0,30).map(p => <option key={p.no}>{p.no} (โซน {p.zone})</option>)}</select></Field>
              <Field label="ทะเบียนรถ"><input className="input mono" placeholder="1กข 1234"/></Field>
              <Field label="ยี่ห้อ-รุ่น"><input className="input" placeholder="Toyota Yaris"/></Field>
              <Field label="ส่วนลดเหมาจ่าย"><select className="select"><option>ไม่มี</option><option>3 เดือน ลด 10%</option><option>6 เดือน ลด 18%</option></select></Field>
            </>
          )}
          <div style={{ gridColumn: "1 / -1" }}>
            <Field label="หมายเหตุ"><textarea className="textarea"/></Field>
          </div>
        </div>
      </Modal>

      <Modal open={!!editing} onClose={() => setEditing(null)} title="แก้ไขข้อมูลลูกค้า"
        footer={<><button className="btn" onClick={() => setEditing(null)}>ยกเลิก</button><button className="btn primary" onClick={() => setEditing(null)}>บันทึก</button></>}>
        {editing && (
          <div className="grid cols-2" style={{ gap: 14 }}>
            <Field label="ชื่อ"><input className="input" defaultValue={editing.name}/></Field>
            <Field label="โทรศัพท์"><input className="input" defaultValue={editing.phone}/></Field>
            {editing.plate && <Field label="ทะเบียนรถ"><input className="input mono" defaultValue={editing.plate}/></Field>}
          </div>
        )}
      </Modal>
    </div>
  );
}

window.Customers = Customers;
