// Buyer portal — request a quote against an open lot
const { Eyebrow, Button, Card, Input, Select, Textarea, Fieldset, Checkbox, Toast, ToastRegion, Icon, DataList, LotCode, Badge } = window.FF;

const QUOTE_LOTS = [
  { id: 'KP-BLK-2026-014', grade: 'Black · Kampot PGI', origin: 'Chhouk', available: 4280, price: 18.4 },
  { id: 'KP-BLK-2026-015', grade: 'Black · Kampot PGI', origin: 'Chhouk', available: 1960, price: 18.4 },
  { id: 'KP-RED-2026-006', grade: 'Red · Kampot PGI', origin: 'Dang Tong', available: 610, price: 32.0 },
  { id: 'KP-WHT-2026-003', grade: 'White · Kampot PGI', origin: 'Chhouk', available: 925, price: 26.5 },
];

const QUOTE_EMPTY = { lot: '', kg: '', incoterm: 'FOB Sihanoukville', shipment: '2026-09', po: '', notes: '', include: ['Certificates', 'Spec sheet'] };
const QUOTE_LABEL = { lot: 'Lot', kg: 'Quantity', shipment: 'Requested shipment' };

function validateQuote(v) {
  const e = {};
  const lot = QUOTE_LOTS.find((l) => l.id === v.lot);
  if (!v.lot) e.lot = 'Choose the lot you want quoted.';
  if (!v.kg.trim()) e.kg = 'Enter a quantity in kilograms.';
  else if (!/^\d+$/.test(v.kg.trim())) e.kg = 'Whole kilograms, digits only.';
  else if (Number(v.kg) < 25) e.kg = 'Minimum order is 25 kg.';
  else if (lot && Number(v.kg) > lot.available) e.kg = 'Only ' + lot.available.toLocaleString('en-GB').replace(/,/g, ' ') + ' kg is uncommitted in this lot.';
  if (!v.shipment) e.shipment = 'Give the month you need it to sail.';
  return e;
}

function RequestQuote() {
  const [v, setV] = React.useState(QUOTE_EMPTY);
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [sent, setSent] = React.useState(null);
  const summaryRef = React.useRef(null);

  const set = (k) => (val) => {
    setV((s) => ({ ...s, [k]: val }));
    setErrors((s) => (s[k] ? { ...s, [k]: undefined } : s));
  };

  const lot = QUOTE_LOTS.find((l) => l.id === v.lot);
  const kg = /^\d+$/.test(v.kg.trim()) ? Number(v.kg) : null;
  const value = lot && kg ? (lot.price * kg) : null;
  const fmt = (n) => n.toLocaleString('en-GB', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/,/g, ' ');

  const onSubmit = (e) => {
    e.preventDefault();
    if (submitting) return;
    const found = validateQuote(v);
    if (Object.keys(found).length) {
      setErrors(found);
      window.requestAnimationFrame(() => summaryRef.current && summaryRef.current.focus());
      return;
    }
    setErrors({});
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setSent({ ref: 'FF-Q-2026-0312', lot: v.lot, kg: v.kg });
      setV(QUOTE_EMPTY);
    }, 1200);
  };

  const invalidKeys = Object.keys(errors).filter((k) => errors[k]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
      <div>
        <Eyebrow>Orders</Eyebrow>
        <h1 style={{ margin: '14px 0 6px', font: 'var(--type-display-3)', color: 'var(--text-strong)' }}>Request a quote</h1>
        <p style={{ margin: 0, maxWidth: '64ch', font: 'var(--type-body)', color: 'var(--text-muted)' }}>
          Quotes are drawn from uncommitted stock in the lot register. Nothing is reserved until you accept.
        </p>
      </div>

      <form noValidate onSubmit={onSubmit} style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 'var(--space-6)', alignItems: 'start' }}>
        <Card padding="lg">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
            {invalidKeys.length ? (
              <div
                ref={summaryRef}
                tabIndex={-1}
                role="alert"
                style={{ display: 'flex', gap: 12, padding: 'var(--space-4)', background: 'var(--status-danger-soft)', borderRadius: 'var(--radius-md)', borderLeft: '2px solid var(--ff-pepper)', outline: 'none' }}
              >
                <Icon name="alert-circle" size={18} style={{ color: 'var(--ff-pepper)', marginTop: 2, flex: '0 0 auto' }} />
                <div>
                  <p style={{ margin: 0, font: 'var(--type-body-sm)', fontSize: 15, fontWeight: 600, color: 'var(--text-strong)' }}>
                    {invalidKeys.length === 1 ? 'One field needs attention' : invalidKeys.length + ' fields need attention'}
                  </p>
                  <span style={{ display: 'block', marginTop: 4, font: 'var(--type-body-sm)', fontSize: 13, color: 'var(--text-muted)' }}>
                    {invalidKeys.map((k) => QUOTE_LABEL[k]).join(' · ')}
                  </span>
                </div>
              </div>
            ) : null}

            <Select
              label="Lot" error={errors.lot} value={v.lot} disabled={submitting}
              hint={errors.lot ? undefined : 'Only lots with uncommitted stock are listed.'}
              onChange={(e) => set('lot')(e.target.value)}
            >
              <option value="">Select a lot</option>
              {QUOTE_LOTS.map((l) => (
                <option key={l.id} value={l.id}>{l.id} — {l.grade} — {l.available.toLocaleString('en-GB')} kg</option>
              ))}
            </Select>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-5)' }}>
              <Input
                label="Quantity" suffix="kg" inputMode="numeric" required error={errors.kg} value={v.kg} disabled={submitting}
                hint={errors.kg ? undefined : lot ? 'Up to ' + lot.available.toLocaleString('en-GB') + ' kg available' : 'Minimum 25 kg'}
                onChange={(e) => set('kg')(e.target.value)}
              />
              <Select
                label="Incoterm" value={v.incoterm} disabled={submitting}
                options={['FOB Sihanoukville', 'CIF Le Havre', 'CIF Rotterdam', 'EXW Phnom Penh']}
                onChange={(e) => set('incoterm')(e.target.value)}
              />
              <Input
                label="Requested shipment" type="month" error={errors.shipment} value={v.shipment} disabled={submitting}
                hint={errors.shipment ? undefined : 'Containers sail every second Friday.'}
                onChange={(e) => set('shipment')(e.target.value)}
              />
              <Input
                label="Your PO reference" mono placeholder="ME-2026-118" value={v.po} disabled={submitting}
                onChange={(e) => set('po')(e.target.value)}
              />
            </div>

            <Fieldset legend="Include with the quote" layout="row">
              {['Certificates', 'Spec sheet', 'Sample 200 g'].map((o) => (
                <Checkbox
                  key={o} label={o} checked={v.include.includes(o)} disabled={submitting}
                  onChange={() => setV((s) => ({ ...s, include: s.include.includes(o) ? s.include.filter((x) => x !== o) : [...s.include, o] }))}
                />
              ))}
            </Fieldset>

            <Textarea
              label="Notes for the trade desk" rows={3} maxLength={400} value={v.notes} disabled={submitting}
              hint="Packing, labelling, documents your customs need."
              onChange={(e) => set('notes')(e.target.value)}
            />
          </div>
        </Card>

        <Card padding="lg" tone="sunken" style={{ position: 'sticky', top: 88 }}>
          <span style={{ font: 'var(--type-label)', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-meta)' }}>Your request</span>
          <div style={{ margin: '14px 0 16px', minHeight: 30 }}>
            {lot ? <LotCode code={lot.id} size="sm" /> : <span style={{ font: 'var(--type-body-sm)', color: 'var(--text-meta)' }}>No lot selected yet.</span>}
          </div>
          <DataList
            dense
            items={[
              { label: 'Grade', value: lot ? lot.grade : '—' },
              { label: 'Origin', value: lot ? lot.origin + ', Kampot' : '—' },
              { label: 'Quantity', value: kg ? kg.toLocaleString('en-GB').replace(/,/g, ' ') + ' kg' : '—', mono: true },
              { label: 'Indicative', value: value ? '$' + fmt(value) : '—', mono: true },
              { label: 'Incoterm', value: v.incoterm },
              { label: 'Shipment', value: v.shipment || '—', mono: true },
            ]}
          />
          <p style={{ margin: '14px 0 0', font: 'var(--type-meta)', color: 'var(--text-meta)' }}>
            Indicative only, at {lot ? '$' + lot.price.toFixed(2) : '$0.00'}/kg ex-register. The quote confirms price, lead time and documents. Valid 30 days.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 'var(--space-6)', paddingTop: 'var(--space-5)', borderTop: '1px solid var(--border-hairline)' }}>
            <Button type="submit" full size="lg" disabled={submitting}>{submitting ? 'Sending request…' : 'Send request'}</Button>
            <span aria-live="polite" style={{ font: 'var(--type-meta)', color: 'var(--text-meta)', textAlign: 'center' }}>
              {submitting ? 'Sending to the trade desk…' : 'Reply within one working day, ICT.'}
            </span>
          </div>
        </Card>
      </form>

      <ToastRegion>
        <Toast
          open={Boolean(sent)}
          message="Quote request sent"
          detail={sent ? sent.ref + ' · ' + sent.lot + ' · ' + sent.kg + ' kg. Nothing is reserved yet.' : undefined}
          onClose={() => setSent(null)}
        />
      </ToastRegion>
    </div>
  );
}
window.RequestQuote = RequestQuote;
