import type { SetupStatus } from '@/lib/setup'

interface SetupRequiredPageProps {
  status: Extract<SetupStatus, { ready: false }>
}

function renderReason(status: SetupStatus & { ready: false }) {
  if (status.reason === 'missing_env') {
    return {
      title: 'Database env is incomplete',
      detail: `Missing environment variables: ${status.missing.join(', ')}`,
    }
  }

  if (status.reason === 'db_unreachable') {
    return {
      title: 'Database connection failed',
      detail: status.details,
    }
  }

  if (status.reason === 'schema_missing') {
    return {
      title: 'Database schema is incomplete',
      detail: `Missing tables: ${status.missingTables.join(', ')}`,
    }
  }

  return {
    title: 'Initial admin bootstrap required',
    detail: 'The database is reachable and the schema exists, but there are no users yet.',
  }
}

export default function SetupRequiredPage({ status }: SetupRequiredPageProps) {
  const reason = renderReason(status)

  return (
    <div className="min-h-screen bg-[#0b1326] flex items-center justify-center p-4">
      <div className="w-full max-w-2xl bg-[#131b2e] rounded-2xl p-8 border border-[#574143]/15 shadow-2xl">
        <div className="flex items-center gap-3 mb-6">
          <div className="w-12 h-12 rounded-2xl bg-[#ffb2b9]/10 text-[#ffb2b9] flex items-center justify-center">
            <span className="material-symbols-outlined">dns</span>
          </div>
          <div>
            <h1 className="text-2xl font-extrabold text-[#dae2fd]" style={{ fontFamily: 'Manrope, sans-serif' }}>
              Database setup required
            </h1>
            <p className="text-sm text-slate-400">This build now expects a self-hosted PostgreSQL database and server-side sessions.</p>
          </div>
        </div>

        <div className="space-y-4 text-sm text-slate-300">
          <div className="rounded-xl bg-[#2a1520] border border-[#fb7185]/20 p-4">
            <p className="text-xs font-black uppercase tracking-widest text-[#ffb2b9]">{reason.title}</p>
            <p className="mt-2 text-sm text-slate-200">{reason.detail}</p>
          </div>

          <p>Add these environment variables before running the app locally or on your Bluehost Node runtime:</p>
          <div className="rounded-xl bg-[#0b1326] border border-[#574143]/20 p-4 font-mono text-[13px] text-slate-300 space-y-2">
            <p>DB_HOST=your-postgres-host</p>
            <p>DB_PORT=5432</p>
            <p>DB_NAME=...</p>
            <p>DB_USER=...</p>
            <p>DB_PASSWORD=...</p>
            <p>DB_SSL=false</p>
            <p>or DATABASE_URL=postgres://...</p>
          </div>
          <p className="text-slate-400">
            Apply the SQL in <span className="text-slate-200">app/postgres/schema.sql</span>, then create at least one user record before signing in.
          </p>
        </div>
      </div>
    </div>
  )
}
