import { defineRouteConfig } from "@medusajs/admin-sdk"
import { ReceiptPercent } from "@medusajs/icons"
import { Container, Heading, Button, Text, Badge, FocusModal } from "@medusajs/ui"
import { useQuery } from "@tanstack/react-query"
import { useState } from "react"
import { sdk } from "../../lib/sdk"
import { isDevOnlyFeaturesEnabled } from "../../lib/feature-flags"
import { useTranslation } from "react-i18next"

export const config = isDevOnlyFeaturesEnabled ? defineRouteConfig({
  label: "adminRoutes.emailLogs.title",
  translationNs: "translation",
  icon: ReceiptPercent,
  rank: 32,
}) : undefined


type EmailLog = {
  id: string
  to: string
  subject: string
  template_key: string | null
  status: "sent" | "failed"
  error: string | null
  rendered_html: string | null
  sent_at: string
}

export default function EmailLogsPage() {
  const { t } = useTranslation()
  // Hide entire route in production
  if (!isDevOnlyFeaturesEnabled) {
    return null
  }

  const [selectedLog, setSelectedLog] = useState<EmailLog | null>(null)
  const [statusFilter, setStatusFilter] = useState<"all" | "sent" | "failed">("all")

  const { data, isLoading } = useQuery({
    queryKey: ["email-logs", statusFilter],
    queryFn: async () => {
      const params = statusFilter !== "all" ? `?status=${statusFilter}` : ""
      const r = await sdk.fetch(`/admin/email-logs${params}`)
      if (!r.ok) throw new Error(t("adminRoutes.emailLogs.loadError"))
      return r.json() as Promise<{ logs: EmailLog[]; count: number }>
    },
  })

  const logs = data?.logs ?? []

  return (
    <Container className="px-3 sm:px-4">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-4 sm:py-6 gap-4">
        <div>
          <Heading level="h1">{t("adminRoutes.emailLogs.title")}</Heading>
          <Text size="small" className="text-ui-fg-subtle mt-1">
            {t("adminRoutes.emailLogs.subtitle")}
          </Text>
        </div>
        <Text size="small" className="text-ui-fg-subtle">
          {t("adminRoutes.emailLogs.total", { count: data?.count ?? 0 })}
        </Text>
      </div>

      {/* Filter tabs */}
      <div className="flex gap-2 mb-4 border-b pb-2">
        {(["all", "sent", "failed"] as const).map((s) => (
          <button
            key={s}
            onClick={() => setStatusFilter(s)}
            className={`px-3 py-1.5 text-sm rounded-md capitalize transition-colors ${
              statusFilter === s
                ? "bg-ui-button-inverted text-ui-fg-on-inverted"
                : "text-ui-fg-subtle hover:text-ui-fg-base hover:bg-ui-bg-base-hover"
            }`}
          >
            {s}
          </button>
        ))}
      </div>

      {isLoading && <p className="text-ui-fg-subtle text-center py-12">{t("adminRoutes.common.loading")}</p>}

      {!isLoading && logs.length === 0 && (
        <Text className="text-ui-fg-subtle py-8 text-center">{t("adminRoutes.emailLogs.empty")}</Text>
      )}

      {!isLoading && logs.length > 0 && (
        <div className="divide-y">
          {logs.map((log) => (
            <div key={log.id} className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-3 gap-2">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <Badge color={log.status === "sent" ? "green" : "red"} size="2xsmall">
                    {log.status === "sent" ? t("adminRoutes.emailLogs.sent") : t("adminRoutes.emailLogs.failed")}
                  </Badge>
                  <Text size="small" weight="plus" leading="compact" className="truncate max-w-xs">{log.subject}</Text>
                  {log.template_key && <Badge color="grey" size="2xsmall">{log.template_key}</Badge>}
                </div>
                <Text size="small" className="text-ui-fg-subtle mt-0.5">
                  {t("adminRoutes.emailLogs.to")} {log.to} · {new Date(log.sent_at).toLocaleString()}
                </Text>
                {log.error && (
                  <Text size="small" className="text-ui-fg-error mt-0.5">{t("adminRoutes.emailLogs.error")} {log.error}</Text>
                )}
              </div>
              {log.rendered_html && (
                <Button size="small" variant="secondary" onClick={() => setSelectedLog(log)}>
                  {t("adminRoutes.emailLogs.viewEmail")}
                </Button>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Email Preview Modal */}
      <FocusModal open={!!selectedLog} onOpenChange={(open) => !open && setSelectedLog(null)}>
        <FocusModal.Content>
          <div className="flex h-full flex-col overflow-hidden">
            <FocusModal.Header>
              <div className="flex items-center justify-between gap-x-2">
                <Text weight="plus">{t("adminRoutes.emailLogs.previewTitle")} — {selectedLog?.subject}</Text>
                <FocusModal.Close asChild>
                  <Button size="small" variant="secondary">{t("adminRoutes.common.close")}</Button>
                </FocusModal.Close>
              </div>
            </FocusModal.Header>
            <FocusModal.Body className="flex-1 overflow-auto p-4">
              <div className="mb-4 flex flex-col gap-1 text-sm">
                <Text size="small"><strong>{t("adminRoutes.emailLogs.toLabel")}</strong> {selectedLog?.to}</Text>
                <Text size="small"><strong>{t("adminRoutes.emailLogs.subjectLabel")}</strong> {selectedLog?.subject}</Text>
                <Text size="small"><strong>{t("adminRoutes.emailLogs.templateLabel")}</strong> {selectedLog?.template_key || "—"}</Text>
                <Text size="small"><strong>{t("adminRoutes.emailLogs.sentAtLabel")}</strong> {selectedLog && new Date(selectedLog.sent_at).toLocaleString()}</Text>
              </div>
              <div className="mb-3 rounded-lg border border-ui-border-base bg-ui-bg-subtle p-3">
                <Text size="small" className="text-ui-fg-subtle">
                  {t("adminRoutes.emailLogs.previewReadonlyHint")}
                </Text>
              </div>
              <div className="border rounded-lg overflow-hidden">
                {selectedLog?.rendered_html && (
                  <iframe
                    srcDoc={selectedLog.rendered_html}
                    className="w-full"
                    style={{ height: "1200px", border: "none", pointerEvents: "none" }}
                    title={t("adminRoutes.emailLogs.previewTitle")}
                    sandbox="allow-same-origin"
                    tabIndex={-1}
                  />
                )}
              </div>
            </FocusModal.Body>
          </div>
        </FocusModal.Content>
      </FocusModal>
    </Container>
  )
}
