// booking-modal.jsx — New Booking modal with 4 tabs

const PAY_METHODS = [
  { k: 'cash',     l: 'Tiền mặt',    ico: 'cash' },
  { k: 'card',     l: 'Thẻ',         ico: 'card' },
  { k: 'transfer', l: 'Chuyển khoản', ico: 'bank' },
  { k: 'qr',       l: 'QR',          ico: 'qr' },
  { k: 'pay_later', l: 'Trả sau',    ico: 'later' },
];

function NewBookingModal({ initialRoomId, initialDate, onClose, onSave }) {
  const data = window.HotelData;
  const [tab, setTab] = React.useState(0);
  const [completed, setCompleted] = React.useState(new Set());

  // Form state
  const [form, setForm] = React.useState(() => {
    const ci = initialDate ? new Date(initialDate) : new Date(data.today);
    const co = new Date(ci);
    co.setDate(co.getDate() + 1);
    return {
      roomId: initialRoomId || 'r101',
      checkIn: ci,
      checkInTime: '14:00',
      checkOut: co,
      checkOutTime: '12:00',
      guests_count: 2,
      source: 'website',
      note: '',
      guestName: '',
      guestPhone: '',
      guestEmail: '',
      guestId: '',
      nationality: 'Việt Nam',
      returning: false,
      services: {},  // {svId: qty}
      paymentMethod: 'card',
      deposit: 0,
      discount: 0,
    };
  });

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Derived
  const room = findRoom(data.rooms, form.roomId);
  const nights = Math.max(1, daysBetween(form.checkIn, form.checkOut));
  const roomTotal = room ? room.price * nights : 0;
  const servicesTotal = Object.entries(form.services).reduce((sum, [id, qty]) => {
    const sv = findService(data.serviceCatalog, id);
    return sum + (sv ? sv.price * qty : 0);
  }, 0);
  const subtotal = roomTotal + servicesTotal;
  const tax = Math.round(subtotal * 0.1);
  const discount = Number(form.discount) || 0;
  const total = Math.max(0, subtotal + tax - discount);

  // Tab nav
  const tabs = [
    { l: 'Thông tin phòng', ico: 'bed' },
    { l: 'Thông tin khách', ico: 'user' },
    { l: 'Dịch vụ',         ico: 'sparkle' },
    { l: 'Thanh toán',      ico: 'card' },
  ];
  const next = () => {
    const newCompleted = new Set(completed);
    newCompleted.add(tab);
    setCompleted(newCompleted);
    setTab(Math.min(3, tab + 1));
  };
  const prev = () => setTab(Math.max(0, tab - 1));

  const handleSave = () => {
    const services = Object.entries(form.services)
      .filter(([_, q]) => q > 0)
      .map(([id, qty]) => ({ id, qty }));
    onSave({
      id: 'BK-' + Math.floor(2500 + Math.random() * 99),
      code: 'SM' + Math.floor(2500 + Math.random() * 99),
      roomId: form.roomId,
      guestId: 'new-' + Date.now(),
      _newGuest: {
        name: form.guestName || 'Khách mới',
        phone: form.guestPhone,
        email: form.guestEmail,
        id_no: form.guestId,
        nationality: form.nationality,
        returning: false,
        stays: 1,
      },
      checkIn: form.checkIn,
      checkOut: form.checkOut,
      checkInTime: form.checkInTime,
      checkOutTime: form.checkOutTime,
      guests_count: form.guests_count,
      status: form.source,
      paymentStatus: form.deposit >= total ? 'paid' : form.deposit > 0 ? 'partial' : 'unpaid',
      paid: Number(form.deposit) || 0,
      paymentMethod: form.paymentMethod,
      source: form.source === 'website' ? 'Website' : form.source === 'walkin' ? 'Tại chỗ' : form.source === 'pending' ? 'Điện thoại' : 'OTA',
      services,
      note: form.note,
      createdBy: 'Lễ tân Hà',
      checkedIn: false,
    });
  };

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-hd">
          <div>
            <h2>Tạo đặt phòng mới</h2>
            <div className="sub">Hoàn tất 4 bước · Phòng {room?.number} · {nights} đêm</div>
          </div>
          <button className="modal-x" onClick={onClose} aria-label="Đóng">
            <Icon name="x" size={20} />
          </button>
        </div>

        <div className="modal-tabs">
          {tabs.map((t, i) => (
            <button
              key={i}
              className={`modal-tab ${tab === i ? 'active' : ''} ${completed.has(i) && tab !== i ? 'done' : ''}`}
              onClick={() => setTab(i)}
            >
              <span className="step">{completed.has(i) && tab !== i ? '✓' : i + 1}</span>
              <span>{t.l}</span>
            </button>
          ))}
        </div>

        <div className="modal-body">
          {tab === 0 && <RoomInfoTab form={form} set={set} rooms={data.rooms} nights={nights} />}
          {tab === 1 && <GuestInfoTab form={form} set={set} />}
          {tab === 2 && <ServicesTab form={form} set={set} catalog={data.serviceCatalog} />}
          {tab === 3 && (
            <PaymentTab
              form={form} set={set}
              room={room} nights={nights}
              roomTotal={roomTotal}
              servicesTotal={servicesTotal}
              tax={tax} subtotal={subtotal}
              discount={discount} total={total}
            />
          )}
        </div>

        <div className="modal-ft">
          <div className="ft-total">
            <div className="lbl">Tổng cộng (đã gồm thuế)</div>
            <div className="val">{VND(total)}</div>
          </div>
          <div className="sp" />
          <button className="btn-ghost" onClick={onClose}>Hủy</button>
          {tab > 0 && <button className="btn-outline" onClick={prev}>Quay lại</button>}
          {tab < 3 && <button className="btn-primary" onClick={next}>Tiếp tục</button>}
          {tab === 3 && <button className="btn-primary" onClick={handleSave}>Xác nhận & lưu</button>}
        </div>
      </div>
    </div>
  );
}

// ─── Tab 1: Room Info ──────────────────────────────────────
function RoomInfoTab({ form, set, rooms, nights }) {
  const dateInputISO = (d) => {
    const y = d.getFullYear(), m = String(d.getMonth() + 1).padStart(2, '0'), dd = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${dd}`;
  };
  const room = findRoom(rooms, form.roomId);
  return (
    <div>
      <div className="field">
        <label>Phòng <span className="req">*</span></label>
        <select value={form.roomId} onChange={(e) => set('roomId', e.target.value)}>
          {rooms.map(r => (
            <option key={r.id} value={r.id}>
              Phòng {r.number} · {r.type} · {VND(r.price)}/đêm · {r.bed}
            </option>
          ))}
        </select>
      </div>

      <div className="field-row">
        <div className="field">
          <label>Ngày nhận phòng <span className="req">*</span></label>
          <input
            type="date"
            value={dateInputISO(form.checkIn)}
            onChange={(e) => {
              const [y, m, d] = e.target.value.split('-').map(Number);
              set('checkIn', new Date(y, m - 1, d));
            }}
          />
        </div>
        <div className="field">
          <label>Giờ nhận</label>
          <input type="time" value={form.checkInTime} onChange={(e) => set('checkInTime', e.target.value)} />
        </div>
      </div>

      <div className="field-row">
        <div className="field">
          <label>Ngày trả phòng <span className="req">*</span></label>
          <input
            type="date"
            value={dateInputISO(form.checkOut)}
            onChange={(e) => {
              const [y, m, d] = e.target.value.split('-').map(Number);
              set('checkOut', new Date(y, m - 1, d));
            }}
          />
        </div>
        <div className="field">
          <label>Giờ trả</label>
          <input type="time" value={form.checkOutTime} onChange={(e) => set('checkOutTime', e.target.value)} />
        </div>
      </div>

      <div className="field-row-3">
        <div className="field">
          <label>Số đêm</label>
          <input type="text" value={`${nights} đêm`} readOnly style={{ background: 'var(--bg-soft)' }} />
        </div>
        <div className="field">
          <label>Số khách</label>
          <input type="number" min="1" max={room?.cap || 4} value={form.guests_count} onChange={(e) => set('guests_count', +e.target.value)} />
          <div className="hint">Tối đa {room?.cap || 4} khách</div>
        </div>
        <div className="field">
          <label>Nguồn đặt phòng</label>
          <select value={form.source} onChange={(e) => set('source', e.target.value)}>
            <option value="website">Website</option>
            <option value="walkin">Tại chỗ (Walk-in)</option>
            <option value="pending">Điện thoại</option>
            <option value="website">OTA (Booking.com / Agoda)</option>
          </select>
        </div>
      </div>

      <div className="field">
        <label>Yêu cầu đặc biệt</label>
        <textarea
          placeholder="VD: phòng tầng cao, giường king, đón sân bay…"
          value={form.note}
          onChange={(e) => set('note', e.target.value)}
        />
      </div>
    </div>
  );
}

// ─── Tab 2: Guest Info ─────────────────────────────────────
function GuestInfoTab({ form, set }) {
  return (
    <div>
      <div className="field-row" style={{ marginBottom: 4 }}>
        <label className="sb-chk" style={{ padding: 0, '--swatch-c': 'var(--primary)' }}>
          <input
            type="checkbox"
            checked={form.returning}
            onChange={(e) => set('returning', e.target.checked)}
          />
          <span className="swatch" />
          <span style={{ fontSize: 13 }}>Khách quen — tìm & tự điền</span>
        </label>
        <div />
      </div>

      {form.returning && (
        <div className="field">
          <label>Tìm khách</label>
          <div className="tb-search" style={{ width: '100%', margin: '4px 0 8px' }}>
            <Icon name="search" size={16} className="ico" />
            <input type="text" placeholder="Tên, SĐT, số CCCD…" />
          </div>
        </div>
      )}

      <div className="field-row">
        <div className="field">
          <label>Họ và tên <span className="req">*</span></label>
          <input
            type="text"
            placeholder="VD: Nguyễn Thị Minh Anh"
            value={form.guestName}
            onChange={(e) => set('guestName', e.target.value)}
          />
        </div>
        <div className="field">
          <label>Số điện thoại <span className="req">*</span></label>
          <input
            type="tel"
            placeholder="VD: 0912 345 678"
            value={form.guestPhone}
            onChange={(e) => set('guestPhone', e.target.value)}
          />
        </div>
      </div>

      <div className="field-row">
        <div className="field">
          <label>Email</label>
          <input
            type="email"
            placeholder="email@example.com"
            value={form.guestEmail}
            onChange={(e) => set('guestEmail', e.target.value)}
          />
        </div>
        <div className="field">
          <label>CCCD / Passport</label>
          <input
            type="text"
            placeholder="Mã số căn cước hoặc hộ chiếu"
            value={form.guestId}
            onChange={(e) => set('guestId', e.target.value)}
          />
        </div>
      </div>

      <div className="field">
        <label>Quốc tịch</label>
        <select value={form.nationality} onChange={(e) => set('nationality', e.target.value)}>
          <option>Việt Nam</option>
          <option>Hoa Kỳ</option>
          <option>Anh Quốc</option>
          <option>Pháp</option>
          <option>Nhật Bản</option>
          <option>Hàn Quốc</option>
          <option>Khác</option>
        </select>
      </div>
    </div>
  );
}

// ─── Tab 3: Services ───────────────────────────────────────
function ServicesTab({ form, set, catalog }) {
  const setQty = (id, qty) => {
    const next = { ...form.services };
    if (qty <= 0) delete next[id];
    else next[id] = qty;
    set('services', next);
  };
  return (
    <div>
      <div className="lbl-strong" style={{ marginBottom: 10, color: 'var(--ink-3)' }}>
        Chọn dịch vụ bổ sung
      </div>
      <div className="svc-grid">
        {catalog.map(s => {
          const qty = form.services[s.id] || 0;
          const sel = qty > 0;
          return (
            <div key={s.id} className={`svc ${sel ? 'selected' : ''}`}>
              <div className="svc-ico">{s.icon}</div>
              <div className="svc-meta">
                <div className="svc-name">{s.name}</div>
                <div className="svc-price">{VND(s.price)} {s.unit}</div>
              </div>
              <div className="stepper">
                <button onClick={() => setQty(s.id, Math.max(0, qty - 1))} disabled={qty === 0}><Icon name="minus" size={14} /></button>
                <span className="qty">{qty}</span>
                <button onClick={() => setQty(s.id, qty + 1)}><Icon name="plus" size={14} /></button>
              </div>
            </div>
          );
        })}
      </div>
      <button className="btn-outline" style={{ marginTop: 14, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
        <Icon name="plus" size={14} stroke={2.5} /> Thêm dịch vụ tùy chỉnh
      </button>
    </div>
  );
}

// ─── Tab 4: Payment ────────────────────────────────────────
function PaymentTab({ form, set, room, nights, roomTotal, servicesTotal, tax, subtotal, discount, total }) {
  const paidStatus = form.deposit >= total ? 'paid' : form.deposit > 0 ? 'partial' : 'unpaid';
  return (
    <div>
      <div className="pay-summary" style={{ marginBottom: 18 }}>
        <div className="pay-row">
          <span className="lbl">Phòng {room?.number} · {nights} đêm × {VND(room?.price)}</span>
          <span className="val">{VND(roomTotal)}</span>
        </div>
        <div className="pay-row">
          <span className="lbl">Dịch vụ</span>
          <span className="val">{VND(servicesTotal)}</span>
        </div>
        <div className="pay-row">
          <span className="lbl">Tạm tính</span>
          <span className="val">{VND(subtotal)}</span>
        </div>
        <div className="pay-row">
          <span className="lbl">Thuế VAT (10%)</span>
          <span className="val">{VND(tax)}</span>
        </div>
        <div className="pay-row">
          <span className="lbl">Giảm giá</span>
          <span className="val" style={{ color: discount > 0 ? 'var(--status-walkin)' : undefined }}>
            {discount > 0 ? '−' + VND(discount) : VND(0)}
          </span>
        </div>
        <div className="pay-row total">
          <span className="lbl">Tổng cộng</span>
          <span className="val">{VND(total)}</span>
        </div>
      </div>

      <div className="field">
        <label>Mã giảm giá</label>
        <div style={{ display: 'flex', gap: 8 }}>
          <input
            type="text"
            placeholder="VD: SUMMER25"
            style={{ flex: 1 }}
            onChange={(e) => {
              if (e.target.value.toUpperCase() === 'SUMMER25') set('discount', Math.round(subtotal * 0.1));
              else set('discount', 0);
            }}
          />
          <button className="btn-outline">Áp dụng</button>
        </div>
        <div className="hint">Thử: SUMMER25 để giảm 10%</div>
      </div>

      <div className="field">
        <label>Phương thức thanh toán</label>
        <div className="pay-methods">
          {PAY_METHODS.map(m => (
            <button
              key={m.k}
              className={`pay-method ${form.paymentMethod === m.k ? 'active' : ''}`}
              onClick={() => set('paymentMethod', m.k)}
            >
              <span className="ico"><Icon name={m.ico} size={18} /></span>
              <span>{m.l}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="field-row">
        <div className="field">
          <label>Số tiền đặt cọc / thanh toán</label>
          <input
            type="number"
            min="0"
            placeholder="0"
            value={form.deposit || ''}
            onChange={(e) => set('deposit', +e.target.value || 0)}
          />
          <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
            <button className="btn-outline" style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => set('deposit', Math.round(total * 0.3))}>30%</button>
            <button className="btn-outline" style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => set('deposit', Math.round(total * 0.5))}>50%</button>
            <button className="btn-outline" style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => set('deposit', total)}>100%</button>
          </div>
        </div>
        <div className="field">
          <label>Trạng thái thanh toán</label>
          <div style={{ paddingTop: 8 }}>
            <span className={`pill s-${paidStatus}`}>
              <span className="pill-dot" />
              {paidStatus === 'paid' ? 'Đã thanh toán' : paidStatus === 'partial' ? 'Đặt cọc một phần' : 'Chưa thanh toán'}
            </span>
          </div>
          <div className="hint" style={{ marginTop: 6 }}>
            Còn lại: <b>{VND(Math.max(0, total - (form.deposit || 0)))}</b>
          </div>
        </div>
      </div>
    </div>
  );
}

window.NewBookingModal = NewBookingModal;
