// Thaipat Quotation — Form, items table, totals, notes

const { useState, useEffect, useRef } = React;

// ---------- NUMBER UTILS --------------------------------------------------
function fmtNum(n) {
  return n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function parseNum(str) {
  return parseFloat(String(str).replace(/,/g, "")) || 0;
}

// ---------- THAI BAHT -----------------------------------------------------
function numToThaiBaht(numStr) {
  const digits = ["", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า"];
  const places = ["", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน", "ล้าน"];
  const raw = String(numStr).replace(/,/g, "");
  if (raw === "0" || raw === "0.00" || raw === "") return "ศูนย์บาทถ้วน";
  const [intPart, decPart] = raw.split(".");
  const satang = decPart ? parseInt(decPart.padEnd(2, "0").slice(0, 2), 10) : 0;
  function groupToThai(n) {
    let s = "";
    const d = String(n).padStart(6, "0");
    for (let i = 0; i < 6; i++) {
      const v = parseInt(d[i], 10);
      if (v === 0) continue;
      const place = 5 - i;
      if (place === 0) { s += digits[v]; }
      else if (place === 1) { s += (v === 2 ? "ยี่" : v === 1 ? "" : digits[v]) + "สิบ"; }
      else { s += digits[v] + places[place]; }
      if (i === 0 && v === 1 && place === 5) s = s.replace("หนึ่งแสน", "แสน");
      if (i === 1 && v === 1 && place === 4) s = s.replace("หนึ่งหมื่น", "หมื่น");
    }
    if (d === "000001") s = "หนึ่ง";
    s = s.replace("หนึ่งสิบ", "สิบ");
    return s;
  }
  const i = parseInt(intPart, 10);
  let baht = "";
  if (i >= 1000000) {
    const mil = Math.floor(i / 1000000);
    const rest = i % 1000000;
    baht += groupToThai(mil) + "ล้าน";
    if (rest > 0) baht += groupToThai(rest);
  } else {
    baht = groupToThai(i);
  }
  baht += "บาท";
  if (satang > 0) {
    baht += groupToThai(satang) + "สตางค์";
  } else {
    baht += "ถ้วน";
  }
  return baht;
}

// ---------- CALC TOTALS ---------------------------------------------------
function calcTotals(items, discountStr, vatRate) {
  const subtotal = items.reduce((sum, item) => {
    return sum + (parseNum(item.unitPrice) * (parseFloat(item.qty) || 0));
  }, 0);
  const discount = parseNum(discountStr);
  const afterDisc = Math.max(0, subtotal - discount);
  const vat = afterDisc * (vatRate / 100);
  const grand = afterDisc + vat;
  return {
    subtotal:     fmtNum(subtotal),
    discount:     fmtNum(discount),
    afterDiscount:fmtNum(afterDisc),
    vatAmount:    fmtNum(vat),
    grandTotal:   fmtNum(grand),
  };
}

// ---------- DEFAULT DATA --------------------------------------------------
function defaultData(mode) {
  const prefix = mode === "invoice" ? "INV" : "QT";
  const today = new Date().toISOString().slice(0, 10);
  return {
    documentNumber: `${prefix}-${new Date().getFullYear()}-`,
    documentDate: today,
    validUntil: 30,
    salesPerson: "",
    customerName: "",
    customerAddress: "",
    customerPhone: "",
    customerEmail: "",
    customerTaxId: "",
    discount: "0.00",
    vatRate: 7,
    notes: [""],
    items: [{ description: "", qty: 1, unit: "", unitPrice: "0.00", amount: "0.00" }],
  };
}

// ---------- ITEMS TABLE ---------------------------------------------------
function ItemsTable({ items, onChange }) {
  const [editing, setEditing] = useState(null);
  const inputRef = useRef(null);

  useEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editing]);

  const fields = ["description", "qty", "unit", "unitPrice"];

  const handleCommit = (value, rowIdx, field) => {
    const updated = items.map((item, i) => {
      if (i !== rowIdx) return item;
      const newItem = { ...item };
      if (field === "unitPrice") {
        newItem.unitPrice = fmtNum(parseNum(value));
        newItem.amount = fmtNum(parseNum(value) * (parseFloat(newItem.qty) || 0));
      } else if (field === "qty") {
        newItem.qty = parseFloat(value) || 1;
        newItem.amount = fmtNum(parseNum(item.unitPrice) * (parseFloat(value) || 0));
      } else {
        newItem[field] = value;
      }
      return newItem;
    });
    onChange(updated);
    setEditing(null);
  };

  const handleKeyDown = (e, rowIdx, field) => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleCommit(e.target.value, rowIdx, field);
      const idx = fields.indexOf(field);
      const nextF = idx < fields.length - 1 ? fields[idx + 1] : fields[0];
      setTimeout(() => setEditing({ row: rowIdx, field: nextF }), 0);
    } else if (e.key === "Tab") {
      e.preventDefault();
      handleCommit(e.target.value, rowIdx, field);
      const idx = fields.indexOf(field);
      if (idx < fields.length - 1) {
        setTimeout(() => setEditing({ row: rowIdx, field: fields[idx + 1] }), 0);
      } else if (rowIdx < items.length - 1) {
        setTimeout(() => setEditing({ row: rowIdx + 1, field: "description" }), 0);
      }
    } else if (e.key === "Escape") {
      setEditing(null);
    }
  };

  const addRow = () => {
    onChange([...items, { description: "", qty: 1, unit: "", unitPrice: "0.00", amount: "0.00" }]);
    setTimeout(() => setEditing({ row: items.length, field: "description" }), 50);
  };

  const deleteRow = (idx) => {
    if (items.length <= 1) return;
    onChange(items.filter((_, i) => i !== idx));
  };

  const renderCell = (rowIdx, field) => {
    if (editing && editing.row === rowIdx && editing.field === field) {
      const val = field === "unitPrice" ? items[rowIdx][field] : items[rowIdx][field];
      return (
        <input
          ref={inputRef}
          className={"cell-input" + (field !== "description" ? " cell-input--mono cell-input--right" : "")}
          defaultValue={field === "unitPrice" ? val : val}
          onBlur={(e) => handleCommit(e.target.value, rowIdx, field)}
          onKeyDown={(e) => handleKeyDown(e, rowIdx, field)}
        />
      );
    }
    const val = field === "description" ? items[rowIdx][field] : items[rowIdx][field];
    const displayVal = field === "description" ? (val || "—") : val;
    const cls = "cell-input" + (field !== "description" ? " cell-input--mono cell-input--right" : "");
    return (
      <div className={cls} tabIndex={0} style={{ cursor: "text", minHeight: 30 }}
        onClick={() => setEditing({ row: rowIdx, field })}
        onFocus={() => setEditing({ row: rowIdx, field })}>
        {displayVal}
      </div>
    );
  };

  return (
    <div>
      <div className="items-table-wrap">
        <table className="items-table">
          <thead>
            <tr>
              <th className="col-no">#</th>
              <th className="col-desc">รายการ</th>
              <th className="col-qty">จำนวน</th>
              <th className="col-unit">หน่วย</th>
              <th className="col-price">ราคา/หน่วย</th>
              <th className="col-amount">จำนวนเงิน</th>
              <th className="col-act"></th>
            </tr>
          </thead>
          <tbody>
            {items.map((item, idx) => (
              <tr key={idx}>
                <td className="item-no">{String(idx + 1).padStart(2, "0")}</td>
                <td>{renderCell(idx, "description")}</td>
                <td>{renderCell(idx, "qty")}</td>
                <td>{renderCell(idx, "unit")}</td>
                <td>{renderCell(idx, "unitPrice")}</td>
                <td><div className="cell-readonly">{item.amount}</div></td>
                <td>
                  {items.length > 1 && (
                    <button className="row-delete" onClick={() => deleteRow(idx)} title="ลบรายการ">
                      <i data-lucide="trash-2" style={{ width: 16, height: 16 }}></i>
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <button className="add-row-btn" onClick={addRow}>
        <i data-lucide="plus" style={{ width: 16, height: 16 }}></i> เพิ่มรายการ
      </button>
    </div>
  );
}

// ---------- TOTALS BLOCK --------------------------------------------------
function TotalsBlock({ totals, discount, vatRate, onDiscountChange, onVatRateChange }) {
  const showVat = vatRate > 0;
  return (
    <div className="totals-section">
      <table className="totals-table">
        <tbody>
          <tr>
            <td>รวมเงิน</td>
            <td>{totals.subtotal}</td>
          </tr>
          <tr className="totals-discount">
            <td>ส่วนลด</td>
            <td>
              <input
                className="totals-input"
                type="text"
                value={discount}
                onChange={e => onDiscountChange(e.target.value)}
              />
            </td>
          </tr>
          <tr>
            <td>หลังหักส่วนลด</td>
            <td>{totals.afterDiscount}</td>
          </tr>
          {showVat && (
            <tr>
              <td>ภาษีมูลค่าเพิ่ม
                <span style={{ display: "inline-block", marginLeft: 4 }}>
                  <input
                    className="totals-input"
                    type="text"
                    value={vatRate}
                    onChange={e => onVatRateChange(parseFloat(e.target.value) || 0)}
                    style={{ width: 44, textAlign: "center", padding: "2px 4px" }}
                  />
                </span>%
              </td>
              <td>{totals.vatAmount}</td>
            </tr>
          )}
          <tr className="totals-total">
            <td>รวมทั้งสิ้น</td>
            <td>{totals.grandTotal}</td>
          </tr>
          <tr className="totals-baht">
            <td></td>
            <td>( {numToThaiBaht(totals.grandTotal)} )</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// ---------- NOTES ---------------------------------------------------------
function NotesEditor({ notes, onChange }) {
  const updateNote = (idx, value) => {
    const updated = [...notes];
    updated[idx] = value;
    if (idx === updated.length - 1 && value !== "") {
      updated.push("");
    }
    if (updated.length > 2 && updated[updated.length - 2] === "" && updated[updated.length - 1] === "") {
      updated.pop();
    }
    onChange(updated);
  };

  const removeNote = (idx) => {
    if (notes.length <= 1) return;
    onChange(notes.filter((_, i) => i !== idx));
  };

  return (
    <ul className="notes-list">
      {notes.map((n, i) => (
        <li key={i} className="note-row">
          <span className="note-index">{String(i + 1).padStart(2, "0")}</span>
          <input
            className="note-input"
            value={n}
            onChange={e => updateNote(i, e.target.value)}
            placeholder="หมายเหตุเพิ่มเติม..."
          />
          {notes.length > 1 && (
            <button className="row-delete" onClick={() => removeNote(i)} title="ลบหมายเหตุ">
              <i data-lucide="trash-2" style={{ width: 16, height: 16 }}></i>
            </button>
          )}
        </li>
      ))}
    </ul>
  );
}

// ---------- FORM ----------------------------------------------------------
function QuotationForm({ mode, data, onChange }) {
  const update = (key, value) => onChange({ ...data, [key]: value });

  const totals = calcTotals(data.items, data.discount, data.vatRate);

  const isInvoice = mode === "invoice";

  return (
    <div>
      {/* Customer Info */}
      <div className="form-block">
        <h2 className="form-block__title">
          {isInvoice ? "ข้อมูลผู้ซื้อ" : "ข้อมูลลูกค้า"}
        </h2>
        <div className="form-grid">
          <Field label="ชื่อลูกค้า / บริษัท" value={data.customerName}
            onChange={v => update("customerName", v)} placeholder="ชื่อบริษัทลูกค้า" />
          <Field label="เบอร์โทรศัพท์" value={data.customerPhone}
            onChange={v => update("customerPhone", v)} placeholder="02-xxx-xxxx" />
          <Field label="ที่อยู่" value={data.customerAddress}
            onChange={v => update("customerAddress", v)} placeholder="ที่อยู่ลูกค้า" fullWidth={true} />
          <Field label="อีเมล" value={data.customerEmail}
            onChange={v => update("customerEmail", v)} placeholder="email@example.com" type="email" />
          {isInvoice && (
            <Field label="เลขประจำตัวผู้เสียภาษี" value={data.customerTaxId}
              onChange={v => update("customerTaxId", v)} placeholder="เลข 13 หลัก" />
          )}
        </div>
      </div>

      {/* Document Meta */}
      <div className="form-block">
        <h2 className="form-block__title">
          {isInvoice ? "รายละเอียดใบกำกับภาษี" : "รายละเอียดใบเสนอราคา"}
        </h2>
        <div className="meta-row">
          <Field label="เลขที่เอกสาร" value={data.documentNumber}
            onChange={v => update("documentNumber", v)} placeholder="QT-2026-0001" />
          <Field label="วันที่ออกเอกสาร" value={data.documentDate}
            onChange={v => update("documentDate", v)} type="date" />
          <Field label="อายุเสนอราคา (วัน)" value={data.validUntil}
            onChange={v => update("validUntil", parseInt(v) || 0)} type="number" />
          <Field label="ผู้จัดทำ" value={data.salesPerson}
            onChange={v => update("salesPerson", v)} placeholder="ชื่อพนักงานขาย" />
        </div>
      </div>

      {/* Items */}
      <div className="form-block">
        <h2 className="form-block__title">รายการสินค้า / บริการ</h2>
        <ItemsTable items={data.items} onChange={items => update("items", items)} />
      </div>

      {/* Totals */}
      <div className="form-block">
        <h2 className="form-block__title">สรุปราคา</h2>
        <TotalsBlock
          totals={totals}
          discount={data.discount}
          vatRate={data.vatRate}
          onDiscountChange={v => update("discount", v)}
          onVatRateChange={v => update("vatRate", v)}
        />
      </div>

      {/* Notes */}
      <div className="form-block">
        <h2 className="form-block__title">หมายเหตุ</h2>
        <NotesEditor notes={data.notes} onChange={notes => update("notes", notes)} />
      </div>
    </div>
  );
}

Object.assign(window, { calcTotals, defaultData, QuotationForm, ItemsTable, TotalsBlock, NotesEditor, numToThaiBaht });
