// screen-receipt.jsx — Foto Struk → AI → Auto-fill Transaksi
// Uses Claude claude-sonnet-4-20250514 Vision via Anthropic API proxy

const ANTHROPIC_KEY = window.INDIECASH_CONFIG?.anthropicKey || '';

function ScreenReceipt({ theme, accent, scenario, onOpenSheet, onTransactionAdded }) {
  const T = theme;

  const [step, setStep] = React.useState('idle'); // idle | processing | result | error
  const [previewUrl, setPreviewUrl] = React.useState(null);
  const [result, setResult] = React.useState(null);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [history, setHistory] = React.useState([]);
  const fileRef = React.useRef(null);
  const cameraRef = React.useRef(null);

  const CATEGORIES_LIST = Object.values(CATEGORIES).filter(c => c.kind === 'expense');

  async function processImage(file) {
    if (!file) return;

    // Preview
    const url = URL.createObjectURL(file);
    setPreviewUrl(url);
    setStep('processing');
    setResult(null);

    try {
      // Convert to base64
      const base64 = await new Promise((res, rej) => {
        const reader = new FileReader();
        reader.onload = () => res(reader.result.split(',')[1]);
        reader.onerror = rej;
        reader.readAsDataURL(file);
      });

      const mediaType = file.type || 'image/jpeg';

      const prompt = `Kamu adalah asisten pencatat keuangan Indonesia. Analisis struk/nota/bukti pembayaran ini.

Ekstrak informasi berikut dan kembalikan HANYA JSON valid (tanpa markdown, tanpa penjelasan):
{
  "merchant": "nama toko/merchant",
  "total": 150000,
  "tanggal": "2024-05-26",
  "items": [
    {"nama": "nama item", "harga": 50000, "qty": 1}
  ],
  "kategori": "makan|belanja|transport|tagihan|hiburan|kesehatan|pendidikan|rumah|lainnya_ex",
  "metode_bayar": "cash|debit|kredit|qris|transfer",
  "catatan": "ringkasan singkat 1 kalimat dalam bahasa Indonesia",
  "confidence": 0.95
}

Aturan:
- total harus angka integer (dalam rupiah, tanpa titik/koma)
- tanggal format YYYY-MM-DD, jika tidak ada pakai hari ini
- kategori pilih yang paling sesuai dari daftar yang ada
- confidence antara 0-1 (seberapa yakin kamu dengan hasilnya)
- Jika struk tidak terbaca/bukan struk, kembalikan {"error": "Bukan struk yang valid"}`;

      // Call backend proxy — key stays on server, never exposed to browser
      const response = await fetch('/api/receipt', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ image: base64, media_type: mediaType }),
      });

      if (!response.ok) {
        const err = await response.json().catch(() => ({}));
        throw new Error(err.error || `Server error ${response.status}`);
      }

      const proxyResult = await response.json();
      if (!proxyResult.ok) throw new Error(proxyResult.error || 'Gagal memproses');

      // proxyResult.data is already parsed JSON from server
      const parsed = proxyResult.data;
      if (parsed.error) throw new Error(parsed.error);

      setResult(parsed);
      setStep('result');
      return; // skip the rest of the try block



    } catch (err) {
      setErrorMsg(err.message || 'Gagal memproses gambar');
      setStep('error');
    }
  }

  function handleFile(e) {
    const file = e.target.files?.[0];
    if (file) processImage(file);
  }

  function confirmAndSave() {
    if (!result) return;
    // Add to history
    const entry = {
      id: Date.now(),
      merchant: result.merchant,
      total: result.total,
      kategori: result.kategori,
      tanggal: result.tanggal,
      catatan: result.catatan,
      previewUrl,
      savedAt: new Date().toISOString(),
    };
    setHistory(h => [entry, ...h].slice(0, 10));

    // Trigger add transaction sheet with pre-filled data
    if (onTransactionAdded) onTransactionAdded(entry);

    setStep('saved');
    setTimeout(() => {
      setStep('idle');
      setPreviewUrl(null);
      setResult(null);
    }, 2000);
  }

  function retry() {
    setStep('idle');
    setPreviewUrl(null);
    setResult(null);
    setErrorMsg('');
  }

  const catInfo = result ? (CATEGORIES[result.kategori] || CATEGORIES.lainnya_ex) : null;

  return (
    <div style={{ background: T.bg, minHeight: '100%', paddingBottom: 100 }}>

      {/* Header */}
      <div style={{
        padding: '56px 20px 20px',
        background: `linear-gradient(160deg, ${accent[50]}, ${T.bg} 70%)`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: `linear-gradient(135deg, ${accent.grad[0]}, ${accent.grad[1]})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="scan" size={18} color="#fff" stroke={2} />
          </div>
          <div>
            <div style={{ fontSize: 20, fontWeight: 800, color: T.fg1, letterSpacing: '-0.03em' }}>
              Scan Struk
            </div>
            <div style={{ fontSize: 11, color: T.fg3, fontWeight: 500 }}>
              Foto struk → AI proses → Auto catat
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: '0 16px' }}>

        {/* ── IDLE: Upload area ── */}
        {(step === 'idle' || step === 'saved') && (
          <>
            {step === 'saved' && (
              <div style={{
                background: accent.tint, border: `1px solid ${accent[200]}`,
                borderRadius: 16, padding: 14, marginBottom: 16,
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <Icon name="check-circle" size={20} color={accent[500]} stroke={2} />
                <span style={{ fontSize: 14, fontWeight: 600, color: accent[700] }}>
                  Transaksi berhasil disimpan!
                </span>
              </div>
            )}

            {/* Camera / Upload buttons */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}>
              <button
                onClick={() => cameraRef.current?.click()}
                style={{
                  border: `2px dashed ${accent[300]}`, borderRadius: 20,
                  background: accent.tint, padding: '24px 16px',
                  cursor: 'pointer', display: 'flex', flexDirection: 'column',
                  alignItems: 'center', gap: 10,
                }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 14,
                  background: `linear-gradient(135deg, ${accent.grad[0]}, ${accent.grad[1]})`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name="camera" size={22} color="#fff" stroke={2} />
                </div>
                <div style={{ fontSize: 13, fontWeight: 700, color: accent[700] }}>Ambil Foto</div>
                <div style={{ fontSize: 11, color: T.fg3 }}>Kamera langsung</div>
              </button>

              <button
                onClick={() => fileRef.current?.click()}
                style={{
                  border: `2px dashed ${T.border}`, borderRadius: 20,
                  background: T.surface, padding: '24px 16px',
                  cursor: 'pointer', display: 'flex', flexDirection: 'column',
                  alignItems: 'center', gap: 10,
                }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 14,
                  background: T.surfaceAlt,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name="image" size={22} color={T.fg3} stroke={1.8} />
                </div>
                <div style={{ fontSize: 13, fontWeight: 700, color: T.fg1 }}>Pilih Foto</div>
                <div style={{ fontSize: 11, color: T.fg3 }}>Dari galeri</div>
              </button>
            </div>

            <input ref={cameraRef} type="file" accept="image/*" capture="environment"
              onChange={handleFile} style={{ display: 'none' }} />
            <input ref={fileRef}   type="file" accept="image/*"
              onChange={handleFile} style={{ display: 'none' }} />

            {/* Tips */}
            <div style={{
              background: T.surface, borderRadius: 16, padding: 14,
              border: `1px solid ${T.border}`, marginBottom: 20,
            }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: T.fg2, marginBottom: 8 }}>
                💡 Tips foto yang bagus
              </div>
              {[
                'Pastikan struk tidak terlipat atau kusut',
                'Foto dalam cahaya yang cukup',
                'Seluruh teks struk terlihat jelas',
                'Bisa juga foto QRIS, tagihan, atau nota tangan',
              ].map((tip, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 4 }}>
                  <span style={{ color: accent[400], fontSize: 11 }}>✓</span>
                  <span style={{ fontSize: 12, color: T.fg3 }}>{tip}</span>
                </div>
              ))}
            </div>

            {/* History */}
            {history.length > 0 && (
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: T.fg1, marginBottom: 10 }}>
                  Riwayat Scan
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {history.map(h => (
                    <div key={h.id} style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      background: T.surface, borderRadius: 14, padding: 12,
                      border: `1px solid ${T.border}`,
                    }}>
                      {h.previewUrl && (
                        <img src={h.previewUrl} alt=""
                          style={{ width: 40, height: 40, borderRadius: 8, objectFit: 'cover' }} />
                      )}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: T.fg1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {h.merchant || 'Merchant'}
                        </div>
                        <div style={{ fontSize: 11, color: T.fg3 }}>{h.catatan}</div>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: T.fg1, whiteSpace: 'nowrap' }}>
                        {fmtRp(h.total)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}

        {/* ── PROCESSING ── */}
        {step === 'processing' && (
          <div style={{ textAlign: 'center', padding: '20px 0 40px' }}>
            {previewUrl && (
              <div style={{ position: 'relative', marginBottom: 24 }}>
                <img src={previewUrl} alt="struk"
                  style={{ width: '100%', maxHeight: 280, objectFit: 'contain', borderRadius: 16 }} />
                <div style={{
                  position: 'absolute', inset: 0, borderRadius: 16,
                  background: 'rgba(0,0,0,0.4)',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12,
                }}>
                  <div style={{
                    width: 48, height: 48, borderRadius: '50%',
                    border: `3px solid ${accent[300]}`,
                    borderTopColor: accent[500],
                    animation: 'spin 0.8s linear infinite',
                  }} />
                  <div style={{ color: '#fff', fontSize: 14, fontWeight: 600 }}>AI sedang membaca struk...</div>
                </div>
              </div>
            )}
            <div style={{ fontSize: 13, color: T.fg3 }}>Menganalisis dengan Claude AI · Harap tunggu</div>
          </div>
        )}

        {/* ── ERROR ── */}
        {step === 'error' && (
          <div style={{ marginBottom: 20 }}>
            {previewUrl && (
              <img src={previewUrl} alt="" style={{ width: '100%', maxHeight: 200, objectFit: 'contain', borderRadius: 16, marginBottom: 16 }} />
            )}
            <div style={{
              background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.25)',
              borderRadius: 16, padding: 16, marginBottom: 16,
              display: 'flex', gap: 10, alignItems: 'flex-start',
            }}>
              <Icon name="alert-circle" size={18} color="#ef4444" stroke={2} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#ef4444', marginBottom: 4 }}>Gagal membaca struk</div>
                <div style={{ fontSize: 12, color: T.fg2 }}>{errorMsg}</div>
              </div>
            </div>
            <button onClick={retry} style={{
              width: '100%', height: 48, borderRadius: 14,
              background: `linear-gradient(135deg, ${accent.grad[0]}, ${accent.grad[1]})`,
              color: '#fff', fontSize: 14, fontWeight: 700, border: 0, cursor: 'pointer',
            }}>
              Coba Lagi
            </button>
          </div>
        )}

        {/* ── RESULT ── */}
        {step === 'result' && result && (
          <div>
            {/* Preview + confidence */}
            <div style={{ position: 'relative', marginBottom: 16 }}>
              <img src={previewUrl} alt=""
                style={{ width: '100%', maxHeight: 200, objectFit: 'contain', borderRadius: 16 }} />
              <div style={{
                position: 'absolute', top: 10, right: 10,
                background: result.confidence >= 0.85 ? accent[500] : '#f59e0b',
                color: '#fff', borderRadius: 99, padding: '3px 10px',
                fontSize: 11, fontWeight: 700,
              }}>
                {Math.round((result.confidence || 0) * 100)}% akurat
              </div>
            </div>

            {/* Parsed result card */}
            <div style={{
              background: T.surface, borderRadius: 20, padding: 16, marginBottom: 12,
              border: `1px solid ${T.border}`,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: (catInfo?.color || accent[500]) + '18',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name={catInfo?.icon || 'receipt'} size={18} color={catInfo?.color || accent[500]} stroke={1.8} />
                </div>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: T.fg1 }}>{result.merchant || '—'}</div>
                  <div style={{ fontSize: 12, color: T.fg3 }}>{catInfo?.label} · {result.metode_bayar?.toUpperCase() || 'CASH'}</div>
                </div>
                <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
                  <div style={{ fontSize: 22, fontWeight: 800, color: T.fg1 }}>{fmtRp(result.total)}</div>
                  <div style={{ fontSize: 11, color: T.fg3 }}>{result.tanggal}</div>
                </div>
              </div>

              {/* Items */}
              {result.items?.length > 0 && (
                <div style={{ marginBottom: 12 }}>
                  <div style={{ fontSize: 11, color: T.fg4, fontWeight: 600, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                    Detail item
                  </div>
                  {result.items.map((item, i) => (
                    <div key={i} style={{
                      display: 'flex', justifyContent: 'space-between',
                      padding: '5px 0', borderBottom: i < result.items.length - 1 ? `1px solid ${T.border}` : 'none',
                    }}>
                      <span style={{ fontSize: 12, color: T.fg2 }}>
                        {item.qty > 1 ? `${item.qty}× ` : ''}{item.nama}
                      </span>
                      <span style={{ fontSize: 12, fontWeight: 600, color: T.fg1 }}>{fmtRp(item.harga * (item.qty || 1))}</span>
                    </div>
                  ))}
                </div>
              )}

              {result.catatan && (
                <div style={{
                  background: T.bg, borderRadius: 10, padding: '8px 12px',
                  fontSize: 12, color: T.fg2, fontStyle: 'italic',
                }}>
                  "{result.catatan}"
                </div>
              )}
            </div>

            {/* Action buttons */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 10 }}>
              <button onClick={retry} style={{
                height: 50, borderRadius: 14, border: `1px solid ${T.border}`,
                background: 'transparent', color: T.fg2, fontSize: 14, fontWeight: 600, cursor: 'pointer',
              }}>
                Ulangi
              </button>
              <button onClick={confirmAndSave} style={{
                height: 50, borderRadius: 14, border: 0, cursor: 'pointer',
                background: `linear-gradient(135deg, ${accent.grad[0]}, ${accent.grad[1]})`,
                color: '#fff', fontSize: 14, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                boxShadow: `0 6px 20px ${accent[500]}44`,
              }}>
                <Icon name="check" size={17} color="#fff" stroke={2.5} />
                Simpan Transaksi
              </button>
            </div>
          </div>
        )}

      </div>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

// Small helper (re-use if already defined)
if (typeof fmtRp === 'undefined') {
  window.fmtRp = (v) => {
    if (v >= 1e9)  return `Rp ${(v/1e9).toFixed(1)}M`;
    if (v >= 1e6)  return `Rp ${(v/1e6).toFixed(1)}jt`;
    if (v >= 1e3)  return `Rp ${(v/1e3).toFixed(0)}rb`;
    return `Rp ${Math.round(v)}`;
  };
}

Object.assign(window, { ScreenReceipt });
