import { defineRouteConfig } from "@medusajs/admin-sdk"
import { User, Eye, UsersSolid } from "@medusajs/icons"
import { Badge, Button, Container, Heading, Text, toast } from "@medusajs/ui"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { useNavigate } from "react-router-dom"
import { sdk } from "../../lib/sdk"
import { isDevOnlyFeaturesEnabled } from "../../lib/feature-flags"
import { useTranslation } from "react-i18next"

type RegisteredUser = {
  id: string
  email: string | null
  full_name: string | null
  first_name: string | null
  last_name: string | null
  phone: string | null
  company_name: string | null
  country_code: string | null
  account_status: string | null
  has_account: boolean
  created_at: string | null
}

const ACCOUNT_STATUSES = {
  active: "active",
  blocked: "blocked",
  pending_review: "pending_review",
  rejected: "rejected",
} as const

type AccountStatus = (typeof ACCOUNT_STATUSES)[keyof typeof ACCOUNT_STATUSES]

export const config = isDevOnlyFeaturesEnabled ? defineRouteConfig({
  label: "adminRoutes.registeredUsers.title",
  translationNs: "translation",
  icon: UsersSolid,
}) : undefined

function formatDate(iso: string | null) {
  if (!iso) {
    return "-"
  }

  try {
    return new Date(iso).toLocaleString()
  } catch {
    return iso
  }
}

function formatStatus(status: string | null) {
  if (!status) {
    return "Active"
  }

  return status
    .split(/[_\s-]+/)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ")
}

function getBadgeColor(status: string | null): "green" | "orange" | "red" {
  if (status === ACCOUNT_STATUSES.rejected || status === ACCOUNT_STATUSES.blocked) {
    return "red"
  }

  if (status === ACCOUNT_STATUSES.pending_review) {
    return "orange"
  }

  return "green"
}

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

  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const updateStatus = useMutation({
    mutationFn: async (payload: { customerId: string; status: AccountStatus }) => {
      const response = await sdk.fetch(
        `/admin/customers/${payload.customerId}/account-status`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ status: payload.status }),
        }
      )

      const text = await response.text()

      if (!response.ok) {
        let message = text || t("adminRoutes.registeredUsers.updateStatusError")

        try {
          const json = JSON.parse(text)
          if (json?.message) {
            message = json.message
          }
        } catch {
          // Keep text fallback
        }

        throw new Error(message)
      }

      return text ? JSON.parse(text) : {}
    },
    onSuccess: (_data, variables) => {
      toast.success(t("adminRoutes.registeredUsers.statusUpdated", { status: formatStatus(variables.status) }))
      queryClient.invalidateQueries({
        queryKey: ["admin", "customers", "registered"],
      })
    },
    onError: (error: Error) => {
      toast.error(error.message || t("adminRoutes.registeredUsers.updateStatusError"))
    },
  })

  const { data, isLoading, isError, error } = useQuery({
    queryKey: ["admin", "customers", "registered"],
    queryFn: async () => {
      const response = await sdk.fetch("/admin/customers/registered")

      if (!response.ok) {
        const text = await response.text()
        throw new Error(
          response.status === 401
            ? t("adminRoutes.common.loginRequired")
            : text || t("adminRoutes.registeredUsers.loadError")
        )
      }

      const json = await response.json()
      const list = json?.customers

      return {
        customers: Array.isArray(list) ? (list as RegisteredUser[]) : [],
      }
    },
  })

  const customers = data?.customers ?? []

  return (
    <Container className="px-3 sm:px-4">
      <div className="py-4 sm:py-6">
        <Heading level="h1" className="text-xl sm:text-2xl">
          {t("adminRoutes.registeredUsers.title")}
        </Heading>
        <Text size="small" className="mt-1 text-ui-fg-subtle">
          {t("adminRoutes.registeredUsers.subtitle")}
        </Text>
      </div>

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

      {isError && (
        <Text className="py-4 text-red-600">
          {(error as Error)?.message ?? t("adminRoutes.registeredUsers.loadError")}
        </Text>
      )}

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

      {!isLoading && !isError && customers.length > 0 && (
        <div className="overflow-x-auto rounded-lg border border-ui-border-base">
          <table className="min-w-[1180px] w-full text-left text-sm">
            <thead>
              <tr className="border-b border-ui-border-base bg-ui-bg-subtle">
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.user")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.email")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.phone")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.company")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.country")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.status")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.registered")}</th>
                <th className="p-3 font-medium">{t("adminRoutes.registeredUsers.columns.actions")}</th>
              </tr>
            </thead>
            <tbody>
              {customers.map((customer) => (
                <tr
                  key={customer.id}
                  className="border-b border-ui-border-base last:border-0"
                >
                  <td className="p-3">
                    <div className="flex items-center gap-2">
                      <span className="flex size-8 items-center justify-center rounded-full bg-ui-bg-base shadow-elevation-card-rest">
                        <User />
                      </span>
                      <div className="min-w-0">
                        <Text size="small" weight="plus">
                          {customer.full_name ?? t("adminRoutes.registeredUsers.unnamedUser")}
                        </Text>
                        <Text size="small" className="text-ui-fg-subtle">
                          {customer.id}
                        </Text>
                      </div>
                    </div>
                  </td>
                  <td className="p-3">{customer.email ?? "-"}</td>
                  <td className="p-3">{customer.phone ?? "-"}</td>
                  <td className="p-3">{customer.company_name ?? "-"}</td>
                  <td className="p-3">{customer.country_code ?? "-"}</td>
                  <td className="p-3">
                    <Badge color={getBadgeColor(customer.account_status)}>
                      {formatStatus(customer.account_status)}
                    </Badge>
                  </td>
                  <td className="p-3 text-ui-fg-subtle">
                    {formatDate(customer.created_at)}
                  </td>
                  <td className="p-3">
                    <div className="flex flex-wrap gap-2">
                      <Button
                        size="small"
                        variant="secondary"
                        onClick={() => navigate(`/customers/${customer.id}`)}
                      >
                        <Eye />
                        {t("adminRoutes.registeredUsers.view")}
                      </Button>
                      <Button
                        size="small"
                        variant="secondary"
                        disabled={
                          updateStatus.isPending ||
                          customer.account_status === ACCOUNT_STATUSES.active
                        }
                        onClick={() => {
                          updateStatus.mutate({
                            customerId: customer.id,
                            status: ACCOUNT_STATUSES.active,
                          })
                        }}
                      >
                        {t("adminRoutes.registeredUsers.unblock")}
                      </Button>
                      <Button
                        size="small"
                        variant="secondary"
                        disabled={
                          updateStatus.isPending ||
                          customer.account_status === ACCOUNT_STATUSES.blocked
                        }
                        onClick={() => {
                          updateStatus.mutate({
                            customerId: customer.id,
                            status: ACCOUNT_STATUSES.blocked,
                          })
                        }}
                      >
                        {t("adminRoutes.registeredUsers.block")}
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Container>
  )
}
