import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import {
  Info,
  ShieldCheck,
  MessageCircle,
  Mail,
  ExternalLink,
  User,
  Sparkles,
  Download,
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import {
  APP_VERSION,
  buildWhatsAppUrl,
  fetchAppInfo,
  type AppInfo,
} from "@/lib/appInfo";
import { useAppUpdate } from "@/hooks/useAppUpdate";
import { isTizen, isWebOS } from "@/lib/platform";

/**
 * Help & About card shown on /account. Surfaces:
 *   • App icon + name + installed version
 *   • "Update available" indicator + manual download button (when admin enabled)
 *   • Privacy Policy link (admin-editable)
 *   • Creator info card
 *   • Support email + WhatsApp contact button (FAB)
 */
const AccountAboutCard = () => {
  const navigate = useNavigate();
  const { hasUpdate, info: liveInfo } = useAppUpdate();
  const [info, setInfo] = useState<AppInfo | null>(liveInfo);

  useEffect(() => {
    if (liveInfo) {
      setInfo(liveInfo);
      return;
    }
    let cancelled = false;
    void fetchAppInfo()
      .then((d) => {
        if (!cancelled) setInfo(d);
      })
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, [liveInfo]);

  const creator = info?.creator;
  const support = info?.support;
  const update = info?.update;

  const waUrl = support
    ? buildWhatsAppUrl(support.whatsapp_number, support.whatsapp_message)
    : null;

  const downloadUrl = update?.apk_url || update?.play_url || "";

  return (
    <div
      className="glass-card rounded-2xl p-4 space-y-4"
      data-testid="account-help-about-card"
    >
      {/* Header */}
      <div className="flex items-center gap-2">
        <Info className="w-4 h-4 text-primary" />
        <p className="text-foreground text-sm font-medium">Help & About</p>
      </div>

      {/* App identity */}
      <div className="flex items-center gap-3 rounded-xl border border-border/60 bg-background/30 p-3">
        <div className="flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-primary/40 bg-primary/10">
          <img
            src="/icon-192.png"
            alt="Nadiplayer"
            className="h-12 w-12 object-cover"
            onError={(e) => {
              (e.currentTarget as HTMLImageElement).style.display = "none";
            }}
            data-testid="account-app-icon"
          />
        </div>
        <div className="min-w-0 flex-1">
          <p className="truncate text-sm font-semibold text-foreground">
            Nadiplayer
          </p>
          <p
            className="text-[11px] text-muted-foreground"
            data-testid="account-app-version"
          >
            Version v{APP_VERSION}
            {update?.latest_version &&
              update.latest_version !== APP_VERSION && (
                <span className="ml-1 text-muted-foreground/70">
                  (latest v{update.latest_version})
                </span>
              )}
          </p>
        </div>
        {hasUpdate && !isTizen() && !isWebOS() && (
          <span
            className="ml-auto inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/15 px-2 py-1 text-[10px] font-medium text-primary"
            data-testid="account-update-badge"
          >
            <Sparkles className="h-3 w-3" />
            Update
          </span>
        )}
      </div>

      {/* Manual download — Samsung Tizen + LG webOS QA forbid in-app
          APK / package self-updates. Updates on those platforms MUST
          flow through the Samsung Apps store / LG Content Store. Card
          hidden completely on Smart-TV builds. */}
      {downloadUrl && !isTizen() && !isWebOS() && (
        <a
          href={downloadUrl}
          target="_blank"
          rel="noopener noreferrer"
          data-testid="account-download-update-btn"
          className="flex items-center justify-center gap-2 rounded-xl border border-primary/40 bg-primary/10 px-4 py-2.5 text-xs font-medium text-primary transition-colors hover:bg-primary/15"
        >
          <Download className="h-3.5 w-3.5" />
          {hasUpdate ? "Download latest version" : "Check downloads"}
        </a>
      )}

      {/* Smart-TV-only fallback message — replaces the download button */}
      {(isTizen() || isWebOS()) && hasUpdate && (
        <p
          className="rounded-xl border border-primary/30 bg-primary/5 px-3 py-2.5 text-center text-[11px] leading-relaxed text-primary/90"
          data-testid="account-tv-update-hint"
        >
          A newer version is available. Please update from the
          {isTizen() ? " Samsung Apps store " : " LG Content Store "}
          on your TV.
        </p>
      )}

      {/* Creator info */}
      {(creator?.name || creator?.bio || creator?.role) && (
        <div
          className="rounded-xl border border-border/60 bg-background/30 p-3"
          data-testid="account-creator-card"
        >
          <p className="mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-muted-foreground">
            Created by
          </p>
          <div className="flex items-start gap-3">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full border border-primary/40 bg-primary/10">
              {creator.avatar_url ? (
                <img
                  src={creator.avatar_url}
                  alt={creator.name}
                  className="h-10 w-10 object-cover"
                  onError={(e) => {
                    (e.currentTarget as HTMLImageElement).style.display =
                      "none";
                  }}
                />
              ) : (
                <User className="h-5 w-5 text-primary" />
              )}
            </div>
            <div className="min-w-0 flex-1">
              {creator.name && (
                <p
                  className="truncate text-sm font-medium text-foreground"
                  data-testid="account-creator-name"
                >
                  {creator.name}
                </p>
              )}
              {creator.role && (
                <p className="truncate text-[11px] text-primary/80">
                  {creator.role}
                </p>
              )}
              {creator.bio && (
                <p className="mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-muted-foreground">
                  {creator.bio}
                </p>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Support row (email + privacy + WhatsApp link) */}
      <div className="grid grid-cols-1 gap-2">
        <button
          type="button"
          onClick={() => navigate("/privacy")}
          data-testid="account-privacy-link"
          className="flex items-center gap-2 rounded-xl border border-border/60 bg-background/30 px-3 py-2.5 text-xs text-foreground transition-colors hover:border-primary/40"
        >
          <ShieldCheck className="h-3.5 w-3.5 text-primary" />
          <span>Privacy Policy</span>
          <ExternalLink className="ml-auto h-3 w-3 text-muted-foreground" />
        </button>

        {support?.email && (
          <a
            href={`mailto:${support.email}`}
            data-testid="account-email-link"
            className="flex items-center gap-2 rounded-xl border border-border/60 bg-background/30 px-3 py-2.5 text-xs text-foreground transition-colors hover:border-primary/40"
          >
            <Mail className="h-3.5 w-3.5 text-primary" />
            <span className="truncate">{support.email}</span>
          </a>
        )}
      </div>

      {/* WhatsApp floating button */}
      {waUrl && (
        <motion.a
          initial={{ scale: 0.92, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          href={waUrl}
          target="_blank"
          rel="noopener noreferrer"
          data-testid="account-whatsapp-fab"
          aria-label="Contact us on WhatsApp"
          className="fixed bottom-24 right-4 z-40 flex h-12 w-12 items-center justify-center rounded-full bg-[#25D366] text-white shadow-lg shadow-[#25D366]/40 ring-2 ring-white/10 transition-shadow hover:shadow-xl"
        >
          <MessageCircle className="h-5 w-5" />
        </motion.a>
      )}
    </div>
  );
};

export default AccountAboutCard;
