"use client"

import * as React from "react"
import Link from "next/link"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { formatAppVersionLabel, getAppVersion } from "@/lib/app-version"
import type { ReleaseManifest } from "@/lib/release-manifest"
import { hasSeenReleaseModal, markReleaseModalSeen } from "@/lib/release-modal-storage"

export function ReleaseNotesModal() {
  const [open, setOpen] = React.useState(false)
  const [manifest, setManifest] = React.useState<ReleaseManifest | null>(null)

  React.useEffect(() => {
    let cancelled = false

    async function loadManifest() {
      try {
        const response = await fetch("/release-manifest.json", { cache: "no-store" })
        if (!response.ok) return

        const data = (await response.json()) as ReleaseManifest
        if (cancelled || !data.commits?.length || hasSeenReleaseModal(data.tag)) return

        setManifest(data)
        setOpen(true)
      } catch {
        // Локальная сборка или недоступный manifest — модалку не показываем.
      }
    }

    void loadManifest()

    return () => {
      cancelled = true
    }
  }, [])

  const handleOpenChange = (nextOpen: boolean) => {
    setOpen(nextOpen)
    if (!nextOpen && manifest) {
      markReleaseModalSeen(manifest.tag)
    }
  }

  const versionLabel = formatAppVersionLabel(manifest?.version ?? getAppVersion())

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="flex max-h-[min(85vh,720px)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[560px]">
        <DialogHeader className="gap-1 border-b px-6 py-4">
          <DialogTitle>Что нового в {versionLabel}</DialogTitle>
          <DialogDescription>
            Краткая сводка изменений текущего релиза MikrotikManager.
          </DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto px-6 py-4">
          {manifest?.commits.length ? (
            <ul className="flex flex-col gap-3">
              {manifest.commits.map((commit) => (
                <li
                  key={commit.sha}
                  className="flex flex-col gap-2 rounded-lg border bg-card px-3 py-2.5"
                >
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge variant="secondary" className="font-mono uppercase">
                      {commit.type}
                    </Badge>
                    <span className="font-mono text-xs text-muted-foreground">{commit.shortSha}</span>
                    <span className="text-xs text-muted-foreground">{commit.author}</span>
                  </div>
                  <p className="text-sm leading-relaxed">{commit.subject}</p>
                </li>
              ))}
            </ul>
          ) : null}
        </div>

        <DialogFooter className="border-t bg-muted/30 px-6 py-4 sm:justify-between">
          <Button
            variant="outline"
            render={<Link href="/releases" />}
            onClick={() => handleOpenChange(false)}
          >
            Все релизы
          </Button>
          <Button onClick={() => handleOpenChange(false)}>Понятно</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
