/**
 * InstallPWA Component
 * Prompt para instalação do PWA
 * @version 1.0
 */

import { useState, useEffect } from "react";
import { X, Download } from "lucide-react";

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

export function InstallPWA() {
  const [deferredPrompt, setDeferredPrompt] =
    useState<BeforeInstallPromptEvent | null>(null);
  const [showInstallPrompt, setShowInstallPrompt] = useState(false);

  useEffect(() => {
    const handler = (e: Event) => {
      // Previne o mini-infobar de aparecer
      e.preventDefault();
      // Salva o evento para disparar depois
      setDeferredPrompt(e as BeforeInstallPromptEvent);

      // Mostrar prompt personalizado depois de 10 segundos
      setTimeout(() => {
        setShowInstallPrompt(true);
      }, 10000);
    };

    window.addEventListener("beforeinstallprompt", handler);

    // Detectar se já está instalado
    if (window.matchMedia("(display-mode: standalone)").matches) {
      // Já está instalado como PWA
      setShowInstallPrompt(false);
    }

    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  const handleInstall = async () => {
    if (!deferredPrompt) return;

    // Mostrar prompt de instalação
    await deferredPrompt.prompt();

    // Esperar pela escolha do usuário
    const { outcome } = await deferredPrompt.userChoice;

    if (outcome === "accepted") {
      console.log("✅ PWA instalado com sucesso");
    } else {
      console.log("❌ Usuário recusou instalação");
    }

    // Limpar prompt
    setDeferredPrompt(null);
    setShowInstallPrompt(false);
  };

  const handleDismiss = () => {
    setShowInstallPrompt(false);
    // Salvar no localStorage que o usuário dispensou
    localStorage.setItem("pwa-install-dismissed", "true");
  };

  // Não mostrar se já foi dispensado antes
  useEffect(() => {
    if (localStorage.getItem("pwa-install-dismissed")) {
      setShowInstallPrompt(false);
    }
  }, []);

  if (!showInstallPrompt || !deferredPrompt) return null;

  return (
    <div
      className="
        fixed bottom-4 right-4 z-50 max-w-sm
        bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700
        animate-in slide-in-from-bottom-4 duration-300
      "
    >
      <div className="relative p-5">
        <button
          onClick={handleDismiss}
          className="absolute top-2 right-2 p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          aria-label="Fechar"
        >
          <X className="w-4 h-4 text-gray-500" />
        </button>

        <div className="flex items-start gap-4">
          <div className="p-3 bg-green-100 dark:bg-green-900/30 rounded-lg">
            <Download className="w-6 h-6 text-green-600 dark:text-green-400" />
          </div>

          <div className="flex-1">
            <h3 className="font-semibold text-gray-900 dark:text-white mb-1">
              Instalar MediConnect
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
              Acesse o sistema offline e tenha uma experiência mais rápida
            </p>

            <button
              onClick={handleInstall}
              className="
                w-full px-4 py-2 bg-green-600 hover:bg-green-700
                text-white font-medium rounded-lg
                transition-colors duration-200
                flex items-center justify-center gap-2
              "
            >
              <Download className="w-4 h-4" />
              Instalar Agora
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
