"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { X, Rocket, ArrowRight, ArrowLeft } from "lucide-react";
import type { Lang } from "@/lib/config";

const STORAGE_KEY = "mawidi_pilot_badge_dismissed";
const DISMISS_DURATION_DAYS = 14;

interface PilotProgramBadgeProps {
  lang: Lang;
  position?: "bottom-left" | "bottom-right";
  showOnPages?: string[];
  demoLink?: string;
}

const translations = {
  en: {
    title: "Join our pilot program",
    description: "Get early access with special pricing",
    cta: "Book a Demo",
    dismiss: "Dismiss",
  },
  ar: {
    title: "انضم إلى برنامجنا التجريبي",
    description: "احصل على وصول مبكر بأسعار خاصة",
    cta: "احجز عرضًا",
    dismiss: "إغلاق",
  },
};

/**
 * PilotProgramBadge Component
 *
 * A floating widget promoting the pilot program.
 * Designed to appear on industry and feature pages.
 *
 * Features:
 * - Floating position (bottom-left or bottom-right)
 * - Bilingual support (Arabic/English)
 * - Dismiss persistence via localStorage
 * - Slide-in animation
 * - Links to demo booking
 *
 * @example
 * <PilotProgramBadge
 *   lang="en"
 *   position="bottom-left"
 *   showOnPages={['/industries', '/about']}
 * />
 */
export function PilotProgramBadge({
  lang,
  position = "bottom-left",
  showOnPages,
  demoLink,
}: PilotProgramBadgeProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const t = translations[lang];
  const isRTL = lang === "ar";

  const defaultDemoLink = `/${lang}/demo`;
  const link = demoLink || defaultDemoLink;

  useEffect(() => {
    // Check if badge was dismissed
    const dismissedData = localStorage.getItem(STORAGE_KEY);
    if (dismissedData) {
      try {
        const { timestamp } = JSON.parse(dismissedData);
        const dismissedAt = new Date(timestamp);
        const now = new Date();
        const daysSinceDismiss =
          (now.getTime() - dismissedAt.getTime()) / (1000 * 60 * 60 * 24);

        if (daysSinceDismiss < DISMISS_DURATION_DAYS) {
          return; // Keep hidden
        }
      } catch {
        // Invalid data, show badge
      }
    }

    // Check page restrictions
    if (typeof window !== "undefined" && showOnPages) {
      const currentPath = window.location.pathname;
      if (!showOnPages.some((page) => currentPath.includes(page))) {
        return;
      }
    }

    // Delay appearance for better UX
    const showTimer = setTimeout(() => {
      setIsVisible(true);
    }, 2000);

    // Auto-expand after appearing
    const expandTimer = setTimeout(() => {
      setIsExpanded(true);
    }, 3000);

    return () => {
      clearTimeout(showTimer);
      clearTimeout(expandTimer);
    };
  }, [showOnPages]);

  const handleDismiss = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsVisible(false);
    localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({ timestamp: new Date().toISOString() }),
    );
  };

  const handleToggle = () => {
    setIsExpanded(!isExpanded);
  };

  if (!isVisible) return null;

  const positionClasses = {
    "bottom-left": isRTL ? "right-4" : "left-4",
    "bottom-right": isRTL ? "left-4" : "right-4",
  };

  const ArrowIcon = isRTL ? ArrowLeft : ArrowRight;

  return (
    <div
      className={`fixed bottom-20 z-40 transition-all duration-500 ease-out ${
        positionClasses[position]
      } ${isVisible ? "translate-y-0 opacity-100" : "translate-y-8 opacity-0"}`}
      dir={isRTL ? "rtl" : "ltr"}
    >
      <div
        className={`relative bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden transition-all duration-300 ${
          isExpanded ? "w-72" : "w-14"
        }`}
      >
        {/* Collapsed state - just icon */}
        <button
          onClick={handleToggle}
          className={`flex items-center justify-center w-14 h-14 bg-gradient-to-br from-indigo-600 to-purple-600 text-white transition-all duration-300 ${
            isExpanded ? "absolute top-0 " + (isRTL ? "right-0" : "left-0") : ""
          }`}
          aria-label={t.title}
        >
          <Rocket
            className={`w-6 h-6 transition-transform duration-300 ${isExpanded ? "rotate-12" : ""}`}
          />
        </button>

        {/* Expanded content */}
        <div
          className={`transition-all duration-300 overflow-hidden ${
            isExpanded ? "opacity-100 max-h-40" : "opacity-0 max-h-0"
          }`}
        >
          <div className={`p-4 ${isRTL ? "pr-16" : "pl-16"}`}>
            {/* Close button */}
            <button
              onClick={handleDismiss}
              className={`absolute top-2 ${isRTL ? "left-2" : "right-2"} p-1 text-gray-400 hover:text-gray-600 transition-colors rounded-full hover:bg-gray-100`}
              aria-label={t.dismiss}
            >
              <X className="w-4 h-4" />
            </button>

            <h3 className="font-bold text-gray-900 text-sm mb-1">{t.title}</h3>
            <p className="text-gray-600 text-xs mb-3">{t.description}</p>

            <Link
              href={link}
              className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-gradient-to-r from-indigo-600 to-purple-600 text-white text-xs font-semibold rounded-full hover:from-indigo-700 hover:to-purple-700 transition-all group"
            >
              {t.cta}
              <ArrowIcon
                className={`w-3 h-3 transition-transform group-hover:${isRTL ? "-translate-x-0.5" : "translate-x-0.5"}`}
              />
            </Link>
          </div>
        </div>

        {/* Pulse indicator for collapsed state */}
        {!isExpanded && (
          <span className="absolute top-0 right-0 w-3 h-3">
            <span className="absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75 animate-ping" />
            <span className="relative inline-flex rounded-full h-3 w-3 bg-indigo-500" />
          </span>
        )}
      </div>
    </div>
  );
}

export default PilotProgramBadge;
