/* หน้าหลังบ้าน: จัดการนายหน้า (brokers) — ใช้เลือกในช่อง "ช่องทาง" ของทรัพย์ขายฝาก/จำนอง */
(function () {
  const { useState, useEffect } = React;

  const BROKER_TYPES = ['ติดทรัพย์', 'ประสานทรัพย์'];

  // จังหวัด → ภาค (จัดกลุ่มเดียวกับหน้าเว็บ) — โซน (ภาค) อ่านจากที่อยู่อัตโนมัติ ไม่ต้องเลือกเอง
  const REGION_PROVINCES = {
    'ภาคกลาง': ['กรุงเทพ','กำแพงเพชร','ชัยนาท','นครนายก','นครปฐม','นครสวรรค์','นนทบุรี','ปทุมธานี','พระนครศรีอยุธยา','อยุธยา','พิจิตร','พิษณุโลก','เพชรบูรณ์','ลพบุรี','สมุทรปราการ','สมุทรสงคราม','สมุทรสาคร','สิงห์บุรี','สุโขทัย','สุพรรณบุรี','สระบุรี','อ่างทอง','อุทัยธานี'],
    'ภาคเหนือ': ['เชียงใหม่','เชียงราย','ลำปาง','ลำพูน','แม่ฮ่องสอน','น่าน','พะเยา','แพร่','อุตรดิตถ์'],
    'ภาคตะวันออกเฉียงเหนือ': ['กาฬสินธุ์','ขอนแก่น','ชัยภูมิ','นครพนม','นครราชสีมา','โคราช','บึงกาฬ','บุรีรัมย์','มหาสารคาม','มุกดาหาร','ยโสธร','ร้อยเอ็ด','เลย','ศรีสะเกษ','สกลนคร','สุรินทร์','หนองคาย','หนองบัวลำภู','อุดรธานี','อุบลราชธานี','อำนาจเจริญ'],
    'ภาคตะวันออก': ['จันทบุรี','ฉะเชิงเทรา','ชลบุรี','ตราด','ปราจีนบุรี','ระยอง','สระแก้ว'],
    'ภาคตะวันตก': ['กาญจนบุรี','ตาก','ประจวบคีรีขันธ์','เพชรบุรี','ราชบุรี'],
    'ภาคใต้': ['กระบี่','ชุมพร','ตรัง','นครศรีธรรมราช','นราธิวาส','ปัตตานี','พังงา','พัทลุง','ภูเก็ต','ยะลา','ระนอง','สงขลา','สตูล','สุราษฎร์ธานี'],
  };
  // [จังหวัด, ภาค] เรียงชื่อยาวก่อน กันจังหวัดชื่อสั้นแมตช์ซ้อนในชื่อยาว
  const PROV_REGION = Object.entries(REGION_PROVINCES)
    .flatMap(([region, provs]) => provs.map(p => [p, region]))
    .sort((a, b) => b[0].length - a[0].length);
  function zoneFromAddress(addr) {
    if (!addr) return '';
    const s = String(addr);
    for (const [prov, region] of PROV_REGION) { if (s.includes(prov)) return region; }
    return '';
  }

  function BrokersPage() {
    const [rows, setRows] = useState([]);
    const [loading, setLoading] = useState(true);
    const [edit, setEdit] = useState(null); // broker ที่กำลังแก้ หรือ {} = เพิ่มใหม่

    function load() {
      setLoading(true);
      window.api.brokers().then(d => { setRows(d.brokers || []); setLoading(false); }).catch(() => setLoading(false));
    }
    useEffect(load, []);

    async function remove(b) {
      if (!window.confirm('ลบนายหน้า "' + b.name + '"? (ทรัพย์ที่อ้างถึงจะไม่มีนายหน้า)')) return;
      try { await window.api.deleteBroker(b.id); load(); } catch (e) { alert('ลบไม่สำเร็จ: ' + e.message); }
    }

    const cols = [
      { label: 'ชื่อ - นามสกุล', sortKey: 'name', render: r => <span className="text-bold">{r.name}</span> },
      { label: 'ประเภท', sortKey: 'broker_type', render: r => r.broker_type ? <span className="badge badge-blue">{r.broker_type}</span> : '-' },
      { label: 'โซน (ภาค)', sortKey: 'zone', render: r => (r.zone || zoneFromAddress(r.province || r.address)) || '-' },
      { label: 'เบอร์', sortKey: 'phone', render: r => r.phone || '-' },
      { label: 'LINE', sortKey: 'line_id', render: r => r.line_id || '-' },
      { label: 'สถานะ', sortKey: 'is_active', render: r => r.is_active ? <span className="badge badge-green">ใช้งาน</span> : <span className="badge badge-gray">ปิด</span> },
      { label: 'จัดการ', render: r => (
        <div className="row gap-8">
          <window.EditBtn onClick={() => setEdit(r)} />
          <window.DeleteBtn onClick={() => remove(r)} />
        </div>
      )},
    ];
    const ts = window.useTableSort(rows, 'name', 'asc');

    return (
      <div className="page">
        <div className="page-header">
          <h1><i className="ph ph-handshake" style={{marginRight:8,color:'#4A6079'}}></i>นายหน้า</h1>
          <button className="btn btn-primary" onClick={() => setEdit({})}>+ เพิ่มนายหน้า</button>
        </div>
        <p className="muted" style={{ marginTop: -8, marginBottom: 16 }}>เก็บรายชื่อนายหน้าไว้เลือกในช่อง “ช่องทาง” ของทรัพย์ขายฝาก/จำนอง</p>
        <div className="card">
          <Table columns={cols} data={ts.sorted} loading={loading} empty="ยังไม่มีนายหน้า" sort={ts.sort} onSort={ts.onSort} />
        </div>
        {edit && <BrokerModal broker={edit} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); load(); }} />}
      </div>
    );
  }

  function BrokerModal({ broker, onClose, onSaved }) {
    const isNew = !broker.id;
    const [f, setF] = useState({
      name: broker.name || '', phone: broker.phone || '', company: broker.company || '',
      line_id: broker.line_id || '', note: broker.note || '',
      broker_type: broker.broker_type || '',
      // ที่อยู่มีโครงสร้าง (autofill) — full_address = เลขที่/ถนน · แมปกับคอลัมน์ address
      full_address: broker.address || '', subdistrict: broker.subdistrict || '',
      district: broker.district || '', province: broker.province || '', zipcode: broker.zipcode || '',
      is_active: broker.is_active !== false,
    });
    const derivedZone = zoneFromAddress(f.province || f.full_address); // โซน (ภาค) อ่านจากจังหวัด — โชว์อย่างเดียว แก้ไม่ได้
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState('');
    const set = (k, v) => setF(s => ({ ...s, [k]: v }));

    async function save() {
      if (!f.name.trim()) { setErr('กรุณากรอกชื่อนายหน้า'); return; }
      setBusy(true); setErr('');
      // แมป full_address → คอลัมน์ address + เก็บโซนที่อ่านจากจังหวัด
      const { full_address, ...rest } = f;
      const payload = { ...rest, address: full_address, zone: zoneFromAddress(f.province || full_address) };
      try {
        if (isNew) await window.api.createBroker(payload);
        else await window.api.updateBroker(broker.id, payload);
        onSaved();
      } catch (e) { setErr('บันทึกไม่สำเร็จ: ' + e.message); setBusy(false); }
    }

    return (
      <Modal title={isNew ? 'เพิ่มนายหน้า' : 'แก้ไขนายหน้า'} onClose={onClose}>
        <div className="form-group"><label>ชื่อ - นามสกุล *</label><input className="input" value={f.name} onChange={e => set('name', e.target.value)} /></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div className="form-group"><label>เบอร์โทร</label><input className="input" value={f.phone} onChange={e => set('phone', e.target.value)} /></div>
          <div className="form-group"><label>LINE ID</label><input className="input" value={f.line_id} onChange={e => set('line_id', e.target.value)} /></div>
        </div>
        <div className="form-group"><label>ประเภทนายหน้า</label>
          <select className="input" value={f.broker_type} onChange={e => set('broker_type', e.target.value)}>
            <option value="">— เลือก —</option>
            {BROKER_TYPES.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>
        <window.ThaiAddressForm form={f} set={set} />
        <div className="form-group">
          <label>โซน (ภาค) <span style={{fontWeight:400,color:'var(--text-2)',fontSize:12}}>— ระบุอัตโนมัติจากจังหวัด</span></label>
          <div className="input" style={{ background:'#F1F5F9', display:'flex', alignItems:'center', cursor:'default', color: derivedZone ? '#0F172A' : '#94A3B8' }}>
            {derivedZone
              ? <span><i className="ph ph-map-pin" style={{marginRight:6,color:'#4A6079'}}></i>{derivedZone}</span>
              : 'กรอกที่อยู่ให้มีจังหวัด แล้วระบบจะระบุภาคให้อัตโนมัติ'}
          </div>
        </div>
        <div className="form-group"><label>บริษัท/สังกัด</label><input className="input" value={f.company} onChange={e => set('company', e.target.value)} /></div>
        <div className="form-group"><label>หมายเหตุ</label><textarea className="input" rows={2} value={f.note} onChange={e => set('note', e.target.value)} /></div>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', marginTop: 4 }}>
          <input type="checkbox" checked={f.is_active} onChange={e => set('is_active', e.target.checked)} style={{ width: 18, height: 18 }} />
          <span>ใช้งานอยู่ (โชว์ให้เลือก)</span>
        </label>
        {err && <div style={{ color: '#D8567A', marginTop: 10 }}>{err}</div>}
        <div className="row gap-10" style={{ marginTop: 18, justifyContent: 'flex-end' }}>
          <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
          <button className="btn btn-primary" onClick={save} disabled={busy}>{busy ? 'กำลังบันทึก...' : 'บันทึก'}</button>
        </div>
      </Modal>
    );
  }

  window.BrokersPage = BrokersPage;
})();
