import { useCallback, useEffect, useMemo, useState } from "react"
import { Link, useNavigate, useParams } from "react-router"
import { ArrowLeft, Pause, Play, RefreshCw } from "lucide-react"

import { useArcadiaClient } from "@crema/arcadia-core-client"
import { BadgeCell, type BadgeTone } from "@crema/table-ui"
import { ConfirmDialog } from "@crema/feedback-ui"
import { useToast } from "@crema/notification-ui"
import { useRegisterContext } from "@crema/aifirst-ui/context"

import { AppShell } from "~/components/layout/app-shell"
import { PageHeader } from "~/components/layout/page-header"
import { DataState } from "~/components/data-state"
import { TenantSection, Field } from "~/components/tenant-detail/section"
import { Button } from "~/components/ui/button"
import { Input } from "~/components/ui/input"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs"
import {
  activateTenant,
  deactivateTenant,
  getTenant,
  suspendTenant,
  updateTenant,
  type Tenant,
  type TenantStatus,
} from "~/lib/arcadia/tenants"
import { errorMessage } from "~/lib/errors"
import { pageTitle } from "~/lib/page-meta"
import { useSession } from "~/lib/session"

// The eight tabs. Each is its own component so the file stays legible and the
// tabs can evolve independently; they share the TenantSection frame and take
// the loaded tenant + a `reload` callback.
import { PlanTab } from "~/components/tenant-detail/plan-tab"
import { BrandingTab } from "~/components/tenant-detail/branding-tab"
import { LocalizationTab } from "~/components/tenant-detail/localization-tab"
import { DeliveryTab } from "~/components/tenant-detail/delivery-tab"
import { FeatureFlagsTab } from "~/components/tenant-detail/feature-flags-tab"
import { IpRulesTab } from "~/components/tenant-detail/ip-rules-tab"
import { InboundWebhooksTab } from "~/components/tenant-detail/inbound-webhooks-tab"

export const meta = () => pageTitle("Tenant")

export type TenantTabProps = {
  tenant: Tenant
  /** Re-fetch the tenant after a mutation that changes the header fields. */
  reload: () => Promise<void>
}

type PendingAction = { kind: "suspend" | "deactivate" } | null

const TABS = [
  { value: "overview", label: "Overview" },
  { value: "plan", label: "Plan & quotas" },
  { value: "branding", label: "Branding" },
  { value: "localization", label: "Localization" },
  { value: "delivery", label: "Email & SMS" },
  { value: "flags", label: "Feature flags" },
  { value: "ip-rules", label: "IP rules" },
  { value: "webhooks", label: "Inbound webhooks" },
]

export default function TenantDetailRoute() {
  const { id = "" } = useParams()
  const session = useSession()
  const arcadia = useArcadiaClient()
  const toast = useToast()
  const navigate = useNavigate()

  const [tenant, setTenant] = useState<Tenant | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<unknown>(null)
  const [tab, setTab] = useState("overview")
  const [pending, setPending] = useState<PendingAction>(null)

  const reload = useCallback(async () => {
    setError(null)
    setLoading(true)
    try {
      setTenant(await getTenant(arcadia, id))
    } catch (err) {
      setError(err)
    } finally {
      setLoading(false)
    }
  }, [arcadia, id])

  useEffect(() => {
    if (session && id) reload()
  }, [session, id, reload])

  useRegisterContext(
    "tenantDetail",
    useMemo(
      () => ({
        loaded: !!tenant,
        id: tenant?.id ?? id,
        slug: tenant?.slug ?? null,
        name: tenant?.name ?? null,
        status: tenant?.status ?? null,
        plan: tenant?.plan?.name ?? null,
        activeTab: tab,
      }),
      [tenant, tab, id],
    ),
  )

  const runLifecycle = useCallback(
    async (action: PendingAction) => {
      if (!action || !tenant) return
      const verb = action.kind === "suspend" ? "Suspended" : "Deactivated"
      try {
        if (action.kind === "suspend") await suspendTenant(arcadia, tenant.id)
        else await deactivateTenant(arcadia, tenant.id)
        setPending(null)
        await reload()
        toast.success(`${verb} ${tenant.name}`)
      } catch (err) {
        setPending(null)
        toast.error(errorMessage(err, `${action.kind} ${tenant.name}`))
      }
    },
    [arcadia, tenant, reload, toast],
  )

  const activate = useCallback(async () => {
    if (!tenant) return
    try {
      await activateTenant(arcadia, tenant.id)
      await reload()
      toast.success(`Activated ${tenant.name}`)
    } catch (err) {
      toast.error(errorMessage(err, `activate ${tenant.name}`))
    }
  }, [arcadia, tenant, reload, toast])

  return (
    <AppShell>
      <PageHeader
        title={
          <span className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="icon-sm"
              onClick={() => navigate("/tenants")}
              aria-label="Back to tenants"
              data-action="tenant-detail-back"
            >
              <ArrowLeft className="size-4" />
            </Button>
            {tenant?.name ?? "Tenant"}
          </span>
        }
        badges={
          tenant ? (
            <>
              <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">
                {tenant.slug}
              </code>
              <BadgeCell label={tenant.status} tone={statusTone(tenant.status)} />
            </>
          ) : null
        }
        description={
          <Link to="/tenants" className="inline-flex items-center gap-1 hover:underline">
            <ArrowLeft className="size-3" /> All tenants
          </Link>
        }
        actions={
          tenant ? (
            <>
              <Button
                variant="outline"
                size="sm"
                onClick={reload}
                disabled={loading}
                data-action="tenant-detail-refresh"
              >
                <RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
                Refresh
              </Button>
              {tenant.status === "active" ? (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPending({ kind: "suspend" })}
                  data-action="tenant-detail-suspend"
                >
                  <Pause className="size-4" />
                  Suspend
                </Button>
              ) : (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={activate}
                  data-action="tenant-detail-activate"
                >
                  <Play className="size-4" />
                  Activate
                </Button>
              )}
              <Button
                variant="outline"
                size="sm"
                className="text-destructive"
                onClick={() => setPending({ kind: "deactivate" })}
                data-action="tenant-detail-deactivate"
              >
                Deactivate
              </Button>
            </>
          ) : null
        }
      />

      <DataState
        loading={loading}
        error={error}
        isEmpty={!tenant}
        onRetry={reload}
        loadingLabel="Loading tenant…"
        empty={<div className="py-12 text-center text-muted-foreground">Tenant not found.</div>}
      >
        {tenant ? (
          <Tabs value={tab} onValueChange={setTab}>
            <div className="overflow-x-auto">
              <TabsList>
                {TABS.map((t) => (
                  <TabsTrigger
                    key={t.value}
                    value={t.value}
                    data-action={`tenant-detail-tab-${t.value}`}
                  >
                    {t.label}
                  </TabsTrigger>
                ))}
              </TabsList>
            </div>

            <TabsContent value="overview">
              <OverviewTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="plan">
              <PlanTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="branding">
              <BrandingTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="localization">
              <LocalizationTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="delivery">
              <DeliveryTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="flags">
              <FeatureFlagsTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="ip-rules">
              <IpRulesTab tenant={tenant} reload={reload} />
            </TabsContent>
            <TabsContent value="webhooks">
              <InboundWebhooksTab tenant={tenant} reload={reload} />
            </TabsContent>
          </Tabs>
        ) : null}
      </DataState>

      <ConfirmDialog
        open={pending?.kind === "suspend"}
        onOpenChange={(o) => !o && setPending(null)}
        title="Suspend tenant?"
        description={
          tenant
            ? `${tenant.name} will be suspended. Members won't be able to sign in until you reactivate.`
            : ""
        }
        confirmLabel="Suspend"
        variant="default"
        onConfirm={() => runLifecycle(pending)}
      />
      <ConfirmDialog
        open={pending?.kind === "deactivate"}
        onOpenChange={(o) => !o && setPending(null)}
        title="Deactivate tenant?"
        description={
          tenant
            ? `${tenant.name} will be taken offline: nobody can sign in and its apps stop serving. Its data is kept, and you can reactivate it from here. Suspend instead if this is temporary.`
            : ""
        }
        confirmLabel="Deactivate"
        variant="danger"
        onConfirm={() => runLifecycle(pending)}
      />
    </AppShell>
  )
}

function statusTone(status: TenantStatus): BadgeTone {
  if (status === "active") return "success"
  if (status === "suspended") return "warning"
  if (status === "deactivated") return "danger"
  return "default"
}

// --- Overview tab (reference implementation for the other seven) ---

function OverviewTab({ tenant, reload }: TenantTabProps) {
  const arcadia = useArcadiaClient()
  const toast = useToast()
  const [name, setName] = useState(tenant.name)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<unknown>(null)

  const dirty = name.trim() !== tenant.name && name.trim().length > 0

  const save = async () => {
    setSaving(true)
    setError(null)
    try {
      await updateTenant(arcadia, tenant.id, { name: name.trim() })
      await reload()
      toast.success("Tenant name updated")
    } catch (err) {
      setError(err)
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <TenantSection
        title="Identity"
        description="The tenant's display name. The slug is fixed once created — it's baked into URLs and the X-Tenant-ID header."
        onSubmit={save}
        saving={saving}
        error={error}
        errorContext="rename the tenant"
        dirty={dirty}
        dataAction="tenant-detail-overview-save"
      >
        <Field label="Name" htmlFor="tenant-name">
          <Input
            id="tenant-name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            data-action="tenant-detail-overview-name"
          />
        </Field>
        <Field label="Slug">
          <Input value={tenant.slug} readOnly disabled className="font-mono" />
        </Field>
      </TenantSection>

      <div className="grid gap-3 sm:grid-cols-2">
        <FactCard label="Status" value={tenant.status} />
        <FactCard label="Plan" value={tenant.plan?.name ?? "—"} />
        <FactCard label="Created" value={new Date(tenant.inserted_at).toLocaleString()} />
        <FactCard label="Last updated" value={new Date(tenant.updated_at).toLocaleString()} />
      </div>
    </div>
  )
}

function FactCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border bg-card/40 px-4 py-3">
      <div className="text-xs uppercase tracking-wider text-muted-foreground">{label}</div>
      <div className="mt-0.5 font-medium capitalize">{value}</div>
    </div>
  )
}

export { RouteErrorBoundary as ErrorBoundary } from "~/components/route-error"
