import { useCallback, useEffect, useState } from "react"
import { RefreshCw, RotateCcw } from "lucide-react"

import { useArcadiaClient } from "@crema/arcadia-core-client"
import { useToast } from "@crema/notification-ui"
import { BadgeCell } from "@crema/table-ui"
import { EmptyState } from "@crema/feedback-ui"

import type { TenantTabProps } from "~/routes/tenants.$id"
import { DataState } from "~/components/data-state"
import { errorMessage } from "~/lib/errors"
import { Button } from "~/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card"
import { Switch } from "~/components/ui/switch"
import {
  clearFeatureFlag,
  listFeatureFlags,
  setFeatureFlag,
  type TenantFeatureFlag,
} from "~/lib/arcadia/tenants"

/**
 * Per-tenant feature-flag overrides. The list is every platform-defined flag
 * with this tenant's effective value; a flag is either inherited from the
 * platform default ("default") or pinned for this tenant ("override"). Toggling
 * a row pins it; "Revert" drops the override so it follows the default again.
 * You can't add arbitrary keys here — a flag has to exist at the platform level
 * before a tenant can override it.
 */
export function FeatureFlagsTab({ tenant }: TenantTabProps) {
  const arcadia = useArcadiaClient()
  const toast = useToast()

  const [flags, setFlags] = useState<TenantFeatureFlag[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<unknown>(null)
  const [busy, setBusy] = useState<string | null>(null)

  const load = useCallback(async () => {
    setError(null)
    setLoading(true)
    try {
      setFlags(await listFeatureFlags(arcadia, tenant.id))
    } catch (err) {
      setError(err)
    } finally {
      setLoading(false)
    }
  }, [arcadia, tenant.id])

  useEffect(() => {
    load()
  }, [load])

  const toggle = async (flag: TenantFeatureFlag, next: boolean) => {
    setBusy(flag.key)
    // Optimistic: reflect the pin immediately, roll back on failure.
    setFlags((prev) =>
      prev.map((f) => (f.key === flag.key ? { ...f, enabled: next, source: "override" } : f)),
    )
    try {
      await setFeatureFlag(arcadia, tenant.id, flag.key, next)
      toast.success(`${next ? "Enabled" : "Disabled"} ${flag.key} for ${tenant.name}`)
      await load()
    } catch (err) {
      setFlags((prev) => prev.map((f) => (f.key === flag.key ? flag : f)))
      toast.error(errorMessage(err, `override ${flag.key}`))
    } finally {
      setBusy(null)
    }
  }

  const revert = async (flag: TenantFeatureFlag) => {
    setBusy(flag.key)
    try {
      await clearFeatureFlag(arcadia, tenant.id, flag.key)
      toast.success(`${flag.key} follows the platform default again`)
      await load()
    } catch (err) {
      toast.error(errorMessage(err, `revert ${flag.key}`))
    } finally {
      setBusy(null)
    }
  }

  return (
    <Card>
      <CardHeader className="flex flex-row items-start justify-between gap-4">
        <div>
          <CardTitle>Feature flags</CardTitle>
          <CardDescription>
            Override a platform flag for this tenant. Un-overridden flags follow
            the platform default.
          </CardDescription>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={load}
          disabled={loading}
          data-action="tenant-detail-flags-refresh"
        >
          <RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </Button>
      </CardHeader>
      <CardContent className="p-0">
        <DataState
          loading={loading}
          error={error}
          isEmpty={flags.length === 0}
          onRetry={load}
          loadingLabel="Loading feature flags…"
          empty={
            <EmptyState
              title="No platform feature flags defined"
              description="Flags are defined at the platform level; once they exist, you can pin any of them on or off for this tenant here."
              className="py-12"
            />
          }
        >
          <ul className="divide-y">
            {flags.map((flag) => (
              <li key={flag.key} className="flex items-center gap-3 px-4 py-3">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <code className="font-mono text-sm">{flag.key}</code>
                    <BadgeCell
                      label={flag.source === "override" ? "override" : "default"}
                      tone={flag.source === "override" ? "info" : "default"}
                    />
                  </div>
                  {flag.description ? (
                    <p className="mt-0.5 truncate text-xs text-muted-foreground">
                      {flag.description}
                    </p>
                  ) : null}
                </div>

                {flag.source === "override" ? (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => revert(flag)}
                    disabled={busy === flag.key}
                    data-action={`tenant-detail-flags-revert-${flag.key}`}
                    title="Revert to the platform default"
                  >
                    <RotateCcw className="size-4" />
                    Revert
                  </Button>
                ) : null}

                <Switch
                  checked={flag.enabled}
                  onCheckedChange={(v) => toggle(flag, v)}
                  disabled={busy === flag.key}
                  data-action={`tenant-detail-flags-toggle-${flag.key}`}
                  aria-label={`Override ${flag.key}`}
                />
              </li>
            ))}
          </ul>
        </DataState>
      </CardContent>
    </Card>
  )
}
