"use client"

import * as React from "react"
import { RefreshCw } from "lucide-react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { dashboardCsrfHeader } from "@/lib/csrf.client"
import { formatPlainAmount } from "@/lib/format/numbers"
import { STRUCTURE_PRODUCT_TYPE_OPTIONS } from "@/lib/structure-product-type"
import { errorMessageOr } from "@/lib/toast-api-error"

const HREF = "/dashboard/master-table/structure-master/bulk-propagate"
const RECENT_MS = 10 * 60 * 1000

type Phase = "idle" | "running" | "done" | "error"

type BulkPropagateProgress = {
  phase: Phase
  percent: number
  structures_total: number
  structures_done: number
  temp_rows: number
  transaction_rows: number
  underlying_rows: number
  error_count: number
  line: string | null
  finished_at: string | null
}

type BulkScope = {
  ids: number[]
  productType: string
}

const EMPTY_SCOPE: BulkScope = { ids: [], productType: "" }

let snapshot: BulkPropagateProgress | null = null
let scopeSnapshot: BulkScope = EMPTY_SCOPE
const listeners = new Set<() => void>()
const scopeListeners = new Set<() => void>()

export function setBulkPropagateScope(next: BulkScope) {
  const sameIds =
    next.ids.length === scopeSnapshot.ids.length &&
    next.ids.every((id, index) => id === scopeSnapshot.ids[index])
  if (sameIds && next.productType === scopeSnapshot.productType) return
  scopeSnapshot = { ids: next.ids, productType: next.productType }
  scopeListeners.forEach((listener) => listener())
}

function useBulkPropagateScope() {
  return React.useSyncExternalStore(
    (listener) => {
      scopeListeners.add(listener)
      return () => scopeListeners.delete(listener)
    },
    () => scopeSnapshot,
    () => EMPTY_SCOPE,
  )
}

function emit(next: BulkPropagateProgress | null) {
  snapshot = next
  listeners.forEach((listener) => listener())
}

function subscribe(listener: () => void) {
  listeners.add(listener)
  return () => listeners.delete(listener)
}

function useBulkPropagateProgress() {
  return React.useSyncExternalStore(
    subscribe,
    () => snapshot,
    () => null,
  )
}

function numberOrZero(value: unknown) {
  const parsed = typeof value === "number" ? value : Number(value)
  return Number.isFinite(parsed) ? parsed : 0
}

function parseProgress(data: unknown): BulkPropagateProgress | null {
  if (!data || typeof data !== "object") return null
  const row = data as Record<string, unknown>
  const phase = row.phase
  if (phase !== "idle" && phase !== "running" && phase !== "done" && phase !== "error") {
    return null
  }
  return {
    phase,
    percent: numberOrZero(row.percent),
    structures_total: numberOrZero(row.structures_total),
    structures_done: numberOrZero(row.structures_done),
    temp_rows: numberOrZero(row.temp_rows),
    transaction_rows: numberOrZero(row.transaction_rows),
    underlying_rows: numberOrZero(row.underlying_rows),
    error_count: numberOrZero(row.error_count),
    line: typeof row.line === "string" && row.line !== "" ? row.line : null,
    finished_at: typeof row.finished_at === "string" ? row.finished_at : null,
  }
}

function isRecent(progress: BulkPropagateProgress) {
  if (progress.phase === "running") return true
  if (!progress.finished_at) return progress.phase !== "idle"
  const at = Date.parse(progress.finished_at)
  return Number.isFinite(at) && Date.now() - at < RECENT_MS
}

async function loadProgress(): Promise<BulkPropagateProgress | null> {
  const res = await fetch(HREF, {
    headers: { Accept: "application/json" },
    cache: "no-store",
  })
  const json = await res.json().catch(() => ({}))
  if (!res.ok || json?.status === "error") {
    throw new Error(
      typeof json?.message === "string" ? json.message : "Could not load update progress.",
    )
  }
  return parseProgress(json?.data)
}

function scopeCopy(scope: BulkScope) {
  if (scope.ids.length > 0) {
    const count = scope.ids.length
    return {
      label: `Update selected (${count})`,
      title: `Update ${count} selected structure${count === 1 ? "" : "s"}?`,
      description: `Copies the current terms of the ${count} selected structure${count === 1 ? "" : "s"} onto their temp records and the portfolios that hold them.`,
      confirm: "Update selected",
    }
  }
  if (scope.productType) {
    return {
      label: `Update ${scope.productType}`,
      title: `Update every ${scope.productType} structure?`,
      description: `Copies every ${scope.productType} structure master's current terms onto its temp records and the portfolios that hold it. Tick rows first if you only want some of them.`,
      confirm: `Update ${scope.productType}`,
    }
  }
  return {
    label: "Update temp & transactions",
    title: "Update temp records and transactions?",
    description:
      "Copies every structure master's current terms onto its temp records and the portfolios that hold it. Filter by product type, or tick rows, to limit the run.",
    confirm: "Update all",
  }
}

export function BulkPropagateButton() {
  const progress = useBulkPropagateProgress()
  const scope = useBulkPropagateScope()
  const running = progress?.phase === "running"
  const [starting, setStarting] = React.useState(false)
  const [open, setOpen] = React.useState(false)
  const [setProductType, setSetProductType] = React.useState("")
  const copy = scopeCopy(scope)

  async function start() {
    if (running || starting) return
    setStarting(true)
    emit({
      phase: "running",
      percent: 0,
      structures_total: 0,
      structures_done: 0,
      temp_rows: 0,
      transaction_rows: 0,
      underlying_rows: 0,
      error_count: 0,
      line: "Starting update of temp records and transactions…",
      finished_at: null,
    })
    try {
      const res = await fetch(HREF, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          ...dashboardCsrfHeader(),
        },
        body: JSON.stringify({
          ids: scope.ids,
          product_type: scope.ids.length === 0 ? scope.productType : "",
          set_product_type: setProductType,
        }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.status === "error") {
        throw new Error(
          typeof json?.message === "string" ? json.message : "Could not start the update.",
        )
      }
      const parsed = parseProgress(json?.data)
      if (!parsed || parsed.phase === "idle") {
        emit(null)
        toast.info(typeof json?.message === "string" ? json.message : "Nothing to update.")
        return
      }
      emit(parsed)
    } catch (error) {
      emit(null)
      toast.error(errorMessageOr(error, "Could not start the update."))
    } finally {
      setStarting(false)
    }
  }

  return (
    <AlertDialog
      open={open}
      onOpenChange={(next) => {
        setOpen(next)
        if (next) setSetProductType("")
      }}
    >
      <AlertDialogTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          className="gap-1.5"
          disabled={running || starting}
        >
          <RefreshCw className={running || starting ? "size-4 animate-spin" : "size-4"} />
          {copy.label}
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{copy.title}</AlertDialogTitle>
          <AlertDialogDescription>
            {copy.description} Blank master fields are left alone. Strike, quantity and
            amounts are not recalculated. Name, expiry, coupon, barriers and underlyings
            (ISIN, name, currency, initial spot) are copied. This runs in the background.
            {setProductType
              ? ` The product type on these masters is set to ${setProductType} first.`
              : ""}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <label className="grid gap-1.5 text-sm">
          Set product type
          <select
            value={setProductType}
            onChange={(event) => setSetProductType(event.target.value)}
            className="h-8 rounded-md border bg-background px-2 text-sm"
          >
            <option value="">Don&apos;t change</option>
            {STRUCTURE_PRODUCT_TYPE_OPTIONS.map((type) => (
              <option key={type} value={type}>
                {type}
              </option>
            ))}
          </select>
          <span className="text-xs text-muted-foreground">
            Portfolio rows that store a product type are updated with the masters. Temp
            records have no product type column.
          </span>
        </label>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction onClick={() => void start()}>{copy.confirm}</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export function BulkPropagateProgressBanner() {
  const progress = useBulkPropagateProgress()
  const router = useRouter()
  const startedHere = React.useRef(false)

  React.useEffect(() => {
    if (!progress) {
      startedHere.current = false
      return
    }
    if (progress.phase === "running") {
      startedHere.current = true
      return
    }
    if (!startedHere.current) return
    if (progress.phase === "done" || progress.phase === "error") {
      startedHere.current = false
      router.refresh()
    }
  }, [progress, router])

  React.useEffect(() => {
    let cancelled = false
    let timer: ReturnType<typeof setTimeout> | undefined

    async function tick() {
      try {
        const next = await loadProgress()
        if (cancelled || !next) return
        if (next.phase === "running" || (next.phase !== "idle" && isRecent(next))) {
          emit(next)
        }
        // Keep polling through the gap between the optimistic "running" state and
        // the first progress write. Stop once the server reports a finish.
        const stillRunning =
          next.phase === "running" ||
          (next.phase === "idle" && snapshot?.phase === "running")
        if (stillRunning) {
          timer = setTimeout(() => void tick(), 2000)
        }
      } catch {
        if (!cancelled && snapshot?.phase === "running") {
          timer = setTimeout(() => void tick(), 2000)
        }
      }
    }

    void tick()
    return () => {
      cancelled = true
      if (timer) clearTimeout(timer)
    }
  }, [progress?.phase])

  if (!progress || progress.phase === "idle") return null

  const percent = Math.max(0, Math.min(100, progress.percent))
  const title =
    progress.phase === "running"
      ? "Updating temp records and transactions…"
      : progress.phase === "error"
        ? "Update finished with errors."
        : "Update finished."

  return (
    <div className="space-y-1.5 rounded-md border bg-muted/20 px-3 py-2">
      <div className="flex items-baseline justify-between gap-3">
        <p className="min-w-0 truncate text-sm text-foreground">{progress.line ?? title}</p>
        <span className="shrink-0 text-xs tabular-nums text-muted-foreground">{percent}%</span>
      </div>
      <div className="h-1.5 overflow-hidden rounded-full bg-muted">
        <div
          className={
            progress.phase === "error"
              ? "h-full rounded-full bg-destructive transition-[width] duration-300"
              : "h-full rounded-full bg-emerald-600 transition-[width] duration-300"
          }
          style={{ width: `${Math.max(progress.phase === "running" ? 2 : 0, percent)}%` }}
        />
      </div>
      <p className="text-[11px] tabular-nums text-muted-foreground">
        {`${formatPlainAmount(progress.structures_done)}/${formatPlainAmount(progress.structures_total)} structures`}
        {` · ${formatPlainAmount(progress.temp_rows)} temp`}
        {` · ${formatPlainAmount(progress.transaction_rows)} transactions`}
        {` · ${formatPlainAmount(progress.underlying_rows)} underlyings`}
        {progress.error_count > 0
          ? ` · ${formatPlainAmount(progress.error_count)} errors`
          : ""}
      </p>
    </div>
  )
}
