import Link from 'next/link'
import { redirect } from 'next/navigation'
import { isAuthenticated } from '@/lib/auth'
import { readJsonFile } from '@/lib/storage'

export default async function TestPage({ searchParams }: { searchParams: Promise<{ status?: string }> }) {
  if (!await isAuthenticated()) {
    redirect('/login')
  }

  const logs = readJsonFile<unknown[]>('webhook-logs.json', [])
  const state = readJsonFile<Record<string, unknown>>('flow-state.json', {})
  const params = await searchParams

  return (
    <div className="wrap">
      <div className="top">
        <div>
          <h1>Halaman Test</h1>
          <p>Nomor testing aktif: <strong>{process.env.WA_TEST_NUMBER}</strong></p>
          <p>Flow: kirim <strong>daftar</strong>, lalu kirim nama.</p>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <Link className="btn" href="/settings">Settings</Link>
          <Link className="btn" href="/webhook-logs">Webhook Logs</Link>
          <form method="POST" action="/api/logout"><button className="btn" type="submit">Logout</button></form>
        </div>
      </div>

      <div className="card">
        {params.status ? <div className="flash">{params.status}</div> : null}
        <form method="POST" action="/api/test/send">
          <label>Kirim pesan ke nomor testing</label>
          <textarea className="textarea" name="message" placeholder="Contoh: daftar" required />
          <div style={{ marginTop: 12 }}><button className="btn" type="submit">Kirim Pesan</button></div>
        </form>
      </div>

      <div className="card">
        <h2>State Flow</h2>
        <pre>{JSON.stringify(state, null, 2)}</pre>
      </div>

      <div className="card">
        <h2>Ringkasan Log</h2>
        <pre>{JSON.stringify(logs.slice(-10).reverse(), null, 2)}</pre>
      </div>
    </div>
  )
}
