/* global CRQQB_SETTINGS, CRQQB_VARS */
const { useState, useMemo } = React;

const fmt2 = (n)=> new Intl.NumberFormat('en-IN',{minimumFractionDigits:2, maximumFractionDigits:2}).format(+n||0);

/** daily-sequenced ID: CRQ/YYMMDD/NNNN (start 21, +6) */
function nextAutoId(baseDate) {
  const d = baseDate ? new Date(baseDate) : new Date();
  const y = String(d.getFullYear()).slice(-2);
  const m = String(d.getMonth()+1).padStart(2,'0');
  const day = String(d.getDate()).padStart(2,'0');
  const key = `crq-seq-${y}${m}${day}`;
  let last = parseInt(localStorage.getItem(key)||'15', 10);
  if (!Number.isFinite(last)) last = 15;
  let nxt = last + 6;
  if (nxt < 21) nxt = 21;
  localStorage.setItem(key, String(nxt));
  const serial = String(nxt).padStart(4,'0');
  return `CRQ/${y}${m}${day}/${serial}`;
}

function parseStateFromGSTIN(gstin){
  if (!gstin || gstin.length < 2) return {code:"", state:""};
  const map = {"27":"Maharashtra","24":"Gujarat","09":"Uttar Pradesh","07":"Delhi"}; // minimal map
  const code = gstin.slice(0,2);
  return {code, state: map[code] || ""};
}

const INDIA_STATES = [
  "Andhra Pradesh","Arunachal Pradesh","Assam","Bihar","Chhattisgarh","Goa","Gujarat","Haryana","Himachal Pradesh",
  "Jharkhand","Karnataka","Kerala","Madhya Pradesh","Maharashtra","Manipur","Meghalaya","Mizoram","Nagaland",
  "Odisha","Punjab","Rajasthan","Sikkim","Tamil Nadu","Telangana","Tripura","Uttar Pradesh","Uttarakhand","West Bengal",
  "Andaman and Nicobar Islands","Chandigarh","Dadra and Nagar Haveli and Daman and Diu","Delhi","Jammu and Kashmir",
  "Ladakh","Lakshadweep","Puducherry"
];
function inrWords(n){
  const a=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"];
  const b=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"];
  n = Math.floor(+n||0);
  const two = (x)=> x<20?a[x]:b[Math.floor(x/10)]+(x%10?(" "+a[x%10]):"");
  const three = (x)=> x<100?two(x):(a[Math.floor(x/100)]+" Hundred"+(x%100?(" "+two(x%100)):""));
  const crore=Math.floor(n/1e7), lakh=Math.floor((n%1e7)/1e5), th=Math.floor((n%1e5)/1e3), h=n%1e3;
  return [crore?two(crore)+" Crore":"", lakh?two(lakh)+" Lakh":"", th?two(th)+" Thousand":"", h?three(h):""].filter(Boolean).join(" ")+" Rupees Only";
}

function defaultsFromSettings() {
  const s = CRQQB_SETTINGS || {};
  const today = new Date();
  const y = String(today.getFullYear()).slice(-2);
  const m = String(today.getMonth()+1).padStart(2,'0');
  return {
    header: { doc_type: 'Quotation', number_label: '', cr_no: `CRQ/${y}${m}${String(today.getDate()).padStart(2,'0')}/0021`, cr_date: today.toISOString().slice(0,10), chip: s.seal_text, place_of_supply: s.place_of_supply },
    job: { job_type: s.default_job_type || 'Re-rubberisation', machine: '', model: '', rubber_grade: s.default_rubber_grade || '', employee_id: '' },
    customer: { name: '', gstin: '', phone:'', email:'', contact_person:'', billing_address:'', pin:'', state:'', state_code:'', shipping_same:true, shipping_address:'' },
    items: [],
    default_rate: 0,
    quote_discount: 0, freight: 0, packaging: 0,
    freight_taxable: true, packaging_taxable: true,
    gst_enabled: true,
    warranty_text: '',
    settings: {
      company: { name: s.company_name, website: s.company_website, office: s.office_address, plant: s.plant_address, branch: s.branch_address, phone: s.company_phone, email: s.company_email, gstin: s.gstin, logo_url: s.logo_url },
      banking: { bank_name: s.bank_name, account_name: s.account_name, account_no: s.account_no, ifsc: s.ifsc, branch: s.branch, upi_id: s.upi_id },
      tax: { mode: s.tax_mode || 'CGST+SGST', percent: +s.tax_percent || 18 },
      labels: { warranty: s.warranty_label || 'Warranty' },
      // Split terms on real newlines so each line becomes its own list item
      terms: (s.terms || '').split(/\r?\n/).filter(Boolean),
      footnote: s.footnote || '',
      // Pass through signature and designation for the print template
      signature_url: s.signature_url,
      designation: s.designation
    }
  };
}

function computeTotals(payload) {
  const isRe = payload.job?.job_type === 'Re-rubberisation';
  const defaultRate = +payload.default_rate || 0;

  const subTotal = Math.round(payload.items.reduce((acc, it) => {
    const base = (Number(it.length_mm)||0) * (Number(it.diameter_mm)||0) / 100;
    const effRate = (it.rate === '' || it.rate === undefined || it.rate === null) ? defaultRate : (Number(it.rate)||0);
    const line = base * effRate * (Number(it.qty)||0);
    const afterDisc = it.disc_type === '%' ? (line - (line * (Number(it.discount)||0) / 100)) : (line - (Number(it.discount)||0));
    const spindle = isRe ? 0 : (Number(it.spindle)||0);
    const withSpindle = afterDisc + spindle;
    return acc + Math.max(0, withSpindle);
  }, 0) * 100) / 100;

  const freight = Number(payload.freight)||0;
  const packaging = Number(payload.packaging)||0;
  const quoteDisc = Number(payload.quote_discount)||0;

  const taxableCharges = (payload.freight_taxable ? freight : 0) + (payload.packaging_taxable ? packaging : 0);
  const nontaxCharges = (payload.freight_taxable ? 0 : freight) + (payload.packaging_taxable ? 0 : packaging);

  const afterQuoteDisc = Math.max(0, subTotal - quoteDisc);
  const taxable = Math.round((afterQuoteDisc + taxableCharges) * 100) / 100;

  const gstEnabled = !!payload.gst_enabled;
  const taxPct = Number(payload.settings?.tax?.percent)||0;
  const isIGST = (payload.settings?.tax?.mode === 'IGST');

  let tax=0, cgst=0, sgst=0, igst=0;
  if (gstEnabled && taxPct>0) {
    tax = Math.round(taxable * taxPct) / 100;
    if (isIGST) {
      igst = tax;
    } else {
      cgst = Math.round((tax/2) * 100)/100;
      sgst = Math.round((tax/2) * 100)/100;
    }
  }

  const preRound = taxable + (gstEnabled ? tax : 0) + nontaxCharges;
  const grand = Math.round(preRound);
  const roundOff = Math.round((grand - preRound) * 100) / 100;

  return { subTotal, taxable, tax: (gstEnabled?tax:0), cgst, sgst, igst, nontaxCharges, roundOff, grand, words: inrWords(grand) };
}

function App() {
  const [payload, setPayload] = useState(defaultsFromSettings());
  const totals = useMemo(()=>computeTotals(payload), [payload]);

  // Add a new item row.  New rows default the HSN code to 84439100 as
  // required.  Other fields remain editable.
  const addRow = ()=> setPayload(p=>({
    ...p,
    items: [...p.items, {
      unit: 'Inking',
      type: '',
      hsn: '84439100',
      qty: 1,
      diameter_mm: 0,
      length_mm: 0,
      rubber_grade: p.job?.rubber_grade || '',
      rate: '',
      discount: 0,
      disc_type: '%',
      spindle: 0
    }]
  }));
  const delRow = (idx)=> setPayload(p=>({...p, items: p.items.filter((_,i)=>i!==idx)}));
  const updateRow = (idx, key, val)=> setPayload(p=>{ const items = p.items.slice(); items[idx] = {...items[idx], [key]: val}; return {...p, items}; });

  const postToPrint = ()=> {
    const w = window.open(CRQQB_VARS?.print_url, '_blank');
    const data = {...payload, totals};
    let tries = 0;
    const send = ()=> {
      try { w.postMessage({type:'CRQ_PAYLOAD', payload: data}, '*'); } catch(e){}
      tries++;
      if (tries<14 && w && !w.closed) setTimeout(send, 250);
    };
    setTimeout(send, 350);
  };

  const gst = parseStateFromGSTIN(payload.customer.gstin||"");

  return (
    <div>
      <datalist id="crq-unit-suggestions">
        <option value="Inking" /><option value="Dampening" />
      </datalist>

      {/* Header */}
      <div className="section-title">Header</div>
      <div className="crq-grid">
        <div style={{gridColumn:'span 6 / span 6'}}>
          <label>{payload.header.number_label || (payload.header.doc_type==="Invoice" ? "Invoice No." : (payload.header.doc_type==="Pro Forma Invoice" ? "Pro Forma Invoice No." : "Quotation No."))}</label>
          <div style={{display:"flex", gap:6}}>
            <input className="crq-input" style={{flex:1}} value={payload.header.cr_no} onChange={e=>setPayload(p=>({...p, header:{...p.header, cr_no:e.target.value}}))} />
            <button type="button" className="crq-btn" onClick={()=>setPayload(p=>({...p, header:{...p.header, cr_no: nextAutoId(p.header.cr_date)}}))}>Auto</button>
          </div>
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Document Type</label>
          <select className="crq-select" value={payload.header.doc_type} onChange={e=>setPayload(p=>({...p, header:{...p.header, doc_type:e.target.value}}))}>
            <option>Quotation</option>
            <option>Pro Forma Invoice</option>
            <option>Invoice</option>
          </select>
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Number Label (optional)</label>
          <input className="crq-input" value={payload.header.number_label} onChange={e=>setPayload(p=>({...p, header:{...p.header, number_label:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 6 / span 6'}}>
          <label>CR Date</label>
          <input className="crq-input" type="date" value={payload.header.cr_date} onChange={e=>setPayload(p=>({...p, header:{...p.header, cr_date:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Header Chip</label>
          <select className="crq-select" value={payload.header.chip} onChange={e=>setPayload(p=>({...p, header:{...p.header, chip:e.target.value}}))}>
            <option>Original for Recipient</option><option>Duplicate</option><option>Triplicate</option>
          </select>
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Place of Supply</label>
          <input className="crq-input" value={payload.header.place_of_supply||''} onChange={e=>setPayload(p=>({...p, header:{...p.header, place_of_supply:e.target.value}}))} />
        </div>
      </div>

      {/* Customer */}
      <div className="section-title">Customer</div>
      <div className="crq-grid">
        <div style={{gridColumn:'span 6 / span 6'}}>
          <label>M/S</label>
          <input className="crq-input" value={payload.customer.name||''}
                 onChange={e=>setPayload(p=>({...p, customer:{...p.customer, name:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Contact Person</label>
          <input className="crq-input" value={payload.customer.contact||''}
                 onChange={e=>setPayload(p=>({...p, customer:{...p.customer, contact:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Phone</label>
          <input
            className="crq-input"
            type="tel"
            pattern="[0-9+ -]*"
            inputMode="tel"
            value={payload.customer.phone||''}
            onChange={e=>setPayload(p=>({...p, customer:{...p.customer, phone:e.target.value}}))}
          />
        </div>
        <div style={{gridColumn:'span 12 / span 12'}}>
          <label>Billing Address</label>
          <textarea className="crq-textarea" value={payload.customer.billing_address||''}
                    onChange={e=>setPayload(p=>({...p, customer:{...p.customer, billing_address:e.target.value, ...(p.customer.shipping_same ? {shipping_address:e.target.value} : {})}}))} />
        </div>
        <div style={{gridColumn:'span 6 / span 6'}}>
          <label>GSTIN</label>
          <input className="crq-input" value={(payload.customer.gstin||'')}
                 onChange={e=>{ const v=e.target.value.toUpperCase(); const g=parseStateFromGSTIN(v);
                   setPayload(p=>({...p, customer:{...p.customer, gstin:v, state: (g.state||p.customer.state||''), state_code:(g.code||p.customer.state_code||'')}}));
                 }} />
        </div>
        <div style={{gridColumn:'span 6 / span 6'}}>
          <label>State</label>
          <select className="crq-select" value={payload.customer.state||''}
                  onChange={e=>setPayload(p=>({...p, customer:{...p.customer, state:e.target.value}}))}>
            <option value="">Select state</option>
            {INDIA_STATES.map(s=><option key={s} value={s}>{s}</option>)}
          </select>
        </div>
        <div style={{gridColumn:'span 12 / span 12', display:'flex', gap:8, alignItems:'center'}}>
          <input id="ship_same" type="checkbox" checked={!!payload.customer.shipping_same}
                 onChange={e=>setPayload(p=>({...p, customer:{...p.customer, shipping_same:e.target.checked, shipping_address: e.target.checked ? (p.customer.billing_address||'') : p.customer.shipping_address}}))} />
          <label htmlFor="ship_same">Shipping same as Billing</label>
        </div>
        <div style={{gridColumn:'span 12 / span 12'}}>
          <label>Shipping Address</label>
          <textarea className="crq-textarea" value={payload.customer.shipping_address||''}
                    onChange={e=>setPayload(p=>({...p, customer:{...p.customer, shipping_address:e.target.value}}))} disabled={!!payload.customer.shipping_same} />
        </div>
      </div>


      {/* Job */}
      <div className="section-title">Job</div>
      <div className="crq-grid">
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Job Type</label>
          <select className="crq-select" value={payload.job.job_type} onChange={e=>setPayload(p=>({...p, job:{...p.job, job_type:e.target.value}}))}>
            <option>New Roller</option><option>Re-rubberisation</option>
          </select>
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Machine</label>
          <input className="crq-input" value={payload.job.machine} onChange={e=>setPayload(p=>({...p, job:{...p.job, machine:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Model</label>
          <input className="crq-input" value={payload.job.model} onChange={e=>setPayload(p=>({...p, job:{...p.job, model:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Rubber Grade (Default/Trade)</label>
          <input className="crq-input" value={payload.job.rubber_grade} onChange={e=>setPayload(p=>({...p, job:{...p.job, rubber_grade:e.target.value}}))} />
        </div>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Employee ID</label>
          <input className="crq-input" value={payload.job.employee_id} onChange={e=>setPayload(p=>({...p, job:{...p.job, employee_id:e.target.value}}))} />
        </div>
      </div>

      {/* Global */}
      <div className="section-title">Global</div>
      <div className="crq-grid" style={{marginTop:12, marginBottom:12}}>
        <div style={{gridColumn:'span 3 / span 3'}}>
          <label>Default Rate (₹)</label>
          <input className="crq-input" type="number" min="0" step="0.01" value={payload.default_rate} onChange={e=>setPayload(p=>({...p, default_rate: +e.target.value || 0}))} />
        </div>
      </div>

      {/* Items */}
      <div className="section-title">Items</div>
      <div className="crq-table-wrap">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>Unit</th>
              <th>Type</th>
              <th>HSN</th>
              <th>Qty</th>
              <th>Dia (mm)</th>
              <th>R.L. (mm)</th>
              <th style={{display:"none"}}>Rate (₹)</th>
              <th>Disc</th>
              <th>Disc Type</th>
              {payload.job?.job_type==="Re-rubberisation" ? null : <th>Spindle (₹)</th>}
              <th></th>
            </tr>
          </thead>
          <tbody>
            {payload.items.map((it, idx)=>{
              const isRe = payload.job?.job_type === 'Re-rubberisation';
              return (
                <tr key={idx}>
                  <td>{idx+1}</td>
                  <td><input list="crq-unit-suggestions" className="crq-input" value={it.unit||''} onChange={e=>updateRow(idx,'unit', e.target.value)} /></td>
                  <td><input className="crq-input" value={it.type||''} onChange={e=>updateRow(idx,'type', e.target.value)} /></td>
                  <td><input className="crq-input" value={it.hsn||''} onChange={e=>updateRow(idx,'hsn', e.target.value)} /></td>
                  <td><input className="crq-input" type="number" min="0" step="1" value={it.qty||0} onChange={e=>updateRow(idx,'qty', +e.target.value||0)} /></td>
                  <td><input className="crq-input" type="number" min="0" step="0.01" value={it.diameter_mm||0} onChange={e=>updateRow(idx,'diameter_mm', +e.target.value||0)} /></td>
                  <td><input className="crq-input" type="number" min="0" step="0.01" value={it.length_mm||0} onChange={e=>updateRow(idx,'length_mm', +e.target.value||0)} /></td>
                  <td><input className="crq-input" type="number" min="0" step="0.01" placeholder={String(payload.default_rate||'')} value={(it.rate===''||it.rate===undefined)?'':it.rate} onChange={e=>updateRow(idx,'rate', e.target.value===''?'':(+e.target.value||0))} /></td>
                  <td><input className="crq-input" type="number" min="0" step="0.01" value={it.discount||0} onChange={e=>updateRow(idx,'discount', +e.target.value||0)} /></td>
                  <td>
                    <select className="crq-select" value={it.disc_type||'%'} onChange={e=>updateRow(idx,'disc_type', e.target.value)}>
                      <option value="%">%</option><option value="₹">₹</option>
                    </select>
                  </td>
                  <td><input className="crq-input" type="number" min="0" step="0.01" disabled={isRe} value={isRe?0:(it.spindle||0)} onChange={e=>updateRow(idx,'spindle', +e.target.value||0)} /></td>
                  <td><button className="crq-btn secondary" onClick={()=>delRow(idx)}>Del</button></td>
                </tr>
              );
            })}
          </tbody>
          <tfoot>
            <tr>
              <td colSpan="12" className="sticky-bar">
                <div className="actions">
                  <button className="crq-btn" onClick={addRow}>+ Add Row</button>
                  <button className="crq-btn secondary" onClick={()=>navigator.clipboard.writeText(JSON.stringify(payload,null,2))}>Copy JSON</button>
                </div>
                <div className="actions">
                  <button className="crq-btn" onClick={postToPrint}>Print / Download</button>
                </div>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>

      {/* Totals & Flags */}
      <div className="section-title">Totals</div>
      <div className="crq-grid">
        <div style={{gridColumn:'span 3 / span 3'}}><label>Quote Discount (₹)</label><input className="crq-input" type="number" min="0" step="0.01" value={payload.quote_discount} onChange={e=>setPayload(p=>({...p, quote_discount:+e.target.value||0}))} /></div>
        <div style={{gridColumn:'span 3 / span 3'}}><label>Freight (₹)</label><input className="crq-input" type="number" min="0" step="0.01" value={payload.freight} onChange={e=>setPayload(p=>({...p, freight:+e.target.value||0}))} /></div>
        <div style={{gridColumn:'span 3 / span 3'}}><label>Packaging (₹)</label><input className="crq-input" type="number" min="0" step="0.01" value={payload.packaging} onChange={e=>setPayload(p=>({...p, packaging:+e.target.value||0}))} /></div>
        <div style={{gridColumn:'span 3 / span 3', display:'flex', gap:12, alignItems:'end'}}>
          <label><input type="checkbox" checked={payload.freight_taxable} onChange={e=>setPayload(p=>({...p, freight_taxable:e.target.checked}))}/> Freight taxable</label>
          <label><input type="checkbox" checked={payload.packaging_taxable} onChange={e=>setPayload(p=>({...p, packaging_taxable:e.target.checked}))}/> Packaging taxable</label>
          <label><input type="checkbox" checked={payload.gst_enabled} onChange={e=>setPayload(p=>({...p, gst_enabled:e.target.checked}))}/> GST Enabled</label>
        </div>
      </div>

      <div className="crq-grid" style={{marginTop:8}}>
        <div style={{gridColumn:'span 4 / span 4'}} className="small">Sub Total: ₹ {fmt2(totals.subTotal)}</div>
        <div style={{gridColumn:'span 4 / span 4'}} className="small">Taxable Total: ₹ {fmt2(totals.taxable)}</div>
        <div style={{gridColumn:'span 4 / span 4'}} className="small">Non-taxable Charges: ₹ {fmt2(totals.nontaxCharges)}</div>
      </div>
      <div className="crq-grid">
        {payload.settings.tax.mode==='IGST'
          ? (<div style={{gridColumn:'span 4 / span 4'}}>IGST ({payload.settings.tax.percent}%): ₹ {fmt2(totals.igst)}</div>)
          : (<>
               <div style={{gridColumn:'span 4 / span 4'}}>CGST ({payload.settings.tax.percent/2}%): ₹ {fmt2(totals.cgst)}</div>
               <div style={{gridColumn:'span 4 / span 4'}}>SGST ({payload.settings.tax.percent/2}%): ₹ {fmt2(totals.sgst)}</div>
             </>)
        }
        <div style={{gridColumn:'span 4 / span 4'}}>Round-off: ₹ {fmt2(totals.roundOff)}</div>
      </div>
      <div className="crq-grid">
        <div style={{gridColumn:'span 12 / span 12', fontSize:18, fontWeight:600}}>Grand Total: ₹ {fmt2(totals.grand)}</div>
        <div style={{gridColumn:'span 12 / span 12'}} className="small">Amount in words: {totals.words}</div>
      </div>

      {/* Warranty */}
      <div className="section-title">{payload.settings.labels.warranty}</div>
      <textarea className="crq-textarea" placeholder="Write warranty terms for THIS quotation (shows on print)" value={payload.warranty_text} onChange={e=>setPayload(p=>({...p, warranty_text:e.target.value}))} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('crqqb-root')).render(<App/>);
