import { defineRouteConfig } from "@medusajs/admin-sdk"
import { EnvelopeSolid, EllipsisHorizontal, Trash, PencilSquare, ArrowPathMini, EyeMini } from "@medusajs/icons"
import { Container, Heading, Button, Text, Badge, toast, DropdownMenu, IconButton } from "@medusajs/ui"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { useNavigate } from "react-router-dom"
import { useState } from "react"
import { sdk } from "../../lib/sdk"
import { isDevOnlyFeaturesEnabled } from "../../lib/feature-flags"
import { useTranslation } from "react-i18next"

export const config = defineRouteConfig({
  label: "adminRoutes.emailTemplates.title",
  translationNs: "translation",
  icon: EnvelopeSolid,
  rank: 30,
})

type Template = {
  id: string
  key: string
  name: string
  category: string
  version: number
  is_active: boolean
  updated_at?: string
}

type TemplatesResponse = {
  templates: Template[]
  count: number
  is_production_mode?: boolean
}

const CATEGORIES = ["all", "user", "order", "payment", "admin"] as const
type Category = typeof CATEGORIES[number]

const categoryColors: Record<string, "blue" | "green" | "orange" | "red" | "grey"> = {
  user: "blue",
  order: "green",
  payment: "orange",
  admin: "red",
}

export default function EmailTemplatesPage() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const qc = useQueryClient()
  const [activeCategory, setActiveCategory] = useState<Category>("all")

  const { data, isLoading } = useQuery({
    queryKey: ["email-templates", activeCategory],
    queryFn: async () => {
      const params = activeCategory !== "all" ? `?category=${activeCategory}` : ""
      const r = await sdk.fetch(`/admin/email-templates${params}`)
      if (!r.ok) throw new Error(t("adminRoutes.emailTemplates.loadError"))
      return r.json() as Promise<TemplatesResponse>
    },
  })

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const r = await sdk.fetch(`/admin/email-templates/${id}`, { method: "DELETE" })
      if (!r.ok) throw new Error(await r.text())
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["email-templates"] })
      toast.success(t("adminRoutes.emailTemplates.toasts.deleted"))
    },
    onError: (e) => toast.error((e as Error).message),
  })

  const templates = data?.templates ?? []
  const isProductionMode = Boolean(data?.is_production_mode)

  return (
    <Container className="px-3 sm:px-4">
      {/* Header */}
      <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.emailTemplates.title")}</Heading>
          <Text size="small" className="text-ui-fg-subtle mt-1">
            {t("adminRoutes.emailTemplates.subtitle")}
          </Text>
        </div>
        <div className="flex gap-2">
          {isDevOnlyFeaturesEnabled && <Button size="small" variant="secondary" onClick={() => navigate("/email-layouts")}>
            {t("adminRoutes.emailTemplates.layouts")}
          </Button>}
          {isDevOnlyFeaturesEnabled && <Button size="small" variant="secondary" onClick={() => navigate("/email-logs")}>
            {t("adminRoutes.emailTemplates.emailLogs")}
          </Button>}
          {isDevOnlyFeaturesEnabled && <Button size="small" onClick={() => navigate("/email-templates/edit?new=1")} disabled={isProductionMode}>
            {t("adminRoutes.emailTemplates.newTemplate")}
          </Button>}
        </div>
      </div>

      {isProductionMode && (
        <div className="mb-4 rounded-lg border border-ui-border-base bg-ui-bg-subtle p-3">
          <Text size="small" className="text-ui-fg-subtle">
            {t("adminRoutes.emailTemplates.productionReadonly")}
          </Text>
        </div>
      )}

      {/* Category Tabs */}
      <div className="flex gap-2 mb-4 flex-wrap border-b pb-2">
        {CATEGORIES.map((cat) => (
          <button
            key={cat}
            onClick={() => setActiveCategory(cat)}
            className={`px-3 py-1.5 text-sm rounded-md capitalize transition-colors ${
              activeCategory === cat
                ? "bg-ui-button-inverted text-ui-fg-on-inverted"
                : "text-ui-fg-subtle hover:text-ui-fg-base hover:bg-ui-bg-base-hover"
            }`}
          >
            {t(`adminRoutes.emailTemplates.categories.${cat}`)}
          </button>
        ))}
      </div>

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

      {!isLoading && templates.length === 0 && (
        <div className="flex flex-col items-center py-16 gap-3">
          <EnvelopeSolid className="text-ui-fg-muted w-10 h-10" />
          <Text className="text-ui-fg-subtle">{t("adminRoutes.emailTemplates.empty")}</Text>
          {isDevOnlyFeaturesEnabled && <Button size="small" onClick={() => navigate("/email-templates/edit?new=1")} disabled={isProductionMode}>{t("adminRoutes.emailTemplates.newTemplate")}</Button>}
        </div>
      )}

      {!isLoading && templates.length > 0 && (
        <div className="divide-y">
          {templates.map((template) => (
            <div key={template.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">
                  <Text size="small" weight="plus" leading="compact">{template.name}</Text>
                  <Badge color={categoryColors[template.category] ?? "grey"} size="2xsmall">
                    {template.category}
                  </Badge>
                  <Badge color="grey" size="2xsmall">v{template.version}</Badge>
                  {!template.is_active && <Badge color="red" size="2xsmall">Inactive</Badge>}
                </div>
                <Text size="small" className="text-ui-fg-subtle mt-0.5">Key: {template.key}</Text>
              </div>
              <div className="flex gap-2 items-center">
                <Button
                  size="small"
                  variant="secondary"
                  onClick={() => navigate(`/email-templates/edit?id=${template.id}&mode=preview`)}
                >
                  <EyeMini />
                  {t("adminRoutes.emailTemplates.preview")}
                </Button>
                {isDevOnlyFeaturesEnabled && <Button
                  size="small"
                  variant="secondary"
                  onClick={() => navigate(`/email-templates/history?id=${template.id}`)}
                >
                  <ArrowPathMini />
                  {t("adminRoutes.emailTemplates.history")}
                </Button>}
                <DropdownMenu>
                  <DropdownMenu.Trigger asChild>
                    <IconButton size="small" variant="transparent">
                      <EllipsisHorizontal />
                    </IconButton>
                  </DropdownMenu.Trigger>
                  <DropdownMenu.Content>
                    <DropdownMenu.Item
                      className="gap-x-2"
                      onClick={() => navigate(`/email-templates/edit?id=${template.id}`)}
                    >
                      <PencilSquare className="text-ui-fg-subtle" />
                      {isProductionMode ? t("adminRoutes.common.view") : t("adminRoutes.common.edit")}
                    </DropdownMenu.Item>
                    {isDevOnlyFeaturesEnabled && !isProductionMode && (
                      <>
                        <DropdownMenu.Separator />
                        <DropdownMenu.Item
                          className="gap-x-2 text-ui-fg-error"
                          onClick={() => deleteMutation.mutate(template.id)}
                        >
                          <Trash className="text-ui-fg-error" />
                          {t("adminRoutes.common.delete")}
                        </DropdownMenu.Item>
                      </>
                    )}
                  </DropdownMenu.Content>
                </DropdownMenu>
              </div>
            </div>
          ))}
        </div>
      )}
    </Container>
  )
}
