import { useState } from "react"
import { useParams } from "react-router-dom"
import { useProgram, useProgramGit, useProgramSync } from "@/services/api/hooks"
import { subdomainUrl } from "@/lib/labels"
import { DetailHeader } from "@/components/detail/DetailHeader"
import { ConfigPanel } from "@/components/detail/ConfigPanel"
import { DeploymentsSection } from "@/components/detail/DeploymentsSection"
import { ProgramActions, ActionOutputPanel, type ActionOutput } from "@/components/ProgramActions"
import { GitSyncRow } from "@/components/detail/GitSyncRow"

export function ProgramDetailPage() {
  const { name } = useParams<{ name: string }>()
  const { data: deployment, isLoading, error, refetch } = useProgram(name ?? "")
  const git = useProgramGit(name ?? "", !!deployment?.repo)
  const sync = useProgramSync()
  const [actionOutput, setActionOutput] = useState<ActionOutput | null>(null)

  const handleSync = () => {
    if (!deployment) return
    setActionOutput(null)
    sync.mutate(deployment.id, {
      onSuccess: (data) => {
        const lines = [data.output || (data.pulled ? "Pulled." : "Already up to date.")]
        if (data.pulled && data.deployments.length) {
          lines.push("", `May need a restart/apply: ${data.deployments.join(", ")}`)
        }
        setActionOutput({ action: "sync", text: lines.join("\n"), ok: true })
      },
      onError: (err) => {
        let text = String(err)
        try {
          text = JSON.parse((err as Error).message).detail ?? text
        } catch {
          text = (err as Error).message ?? text
        }
        setActionOutput({ action: "sync", text, ok: false })
      },
    })
  }

  if (isLoading) {
    return (
      <div className="max-w-3xl mx-auto px-6 py-8 text-[var(--muted)]">Loading...</div>
    )
  }

  if (error || !deployment) {
    return (
      <div className="max-w-3xl mx-auto px-6 py-8">
        <DetailHeader backTo="/" backLabel="Back" name={name ?? ""} />
        <p className="text-red-400">Program not found</p>
      </div>
    )
  }

  // A static (caddy) deployment with build outputs is served by the gateway in
  // place at its own subdomain — show where.
  const buildOutputs = (deployment.manifest.build as { outputs?: string[] } | undefined)?.outputs
  const isStatic = deployment.deployments.some((d) => d.kind === "static")
  const servedAt =
    isStatic && buildOutputs?.length
      ? (subdomainUrl(deployment.id) ?? `${deployment.id}.<gateway.domain>`)
      : null

  return (
    <div className="max-w-3xl mx-auto px-6 py-8">
      <DetailHeader
        backTo="/programs"
        backLabel="Back to Programs"
        name={deployment.id}
        stack={deployment.stack}
        source={deployment.source}
      >
        <ProgramActions
          name={deployment.id}
          actions={deployment.actions}
          onOutput={setActionOutput}
        />
      </DetailHeader>

      {actionOutput && actionOutput.action && (
        <div className="-mt-2 mb-6">
          <ActionOutputPanel output={actionOutput} onDismiss={() => setActionOutput(null)} />
        </div>
      )}

      {deployment.description && (
        <p className="text-sm text-[var(--muted)] -mt-4 mb-6">{deployment.description}</p>
      )}

      <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-5 mb-6">
        <h2 className="text-sm font-semibold text-[var(--muted)] uppercase tracking-wider mb-1">
          Program Info
        </h2>
        <p className="text-xs text-[var(--muted)] mb-4">
          Where the source lives and how wildpc works with it.
        </p>
        <div className="grid grid-cols-2 gap-x-6 gap-y-2 text-sm mb-4">
          {deployment.source && (
            <>
              <span className="text-[var(--muted)]">Source</span>
              <span className="font-mono break-all">{deployment.source}</span>
            </>
          )}
          {deployment.repo && (
            <>
              <span className="text-[var(--muted)]">Repo</span>
              <span className="font-mono break-all">
                {deployment.repo}
                {deployment.ref ? ` @ ${deployment.ref}` : ""}
              </span>
            </>
          )}
          {deployment.repo && git.data?.is_repo && (
            <>
              <span className="text-[var(--muted)]">Git</span>
              <GitSyncRow
                status={git.data}
                program={deployment.id}
                loading={git.isFetching}
                syncing={sync.isPending}
                onSync={handleSync}
              />
            </>
          )}
          {deployment.version && (
            <>
              <span className="text-[var(--muted)]">Version</span>
              <span>{deployment.version}</span>
            </>
          )}
          {deployment.active !== null && (
            <>
              <span className="text-[var(--muted)]">Active</span>
              <span className={deployment.active ? "text-green-400" : "text-[var(--muted)]"}>
                {deployment.active ? "● active" : "○ inactive"}
              </span>
            </>
          )}
          {servedAt && (
            <>
              <span className="text-[var(--muted)]">Reachable at</span>
              <a href={servedAt} className="font-mono break-all text-[var(--primary)] hover:underline">
                {servedAt} <span className="text-[var(--muted)]">· served (static)</span>
              </a>
            </>
          )}
        </div>

        {deployment.commands && Object.keys(deployment.commands).length > 0 && (
          <div className="mb-4">
            <span className="text-sm text-[var(--muted)] block mb-1">Commands</span>
            <div className="space-y-1">
              {Object.entries(deployment.commands).map(([verb, cmds]) => (
                <div key={verb} className="flex gap-2 text-xs">
                  <span className="text-[var(--muted)] w-20 shrink-0">{verb}</span>
                  <span className="font-mono break-all">
                    {cmds.map((argv) => argv.join(" ")).join(" && ")}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}

        {deployment.system_dependencies.length > 0 && (
          <div className="mb-4">
            <span className="text-sm text-[var(--muted)] block mb-1">System Dependencies</span>
            <div className="flex flex-wrap gap-1">
              {deployment.system_dependencies.map((dep) => (
                <span
                  key={dep}
                  className="text-xs px-2 py-0.5 rounded bg-amber-900/30 text-amber-400 border border-amber-800"
                >
                  {dep}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      <DeploymentsSection program={deployment} />

      <ConfigPanel deployment={deployment} configSection="programs" onRefetch={refetch} />
    </div>
  )
}
