// ───────────────────────────────────────────────
// Emails Page (/(dashboard)/emails)
// ───────────────────────────────────────────────
// Route: /emails
// Purpose: Admin-only email log viewer. Lists
//   all sent emails with subject, recipient,
//   and timestamp. Extracts "With:" metadata
//   from the email body text.
// Layout: Simple list with header + description.
//   Access restricted to admin / super_admin.
// ───────────────────────────────────────────────

"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { useUser } from "@/providers/user-provider"
import { Mail, Clock } from "lucide-react"

/**
 * EmailsPage
 * ──────────
 * Dispatched-email log. Only available to admin
 * and super_admin roles. Redirects unauthorized
 * users back to /dashboard or /login.
 *
 * @returns Email list UI or null if unauthorized.
 */
export default function EmailsPage() {
  const router = useRouter()
  const { user } = useUser()
  const [emails, setEmails] = useState<any[]>([])

  // ── Auth guard + fetch emails ──
  useEffect(() => {
    if (!user) { router.push("/login"); return }
    if (user.role !== "admin" && user.role !== "super_admin") { router.push("/dashboard"); return }
    fetch("/api/emails").then((r) => r.ok ? r.json() : { emails: [] }).then((d) => setEmails(d.emails || []))
  }, [user, router])

  if (!user || (user.role !== "admin" && user.role !== "super_admin")) return null

  return (
    <div className="p-6">
      <h1 className="text-xl font-bold mb-4">Email Log</h1>
      <p className="text-sm text-muted-foreground mb-6">
        Emails are stored locally. To actually deliver them, add <code className="bg-muted px-1 rounded">EMAIL_API_KEY</code> to your .env.
      </p>

      {/* ── Email list or empty state ── */}
      {emails.length === 0 ? (
        <p className="text-sm text-muted-foreground">No emails sent yet.</p>
      ) : (
        <div className="space-y-2">
          {emails.map((e: any) => {
            // Extract "With:" metadata from email body for display
            const withMatch = e.bodyText?.match(/With:\s*(.+)/)
            const withName = withMatch ? withMatch[1].trim() : null
            return (
              <div key={e.id} className="flex items-center gap-3 p-3 rounded-lg border bg-card">
                <Mail className="h-4 w-4 text-muted-foreground shrink-0" />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">{e.subject}</p>
                  <p className="text-xs text-muted-foreground">To: {e.recipient}</p>
                  {withName && <p className="text-xs text-muted-foreground/70 mt-0.5">With: {withName}</p>}
                </div>
                <div className="flex items-center gap-1 text-xs text-muted-foreground shrink-0">
                  <Clock className="h-3 w-3" />
                  {new Date(e.createdAt).toLocaleString()}
                </div>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}
