import { useCallback, useEffect, useMemo, useState } from "react"
import {
  CheckCircle2,
  HardDrive,
  Pause,
  Play,
  Plus,
  RefreshCw,
  ShieldCheck,
  Star,
  Trash2,
  Wrench,
} from "lucide-react"

import { useArcadiaClient } from "@crema/arcadia-core-client"
import { useToast } from "@crema/notification-ui"
import {
  ActionsCell,
  BadgeCell,
  DataTable,
  DateCell,
  Pagination,
  useTable,
  type ActionItem,
  type BadgeTone,
  type Column,
} from "@crema/table-ui"
import { SearchInput } from "@crema/search-ui"
import { ConfirmDialog, EmptyState } from "@crema/feedback-ui"

import { AppShell } from "~/components/layout/app-shell"
import { DataState, DialogError } 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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "~/components/ui/dialog"
import { Input } from "~/components/ui/input"
import { Label } from "~/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "~/components/ui/select"
import { Switch } from "~/components/ui/switch"
import { Textarea } from "~/components/ui/textarea"
import {
  activateStorageConfig,
  createStorageConfig,
  deactivateStorageConfig,
  deleteStorageConfig,
  isMaskedSecret,
  isSecretField,
  listStorageConfigs,
  markStorageConfigDegraded,
  markStorageConfigMaintenance,
  OPTIONAL_FIELDS,
  REQUIRED_FIELDS,
  setDefaultStorageConfig,
  updateStorageConfig,
  validateStorageConfig,
  type StorageBackend,
  type StorageConfig,
  type StorageConfigInput,
  type StorageStatus,
} from "~/lib/arcadia/storage-configs"
import { pageTitle } from "~/lib/page-meta"
import { useSession } from "~/lib/session"
import { useRegisterContext } from "@crema/aifirst-ui/context"

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

type PendingAction =
  | { kind: "deactivate" | "degraded" | "maintenance" | "delete"; config: StorageConfig }
  | null

type EditorState =
  | { mode: "create" }
  | { mode: "edit"; config: StorageConfig }
  | null

const ACTION_PAST_TENSE: Record<
  Exclude<NonNullable<PendingAction>["kind"], never>,
  string
> = {
  deactivate: "Deactivated",
  degraded: "Marked degraded",
  maintenance: "Marked in maintenance",
  delete: "Deleted",
}

export default function StorageRoute() {
  const session = useSession()
  const arcadia = useArcadiaClient()
  const toast = useToast()

  const [configs, setConfigs] = useState<StorageConfig[]>([])
  const [loading, setLoading] = useState(true)
  // The raw thrown value — `DataState` normalises it into plain language. A
  // 500 here used to render "Internal Server Error" *and* "No storage configs
  // yet." side by side, which reads as an empty deployment.
  const [error, setError] = useState<unknown>(null)
  const [pending, setPending] = useState<PendingAction>(null)
  const [editor, setEditor] = useState<EditorState>(null)
  const [search, setSearch] = useState("")

  const refresh = useCallback(async () => {
    setError(null)
    setLoading(true)
    try {
      const list = await listStorageConfigs(arcadia)
      setConfigs(list)
    } catch (err) {
      setError(err)
    } finally {
      setLoading(false)
    }
  }, [arcadia])

  useEffect(() => {
    if (session) refresh()
  }, [session, refresh])

  const runAction = useCallback(
    async (action: PendingAction) => {
      if (!action) return
      try {
        if (action.kind === "deactivate") await deactivateStorageConfig(arcadia, action.config.id)
        else if (action.kind === "degraded")
          await markStorageConfigDegraded(arcadia, action.config.id)
        else if (action.kind === "maintenance")
          await markStorageConfigMaintenance(arcadia, action.config.id)
        else if (action.kind === "delete") await deleteStorageConfig(arcadia, action.config.id)
        setPending(null)
        await refresh()
        toast.success(`${ACTION_PAST_TENSE[action.kind]} ${action.config.name}`)
      } catch (err) {
        setPending(null)
        toast.error(errorMessage(err, `${action.kind} ${action.config.name}`))
      }
    },
    [arcadia, refresh, toast],
  )

  const validate = useCallback(
    async (config: StorageConfig) => {
      try {
        const result = await validateStorageConfig(arcadia, config.id)
        if (result?.ok) {
          toast.success(`${config.name} validated`, {
            description: "The backend answered with the credentials on file.",
          })
        } else {
          // The call succeeded; the *credentials* didn't. That's not a load
          // failure, so it belongs in a toast, not the table's error slot.
          toast.error(`${config.name} failed validation`, {
            description: result?.message ?? undefined,
          })
        }
      } catch (err) {
        toast.error(errorMessage(err, `validate ${config.name}`))
      }
    },
    [arcadia, toast],
  )

  const columns = useMemo<Column<StorageConfig>[]>(
    () => [
      {
        id: "name",
        header: "Name",
        accessor: "name",
        sortable: true,
        cell: (c) => (
          <span className="flex items-center gap-2 font-medium">
            {c.is_default ? <Star className="size-3.5 fill-amber-400 text-amber-400" /> : null}
            {c.name}
          </span>
        ),
      },
      {
        id: "backend",
        header: "Backend",
        accessor: "backend_type",
        sortable: true,
        cell: (c) => (
          <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs uppercase">
            {c.backend_type}
          </code>
        ),
      },
      {
        id: "status",
        header: "Status",
        accessor: "status",
        sortable: true,
        cell: (c) => <BadgeCell label={c.status} tone={statusTone(c.status)} />,
      },
      {
        id: "size",
        header: "Max size",
        accessor: "max_file_size_bytes",
        sortable: true,
        cell: (c) => (
          <span className="text-muted-foreground">{formatBytes(c.max_file_size_bytes)}</span>
        ),
      },
      {
        id: "updated",
        header: "Updated",
        accessor: "updated_at",
        sortable: true,
        cell: (c) => <DateCell value={c.updated_at} format="short" />,
      },
      {
        id: "actions",
        header: "",
        align: "right",
        cell: (c) => (
          <ActionsCell
            items={rowActions(c, {
              arcadia,
              refresh,
              setPending,
              setEditor,
              toast,
              validate,
            })}
            triggerDataAction={`storage-${slugify(c.name)}-actions`}
          />
        ),
      },
    ],
    [arcadia, refresh, toast, validate],
  )

  const summary = useMemo(
    () => ({
      total: configs.length,
      byStatus: configs.reduce<Record<string, number>>((acc, c) => {
        acc[c.status] = (acc[c.status] ?? 0) + 1
        return acc
      }, {}),
      byBackend: configs.reduce<Record<string, number>>((acc, c) => {
        acc[c.backend_type] = (acc[c.backend_type] ?? 0) + 1
        return acc
      }, {}),
      configs: configs.map((c) => ({
        id: c.id,
        name: c.name,
        backend_type: c.backend_type,
        status: c.status,
        is_default: c.is_default,
        max_file_size_bytes: c.max_file_size_bytes,
        updated_at: c.updated_at,
      })),
    }),
    [configs],
  )
  useRegisterContext("storage", summary)

  const table = useTable<StorageConfig>({
    data: configs,
    columns,
    getRowId: (c) => c.id,
    initialPageSize: 25,
    initialSearch: search,
  })
  useEffect(() => {
    table.setSearch(search)
  }, [search, table])

  return (
    <AppShell>
      <div className="flex flex-col gap-4">
        <header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight">Storage</h1>
            <p className="text-sm text-muted-foreground">
              Storage backends and credentials for the platform-admin tenant.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={refresh}
              disabled={loading}
              data-action="storage-refresh"
            >
              <RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
              Refresh
            </Button>
            <Button
              size="sm"
              onClick={() => setEditor({ mode: "create" })}
              data-action="storage-create"
            >
              <Plus className="size-4" />
              New storage config
            </Button>
          </div>
        </header>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between gap-4">
            <SearchInput
              value={search}
              onValueChange={setSearch}
              placeholder="Search by name, backend, or status"
              data-action="storage-search"
              className="max-w-sm flex-1"
            />
            <div className="text-xs text-muted-foreground">
              {table.total} of {configs.length}
            </div>
          </CardHeader>

          <CardContent className="relative p-0">
            <DataState
              loading={loading}
              error={error}
              isEmpty={table.total === 0}
              onRetry={refresh}
              loadingLabel="Loading storage configs…"
              empty={
                <EmptyState
                  title={search ? "No configs match that search." : "No storage configs yet."}
                  description={
                    search
                      ? "Try a different name, backend, or status."
                      : "Create your first storage config to start uploading objects."
                  }
                  className="py-12"
                />
              }
            >
              <DataTable
                columns={columns}
                rows={table.pageRows}
                getRowId={(c) => c.id}
                sort={table.sort}
                onSortToggle={table.toggleSort}
                loading={loading && configs.length > 0}
                stickyHeader
              />
              <Pagination
                page={table.page}
                pageSize={table.pageSize}
                total={table.total}
                onPageChange={table.setPage}
                onPageSizeChange={table.setPageSize}
              />
            </DataState>
          </CardContent>
        </Card>
      </div>

      <ConfirmDialog
        open={pending?.kind === "deactivate"}
        onOpenChange={(o) => !o && setPending(null)}
        title="Deactivate storage config?"
        description={
          pending
            ? `${pending.config.name} will stop accepting new uploads. Existing objects remain accessible.`
            : ""
        }
        confirmLabel="Deactivate"
        variant="default"
        onConfirm={() => runAction(pending)}
      />
      <ConfirmDialog
        open={pending?.kind === "degraded"}
        onOpenChange={(o) => !o && setPending(null)}
        title="Mark as degraded?"
        description={
          pending
            ? `${pending.config.name} will be flagged as degraded. The platform may route new uploads elsewhere.`
            : ""
        }
        confirmLabel="Mark degraded"
        variant="default"
        onConfirm={() => runAction(pending)}
      />
      <ConfirmDialog
        open={pending?.kind === "maintenance"}
        onOpenChange={(o) => !o && setPending(null)}
        title="Mark as in maintenance?"
        description={
          pending
            ? `${pending.config.name} will be put into maintenance mode.`
            : ""
        }
        confirmLabel="Mark maintenance"
        variant="default"
        onConfirm={() => runAction(pending)}
      />
      <ConfirmDialog
        open={pending?.kind === "delete"}
        onOpenChange={(o) => !o && setPending(null)}
        title="Delete storage config?"
        description={
          pending
            ? `${pending.config.name} will be permanently removed. Objects already stored on this backend may become unreachable.`
            : ""
        }
        confirmLabel="Delete"
        variant="danger"
        onConfirm={() => runAction(pending)}
      />

      <StorageEditorDialog
        state={editor}
        onClose={() => setEditor(null)}
        onSaved={async (name, wasEdit) => {
          setEditor(null)
          await refresh()
          toast.success(wasEdit ? `Saved ${name}` : `Created ${name}`)
        }}
      />
    </AppShell>
  )
}

function statusTone(status: StorageStatus): BadgeTone {
  if (status === "active") return "success"
  if (status === "degraded") return "warning"
  if (status === "maintenance") return "warning"
  if (status === "inactive") return "default"
  return "default"
}

function rowActions(
  c: StorageConfig,
  ctx: {
    arcadia: ReturnType<typeof useArcadiaClient>
    refresh: () => Promise<void>
    setPending: (p: PendingAction) => void
    setEditor: (s: EditorState) => void
    toast: ReturnType<typeof useToast>
    validate: (c: StorageConfig) => Promise<void>
  },
): ActionItem[] {
  const { arcadia, refresh, setPending, setEditor, toast, validate } = ctx
  const slug = slugify(c.name)
  const items: ActionItem[] = []

  items.push({
    id: "validate",
    label: "Validate",
    icon: <ShieldCheck className="size-4" />,
    dataAction: `storage-${slug}-validate`,
    onSelect: () => validate(c),
  })

  items.push({
    id: "edit",
    label: "Edit",
    dataAction: `storage-${slug}-edit`,
    onSelect: () => setEditor({ mode: "edit", config: c }),
  })

  if (c.status === "active") {
    items.push({
      id: "deactivate",
      label: "Deactivate",
      icon: <Pause className="size-4" />,
      dataAction: `storage-${slug}-deactivate`,
      onSelect: () => setPending({ kind: "deactivate", config: c }),
    })
  } else {
    items.push({
      id: "activate",
      label: "Activate",
      icon: <Play className="size-4" />,
      dataAction: `storage-${slug}-activate`,
      onSelect: async () => {
        try {
          await activateStorageConfig(arcadia, c.id)
          await refresh()
          toast.success(`Activated ${c.name}`)
        } catch (err) {
          toast.error(errorMessage(err, `activate ${c.name}`))
        }
      },
    })
  }

  if (!c.is_default) {
    items.push({
      id: "set-default",
      label: "Set as default",
      icon: <Star className="size-4" />,
      dataAction: `storage-${slug}-set-default`,
      onSelect: async () => {
        try {
          await setDefaultStorageConfig(arcadia, c.id)
          await refresh()
          toast.success(`${c.name} is now the default backend`)
        } catch (err) {
          toast.error(errorMessage(err, `set ${c.name} as the default backend`))
        }
      },
    })
  }

  items.push({
    id: "mark-degraded",
    label: "Mark degraded",
    icon: <Wrench className="size-4" />,
    dataAction: `storage-${slug}-mark-degraded`,
    onSelect: () => setPending({ kind: "degraded", config: c }),
  })
  items.push({
    id: "mark-maintenance",
    label: "Mark maintenance",
    icon: <Wrench className="size-4" />,
    dataAction: `storage-${slug}-mark-maintenance`,
    onSelect: () => setPending({ kind: "maintenance", config: c }),
  })

  items.push({
    id: "delete",
    label: "Delete",
    icon: <Trash2 className="size-4" />,
    destructive: true,
    dataAction: `storage-${slug}-delete`,
    onSelect: () => setPending({ kind: "delete", config: c }),
  })

  return items
}

function StorageEditorDialog({
  state,
  onClose,
  onSaved,
}: {
  state: EditorState
  onClose: () => void
  onSaved: (name: string, wasEdit: boolean) => Promise<void>
}) {
  const arcadia = useArcadiaClient()
  const open = state !== null
  const isEdit = state?.mode === "edit"
  const initial = isEdit ? state.config : null
  // Errors belong to the dialog, not the page: a page-level banner renders
  // behind the modal scrim, where nobody reads it.
  const [error, setError] = useState<unknown>(null)

  const [name, setName] = useState("")
  const [backend, setBackend] = useState<StorageBackend>("s3")
  const [isDefault, setIsDefault] = useState(false)
  const [maxSize, setMaxSize] = useState<string>("")
  const [allowedTypes, setAllowedTypes] = useState<string>("")
  const [fields, setFields] = useState<Record<string, string>>({})
  const [secretTouched, setSecretTouched] = useState<Record<string, boolean>>({})
  const [saving, setSaving] = useState(false)

  // Reset form whenever the dialog opens / target changes.
  useEffect(() => {
    if (!open) {
      setError(null)
      return
    }
    setError(null)
    if (initial) {
      setName(initial.name)
      setBackend(initial.backend_type)
      setIsDefault(initial.is_default)
      setMaxSize(
        initial.max_file_size_bytes == null ? "" : String(initial.max_file_size_bytes),
      )
      setAllowedTypes((initial.allowed_content_types ?? []).join(", "))
      const initialFields: Record<string, string> = {}
      const cfg = (initial.config ?? {}) as Record<string, unknown>
      for (const k of Object.keys(cfg)) {
        const v = cfg[k]
        initialFields[k] = isMaskedSecret(v) ? "" : v == null ? "" : String(v)
      }
      setFields(initialFields)
      setSecretTouched({})
    } else {
      setName("")
      setBackend("s3")
      setIsDefault(false)
      setMaxSize("")
      setAllowedTypes("")
      setFields({})
      setSecretTouched({})
    }
  }, [open, initial])

  const required = REQUIRED_FIELDS[backend]
  const optional = OPTIONAL_FIELDS[backend]

  const setField = (key: string, value: string) => {
    setFields((f) => ({ ...f, [key]: value }))
    if (isSecretField(backend, key)) {
      setSecretTouched((t) => ({ ...t, [key]: true }))
    }
  }

  const submit = async () => {
    setError(null)
    setSaving(true)
    try {
      const config: Record<string, unknown> = {}
      for (const k of [...required, ...optional]) {
        const v = fields[k]
        if (isSecretField(backend, k)) {
          // Only send a secret if the user typed a fresh value.
          if (secretTouched[k] && v !== "") config[k] = v
        } else if (v !== undefined && v !== "") {
          config[k] = v
        }
      }

      const allowed = allowedTypes
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean)

      const max = maxSize.trim() === "" ? null : Number(maxSize)
      if (max != null && Number.isNaN(max)) {
        throw new Error("Max file size must be a number (bytes).")
      }

      const input: StorageConfigInput = {
        name,
        backend_type: backend,
        config,
        is_default: isDefault,
        max_file_size_bytes: max,
        allowed_content_types: allowed.length ? allowed : undefined,
      }

      if (isEdit && initial) {
        await updateStorageConfig(arcadia, initial.id, input)
      } else {
        await createStorageConfig(arcadia, input)
      }
      await onSaved(name, isEdit)
    } catch (err) {
      // Keep the dialog open with the form intact — including any secret the
      // operator just pasted — so they can fix and resubmit.
      setError(err)
    } finally {
      setSaving(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{isEdit ? "Edit storage config" : "New storage config"}</DialogTitle>
          <DialogDescription>
            {isEdit
              ? "Secrets are write-only — leave masked fields blank to keep the existing value."
              : "Connect a backend to start storing objects on this tenant."}
          </DialogDescription>
        </DialogHeader>

        <div className="flex flex-col gap-3">
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="storage-name">Name</Label>
            <Input
              id="storage-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Primary S3 storage"
              data-action="storage-form-name"
            />
          </div>

          <div className="flex flex-col gap-1.5">
            <Label>Backend</Label>
            <Select
              value={backend}
              onValueChange={(v) => setBackend(v as StorageBackend)}
              disabled={isEdit}
            >
              <SelectTrigger data-action="storage-form-backend">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="s3">S3 (or S3-compatible)</SelectItem>
                <SelectItem value="gcs">Google Cloud Storage</SelectItem>
                <SelectItem value="local">Local filesystem</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {required.map((k) => (
            <BackendField
              key={k}
              label={fieldLabel(k)}
              field={k}
              backend={backend}
              value={fields[k] ?? ""}
              originalIsMasked={
                !!initial && isMaskedSecret((initial.config ?? {})[k as keyof typeof initial.config])
              }
              touched={!!secretTouched[k]}
              onChange={(v) => setField(k, v)}
              required
            />
          ))}
          {optional.map((k) => (
            <BackendField
              key={k}
              label={fieldLabel(k)}
              field={k}
              backend={backend}
              value={fields[k] ?? ""}
              originalIsMasked={false}
              touched={false}
              onChange={(v) => setField(k, v)}
            />
          ))}

          <div className="flex flex-col gap-1.5">
            <Label htmlFor="storage-max-size">Max file size (bytes)</Label>
            <Input
              id="storage-max-size"
              value={maxSize}
              onChange={(e) => setMaxSize(e.target.value)}
              placeholder="e.g. 104857600"
              data-action="storage-form-max-size"
            />
          </div>

          <div className="flex flex-col gap-1.5">
            <Label htmlFor="storage-allowed-types">Allowed content types (comma-separated)</Label>
            <Textarea
              id="storage-allowed-types"
              value={allowedTypes}
              onChange={(e) => setAllowedTypes(e.target.value)}
              placeholder="image/jpeg, image/png, application/pdf"
              data-action="storage-form-allowed-types"
              rows={2}
            />
          </div>

          <div className="flex items-center justify-between rounded-md border px-3 py-2">
            <div>
              <div className="text-sm font-medium">Default backend</div>
              <div className="text-xs text-muted-foreground">
                New uploads go here unless another backend is specified.
              </div>
            </div>
            <Switch
              checked={isDefault}
              onCheckedChange={setIsDefault}
              data-action="storage-form-is-default"
            />
          </div>
        </div>

        {error ? (
          <DialogError
            error={error}
            context={isEdit ? "save the storage config" : "create the storage config"}
          />
        ) : null}

        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={saving} data-action="storage-form-cancel">
            Cancel
          </Button>
          <Button onClick={submit} disabled={saving || name.trim() === ""} data-action="storage-form-save">
            {saving ? (
              <RefreshCw className="size-4 animate-spin" />
            ) : (
              <CheckCircle2 className="size-4" />
            )}
            {isEdit ? "Save changes" : "Create"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

function BackendField({
  label,
  field,
  backend,
  value,
  originalIsMasked,
  touched,
  onChange,
  required,
}: {
  label: string
  field: string
  backend: StorageBackend
  value: string
  originalIsMasked: boolean
  touched: boolean
  onChange: (v: string) => void
  required?: boolean
}) {
  const secret = isSecretField(backend, field)
  const isJson = field === "service_account_json"
  const placeholder = secret && originalIsMasked && !touched ? "•••••• (unchanged)" : ""
  const inputId = `storage-config-field-${field}`
  return (
    <div className="flex flex-col gap-1.5">
      <Label htmlFor={inputId}>
        {label}
        {required ? <span className="ml-1 text-destructive">*</span> : null}
      </Label>
      {isJson ? (
        <Textarea
          id={inputId}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder || "Paste service account JSON"}
          rows={4}
          data-action={`storage-form-config-${field}`}
        />
      ) : (
        <Input
          id={inputId}
          type={secret ? "password" : "text"}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          data-action={`storage-form-config-${field}`}
        />
      )}
    </div>
  )
}

function fieldLabel(key: string): string {
  return key
    .split("_")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ")
}

function slugify(s: string): string {
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "config"
}

function formatBytes(n: number | null): string {
  if (n == null) return "—"
  const units = ["B", "KB", "MB", "GB", "TB"]
  let i = 0
  let v = n
  while (v >= 1024 && i < units.length - 1) {
    v /= 1024
    i++
  }
  return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${units[i]}`
}

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