"use client"

import type React from "react"

import { useEffect, useState } from "react"
import { registerServiceWorker } from "@/lib/service-worker-registration"
import { Download, X, RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"

interface BeforeInstallPromptEvent extends Event {
  prompt(): Promise<void>
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>
}

export function PWAProvider({ children }: { children: React.ReactNode }) {
  const [installPrompt, setInstallPrompt] = useState<BeforeInstallPromptEvent | null>(null)
  const [showInstallBanner, setShowInstallBanner] = useState(false)
  const [showUpdateBanner, setShowUpdateBanner] = useState(false)
  const [isProduction, setIsProduction] = useState(false)

  useEffect(() => {
    const isProd =
      !window.location.hostname.includes("vusercontent.net") &&
      !window.location.hostname.includes("v0.app") &&
      window.location.hostname !== "localhost"

    setIsProduction(isProd)

    if (!isProd) {
      console.log("[v0] PWA features disabled in preview environment")
      return
    }

    registerServiceWorker()

    const handleBeforeInstall = (e: Event) => {
      e.preventDefault()
      setInstallPrompt(e as BeforeInstallPromptEvent)

      const dismissedAt = localStorage.getItem("pwa-banner-dismissed")
      if (!dismissedAt || Date.now() - Number.parseInt(dismissedAt) > 7 * 24 * 60 * 60 * 1000) {
        setShowInstallBanner(true)
      }
    }

    const handleAppInstalled = () => {
      setShowInstallBanner(false)
      setInstallPrompt(null)
    }

    const handleUpdateAvailable = () => {
      setShowUpdateBanner(true)
    }

    window.addEventListener("beforeinstallprompt", handleBeforeInstall)
    window.addEventListener("appinstalled", handleAppInstalled)
    window.addEventListener("sw-update-available", handleUpdateAvailable)

    return () => {
      window.removeEventListener("beforeinstallprompt", handleBeforeInstall)
      window.removeEventListener("appinstalled", handleAppInstalled)
      window.removeEventListener("sw-update-available", handleUpdateAvailable)
    }
  }, [])

  const handleInstall = async () => {
    if (!installPrompt) return

    await installPrompt.prompt()
    const { outcome } = await installPrompt.userChoice

    if (outcome === "accepted") {
      setShowInstallBanner(false)
    }

    setInstallPrompt(null)
  }

  const handleDismissInstall = () => {
    setShowInstallBanner(false)
    localStorage.setItem("pwa-banner-dismissed", Date.now().toString())
  }

  const handleUpdate = () => {
    window.location.reload()
  }

  return (
    <>
      {children}

      {isProduction && showInstallBanner && (
        <div className="fixed bottom-20 left-4 right-4 z-50 mx-auto max-w-md animate-in slide-in-from-bottom-4">
          <div className="rounded-xl border border-border bg-card p-4 shadow-lg">
            <div className="flex items-start gap-3">
              <div className="rounded-full bg-primary/10 p-2">
                <Download className="h-5 w-5 text-primary" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold text-foreground">Installer Musique</h3>
                <p className="text-sm text-muted-foreground">
                  Installez l&apos;application pour une meilleure experience et l&apos;ecoute hors ligne.
                </p>
                <div className="mt-3 flex gap-2">
                  <Button size="sm" onClick={handleInstall}>
                    Installer
                  </Button>
                  <Button size="sm" variant="ghost" onClick={handleDismissInstall}>
                    Plus tard
                  </Button>
                </div>
              </div>
              <button onClick={handleDismissInstall} className="text-muted-foreground hover:text-foreground">
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>
      )}

      {isProduction && showUpdateBanner && (
        <div className="fixed top-4 left-4 right-4 z-50 mx-auto max-w-md animate-in slide-in-from-top-4">
          <div className="rounded-xl border border-border bg-card p-4 shadow-lg">
            <div className="flex items-center gap-3">
              <div className="rounded-full bg-primary/10 p-2">
                <RefreshCw className="h-5 w-5 text-primary" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold text-foreground">Mise a jour disponible</h3>
                <p className="text-sm text-muted-foreground">Une nouvelle version est disponible.</p>
              </div>
              <Button size="sm" onClick={handleUpdate}>
                Actualiser
              </Button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
