import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import {
  User,
  Plus,
  Trash2,
  Edit2,
  Check,
  X,
  RefreshCw,
  Server,
  Loader2,
  Smartphone,
  Link2,
  ShieldCheck,
  Tv,
  Film,
  Clapperboard,
} from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";

import PageLayout from "@/components/PageLayout";
import AddServerDialog from "@/components/AddServerDialog";
import AccountAboutCard from "@/components/AccountAboutCard";
import AboutMenu from "@/components/AboutMenu";
import DeviceStatusCard from "@/components/DeviceStatusCard";
import EditAccountCard from "@/components/EditAccountCard";
import PremiumStatusCard from "@/components/PremiumStatusCard";
import RewardAdCard from "@/components/RewardAdCard";
import { useProfiles } from "@/hooks/useProfiles";
import { useReloadPlaylist } from "@/hooks/useXtreamData";
import { useConnectProfile } from "@/hooks/useConnectProfile";
import {
  getManagedProfileId,
  getManagedCounts,
} from "@/hooks/useSubscriberProfileSync";
import { useManagedCounts } from "@/hooks/useManagedCounts";
import { xtreamApi } from "@/lib/xtream";
import { UA_PRESETS, getUserAgent, setUserAgent } from "@/lib/userAgent";
import type { XtreamProfile } from "@/types/xtream";
import { useNavigate } from "react-router-dom";
import { FocusableButton, FocusableSection, setFocus } from "@/components/focusable";

const Account = () => {
  const { t } = useTranslation();
  const {
    profiles,
    ownedProfiles,
    sharedProfiles,
    activeProfileId,
    setActiveProfileId,
    updateProfile,
    removeProfile,
  } = useProfiles();
  const reload = useReloadPlaylist();
  const connect = useConnectProfile();
  const managedId = getManagedProfileId();
  const managedCounts = useManagedCounts();

  const [showAdd, setShowAdd] = useState(false);
  const [editing, setEditing] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<Partial<XtreamProfile>>({});
  const [testingId, setTestingId] = useState<string | null>(null);
  const [ua, setUa] = useState<string>(getUserAgent());
  const nav = useNavigate();

  // Land initial spatial focus on the top "Add Server" button so the
  // gold ring is exactly where the eye expects it — not buried deep
  // in the About menu (which is where norigin's "closest-to-origin"
  // heuristic was landing because that card mounts first).
  useEffect(() => {
    const tryFocus = () => {
      try {
        setFocus("account-add-server");
      } catch {
        /* spatial-nav not ready */
      }
    };
    const t1 = window.setTimeout(tryFocus, 150);
    const t2 = window.setTimeout(tryFocus, 450);
    return () => {
      window.clearTimeout(t1);
      window.clearTimeout(t2);
    };
  }, []);

  const startEdit = (p: XtreamProfile) => {
    setEditing(p.id);
    setEditForm({
      name: p.name,
      serverUrl: p.serverUrl,
      username: p.username,
      password: p.password,
    });
  };

  const saveEdit = (id: string) => {
    updateProfile(id, editForm);
    setEditing(null);
    toast.success(t("account.profileUpdated"));
  };

  const handleReload = (id: string) => {
    reload(id);
    toast.success(t("account.playlistReloaded"));
  };

  const handleTest = async (p: XtreamProfile) => {
    setTestingId(p.id);
    try {
      await xtreamApi.authenticate(p);
      toast.success(t("account.connectedSuccess", { name: p.name }));
    } catch (e: any) {
      toast.error(
        t("account.connectFailed", {
          name: p.name,
          error: e?.message ?? "Failed to connect",
        }),
      );
    } finally {
      setTestingId(null);
    }
  };

  const handleDelete = (id: string) => {
    // Samsung Tizen QA bans native confirm() — use sonner toast with an
    // action button instead.
    toast.warning(t("account.confirmDelete"), {
      action: {
        label: t("account.delete", { defaultValue: "Delete" }),
        onClick: () => {
          removeProfile(id);
          toast.success(t("account.profileRemoved"));
        },
      },
      duration: 8000,
    });
  };

  return (
    <PageLayout title={t("account.title")}>
      <FocusableSection
        focusKey="account-page"
        autoFocus
        className="h-full flex flex-col gap-3 max-w-2xl mx-auto w-full"
      >
        <div className="flex items-center justify-between">
          <p className="text-muted-foreground text-xs">
            {t("account.profilesCount", { count: ownedProfiles.length })}
          </p>
          <FocusableButton
            focusKey="account-add-server"
            onEnter={() => setShowAdd(true)}
            onClick={() => setShowAdd(true)}
            data-testid="account-add-server-btn"
            className="glass-card rounded-xl px-4 py-2 flex items-center gap-2 hover:border-primary/40 transition-all outline-none"
            focusClassName="border-primary/60 ring-2 ring-primary/40"
          >
            <Plus className="w-4 h-4 text-primary" />
            <span className="text-foreground text-xs font-medium">
              {t("account.addServer")}
            </span>
          </FocusableButton>
        </div>

        <div className="flex-1 overflow-y-auto space-y-3 pr-1">
          {/* ─── Premium status: gold badge, days remaining, expiry ─── */}
          <PremiumStatusCard />

          {/* ─── Reward Ads (iter-6, 2026-01): 3 rewarded ads → 1 hour ad-free ─── */}
          <RewardAdCard adsToWatch={3} hoursPerUnlock={1} />

          {/* ─── Device Pairing ─── */}
          <div
            className="glass-card rounded-2xl p-4"
            data-testid="device-pairing-section"
          >
            <div className="flex items-center gap-2 mb-2">
              <Link2 className="w-4 h-4 text-primary" />
              <p className="text-foreground text-sm font-medium">
                {t("account.devicePairing")}
              </p>
            </div>
            <p className="text-muted-foreground text-[11px] mb-3">
              {t("account.devicePairingDesc")}
            </p>
            <div className="flex gap-2">
              <FocusableButton
                focusKey="account-go-activate"
                onEnter={() => nav("/activate")}
                onClick={() => nav("/activate")}
                className="flex-1 text-[12px] px-3 py-2 rounded-lg glass hover:border-primary/40 text-foreground flex items-center justify-center gap-2 transition-all outline-none"
                focusClassName="border-primary/60 ring-2 ring-primary/40"
                data-testid="go-activate-btn"
              >
                <Smartphone className="w-3.5 h-3.5" /> {t("account.imOnDevice")}
              </FocusableButton>
              <FocusableButton
                focusKey="account-go-pair"
                onEnter={() => nav("/pair")}
                onClick={() => nav("/pair")}
                className="flex-1 text-[12px] px-3 py-2 rounded-lg glass hover:border-primary/40 text-foreground flex items-center justify-center gap-2 transition-all outline-none"
                focusClassName="border-primary/60 ring-2 ring-primary/40"
                data-testid="go-pair-btn"
              >
                <Link2 className="w-3.5 h-3.5" /> {t("account.iHavePin")}
              </FocusableButton>
            </div>

            {/* Current-device identity + unpair action (only rendered when a device row is cached locally). */}
            <DeviceStatusCard />
          </div>

          {/* ─── Help & About (app version, privacy, creator, WhatsApp) ─── */}
          <AccountAboutCard />

          {/* ─── Edit Account (logged-in users only, changes own username/password) ─── */}
          <EditAccountCard />

          {/* ─── Player Identity (User-Agent) ─── */}
          <div className="glass-card rounded-2xl p-4">
            <div className="flex items-center gap-2 mb-2">
              <Smartphone className="w-4 h-4 text-primary" />
              <p className="text-foreground text-sm font-medium">
                {t("account.playerIdentity")}
              </p>
            </div>
            <p className="text-muted-foreground text-[11px] mb-3">
              {t("account.playerIdentityDesc")}
            </p>
            <div className="flex flex-wrap gap-2">
              {UA_PRESETS.map((preset) => {
                const active = ua === preset.value;
                return (
                  <FocusableButton
                    key={preset.id}
                    focusKey={`account-ua-${preset.id}`}
                    onEnter={() => {
                      setUserAgent(preset.value);
                      setUa(preset.value);
                      toast.success(
                        t("account.userAgentSet", { name: preset.label }),
                      );
                    }}
                    onClick={() => {
                      setUserAgent(preset.value);
                      setUa(preset.value);
                      toast.success(
                        t("account.userAgentSet", { name: preset.label }),
                      );
                    }}
                    data-testid={`account-ua-${preset.id}`}
                    className={`text-[11px] px-3 py-1.5 rounded-lg transition-all outline-none ${
                      active
                        ? "bg-primary/20 text-primary border border-primary/40"
                        : "glass hover:border-primary/40 text-foreground"
                    }`}
                    focusClassName="ring-2 ring-primary/60 border-primary/60"
                  >
                    {preset.label}
                  </FocusableButton>
                );
              })}
            </div>
            <p className="text-muted-foreground text-[10px] mt-2 truncate">
              {t("account.sending")}: <span className="text-foreground/70">{ua}</span>
            </p>
          </div>

          {/* ─── My Playlists (Owned — user-added only) ─── */}
          <div className="glass-card rounded-2xl p-4" data-testid="owned-profiles-section">
            <div className="flex items-center gap-2 mb-3">
              <User className="w-4 h-4 text-primary" />
              <p className="text-foreground text-sm font-medium">
                {t("account.myPlaylists", "My Playlists")}
              </p>
              <span className="text-muted-foreground text-[10px] ml-auto">
                {ownedProfiles.length} {ownedProfiles.length === 1 ? "playlist" : "playlists"}
              </span>
            </div>

            {ownedProfiles.length === 0 ? (
              <div className="text-center py-6" data-testid="owned-profiles-empty">
                <Server className="w-8 h-8 text-muted-foreground/30 mx-auto mb-2" />
                <p className="text-foreground text-sm mb-1">
                  {t("account.noOwnedProfiles", "No playlists yet")}
                </p>
                <p className="text-muted-foreground text-xs mb-3">
                  {t("account.noOwnedProfilesDesc", "Add your own Xtream, M3U or Stalker playlist to get started.")}
                </p>
                <FocusableButton
                  focusKey="owned-profiles-add"
                  onEnter={() => setShowAdd(true)}
                  onClick={() => setShowAdd(true)}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-primary/20 text-primary hover:bg-primary/30 text-xs font-medium transition-all outline-none"
                  focusClassName="ring-2 ring-primary/60"
                  data-testid="owned-profiles-add-btn"
                >
                  <Plus className="w-4 h-4" />
                  {t("account.addPlaylist", "Add Playlist")}
                </FocusableButton>
              </div>
            ) : (
              <div className="space-y-2">
                {ownedProfiles.map((p) => {
                  const isActive = p.id === activeProfileId;
                  const isEditing = editing === p.id;
                  return (
                    <motion.div
                      key={p.id}
                      layout
                      data-testid="user-profile-card"
                      className={`glass rounded-2xl p-3 border ${
                        isActive ? "border-primary/40" : "border-transparent"
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        <div
                          className={`w-10 h-10 rounded-full glass flex items-center justify-center shrink-0 ${
                            isActive ? "border border-primary" : ""
                          }`}
                        >
                          <User
                            className={`w-5 h-5 ${
                              isActive ? "text-primary" : "text-muted-foreground"
                            }`}
                          />
                        </div>
                        <div className="flex-1 min-w-0 space-y-2">
                          {isEditing ? (
                            <>
                              {[
                                { key: "name", label: "profileName" },
                                { key: "serverUrl", label: "serverUrl" },
                                { key: "username", label: "username" },
                                { key: "password", label: "password" },
                              ].map(({ key, label }) => (
                                <input
                                  key={key}
                                  value={(editForm as any)[key] ?? ""}
                                  onChange={(e) =>
                                    setEditForm({
                                      ...editForm,
                                      [key]: e.target.value,
                                    })
                                  }
                                  placeholder={
                                    label === "profileName"
                                      ? t("account.profileName")
                                      : label === "serverUrl"
                                        ? t("account.serverUrl")
                                        : label === "username"
                                          ? t("common.username")
                                          : t("common.password")
                                  }
                                  className="w-full glass-input rounded-lg px-3 py-2 text-foreground text-xs outline-none"
                                />
                              ))}
                            </>
                          ) : (
                            <>
                              <p className="text-foreground text-sm font-medium truncate">
                                {p.name}
                              </p>
                              <p className="text-muted-foreground text-xs truncate">
                                {p.serverUrl}
                              </p>
                              <p className="text-muted-foreground text-[10px] truncate">
                                {t("account.user")}: {p.username}
                              </p>
                            </>
                          )}
                        </div>
                        <div className="flex flex-col gap-1.5 shrink-0">
                          {isEditing ? (
                            <>
                              <FocusableButton
                                focusKey={`owned-save-${p.id}`}
                                onEnter={() => saveEdit(p.id)}
                                onClick={() => saveEdit(p.id)}
                                className="w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40 outline-none"
                                focusClassName="ring-2 ring-primary/60"
                              >
                                <Check className="w-4 h-4 text-primary" />
                              </FocusableButton>
                              <FocusableButton
                                focusKey={`owned-cancel-${p.id}`}
                                onEnter={() => setEditing(null)}
                                onClick={() => setEditing(null)}
                                className="w-8 h-8 rounded-lg glass flex items-center justify-center outline-none"
                                focusClassName="ring-2 ring-primary/60"
                              >
                                <X className="w-4 h-4 text-muted-foreground" />
                              </FocusableButton>
                            </>
                          ) : (
                            <>
                              <FocusableButton
                                focusKey={`owned-edit-${p.id}`}
                                onEnter={() => startEdit(p)}
                                onClick={() => startEdit(p)}
                                className="w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40 outline-none"
                                focusClassName="ring-2 ring-primary/60"
                              >
                                <Edit2 className="w-3.5 h-3.5 text-muted-foreground" />
                              </FocusableButton>
                              <FocusableButton
                                focusKey={`owned-del-${p.id}`}
                                onEnter={() => handleDelete(p.id)}
                                onClick={() => handleDelete(p.id)}
                                className="w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-destructive/40 outline-none"
                                focusClassName="ring-2 ring-destructive/60"
                              >
                                <Trash2 className="w-3.5 h-3.5 text-destructive" />
                              </FocusableButton>
                            </>
                          )}
                        </div>
                      </div>
                      {!isEditing && (
                        <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/40">
                          <FocusableButton
                            focusKey={`owned-active-${p.id}`}
                            onEnter={() => !isActive && setActiveProfileId(p.id)}
                            onClick={() => setActiveProfileId(p.id)}
                            disabled={isActive}
                            className={`text-[11px] px-3 py-1.5 rounded-lg transition-all outline-none ${
                              isActive
                                ? "bg-primary/20 text-primary"
                                : "glass hover:border-primary/40 text-foreground"
                            }`}
                            focusClassName="ring-2 ring-primary/60"
                          >
                            {isActive ? t("common.active") : t("common.setActive")}
                          </FocusableButton>
                          <FocusableButton
                            focusKey={`owned-test-${p.id}`}
                            onEnter={() => handleTest(p)}
                            onClick={() => handleTest(p)}
                            disabled={testingId === p.id}
                            loading={testingId === p.id}
                            className="text-[11px] px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground flex items-center gap-1.5 outline-none"
                            focusClassName="ring-2 ring-primary/60"
                          >
                            {testingId === p.id ? (
                              <Loader2 className="w-3 h-3 animate-spin" />
                            ) : null}{" "}
                            {t("common.test")}
                          </FocusableButton>
                          <FocusableButton
                            focusKey={`owned-reload-${p.id}`}
                            onEnter={() => handleReload(p.id)}
                            onClick={() => handleReload(p.id)}
                            className="text-[11px] px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground flex items-center gap-1.5 outline-none"
                            focusClassName="ring-2 ring-primary/60"
                          >
                            <RefreshCw className="w-3 h-3" /> {t("account.reloadPlaylist")}
                          </FocusableButton>
                        </div>
                      )}
                    </motion.div>
                  );
                })}
              </div>
            )}
          </div>

          {/* ─── Shared / Admin-Managed Profiles ─── */}
          {sharedProfiles.length > 0 && (
            <div className="glass-card rounded-2xl p-4" data-testid="shared-profiles-section">
              <div className="flex items-center gap-2 mb-3">
                <ShieldCheck className="w-4 h-4 text-primary" />
                <p className="text-foreground text-sm font-medium">
                  {t("account.sharedProfiles", "Shared Profiles")}
                </p>
                <span className="text-muted-foreground text-[10px] ml-auto">
                  {t("account.managedByAdmin", "Managed by admin")}
                </span>
              </div>
              <div className="space-y-2">
                {sharedProfiles.map((p) => {
                  const isActive = p.id === activeProfileId;
                  return (
                    <motion.div
                      key={p.id}
                      layout
                      data-testid="managed-profile-card"
                      className={`glass rounded-2xl p-3 border ${
                        isActive ? "border-primary/40" : "border-transparent"
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        <div
                          className={`w-10 h-10 rounded-full glass flex items-center justify-center shrink-0 ${
                            isActive ? "border border-primary" : ""
                          }`}
                        >
                          <ShieldCheck
                            className={`w-5 h-5 ${
                              isActive ? "text-primary" : "text-muted-foreground"
                            }`}
                          />
                        </div>
                        <div className="flex-1 min-w-0 space-y-2">
                          <p className="text-foreground text-sm font-medium truncate">
                            {p.name}
                          </p>
                          <div className="flex items-center gap-1.5 text-[10px] text-primary">
                            <ShieldCheck className="w-3 h-3" />
                            <span>Managed by admin</span>
                          </div>
                          <div className="flex flex-wrap gap-3 pt-1" data-testid="managed-counts">
                            <span className="inline-flex items-center gap-1 text-[11px] text-foreground/80">
                              <Tv className="w-3 h-3 text-primary" />
                              <span className="tabular-nums">
                                {managedCounts?.channels ?? "—"}
                              </span>
                              <span className="text-muted-foreground">TV</span>
                            </span>
                            <span className="inline-flex items-center gap-1 text-[11px] text-foreground/80">
                              <Film className="w-3 h-3 text-primary" />
                              <span className="tabular-nums">
                                {managedCounts?.movies ?? "—"}
                              </span>
                              <span className="text-muted-foreground">Movies</span>
                            </span>
                            <span className="inline-flex items-center gap-1 text-[11px] text-foreground/80">
                              <Clapperboard className="w-3 h-3 text-primary" />
                              <span className="tabular-nums">
                                {managedCounts?.series ?? "—"}
                              </span>
                              <span className="text-muted-foreground">Series</span>
                            </span>
                          </div>
                        </div>
                      </div>
                      <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/40">
                        <FocusableButton
                          focusKey={`shared-active-${p.id}`}
                          onEnter={() => !isActive && setActiveProfileId(p.id)}
                          onClick={() => setActiveProfileId(p.id)}
                          disabled={isActive}
                          className={`text-[11px] px-3 py-1.5 rounded-lg transition-all outline-none ${
                            isActive
                              ? "bg-primary/20 text-primary"
                              : "glass hover:border-primary/40 text-foreground"
                          }`}
                          focusClassName="ring-2 ring-primary/60"
                        >
                          {isActive ? t("common.active") : t("common.setActive")}
                        </FocusableButton>
                        <FocusableButton
                          focusKey={`shared-test-${p.id}`}
                          onEnter={() => handleTest(p)}
                          onClick={() => handleTest(p)}
                          disabled={testingId === p.id}
                          loading={testingId === p.id}
                          data-testid="managed-profile-test-btn"
                          className="text-[11px] px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground flex items-center gap-1.5 outline-none"
                          focusClassName="ring-2 ring-primary/60"
                        >
                          {testingId === p.id ? (
                            <Loader2 className="w-3 h-3 animate-spin" />
                          ) : null}{" "}
                          {t("common.test")}
                        </FocusableButton>
                        <FocusableButton
                          focusKey={`shared-reload-${p.id}`}
                          onEnter={() => handleReload(p.id)}
                          onClick={() => handleReload(p.id)}
                          className="text-[11px] px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground flex items-center gap-1.5 outline-none"
                          focusClassName="ring-2 ring-primary/60"
                        >
                          <RefreshCw className="w-3 h-3" /> {t("account.reloadPlaylist")}
                        </FocusableButton>
                      </div>
                    </motion.div>
                  );
                })}
              </div>
            </div>
          )}

          {/* ─── FEATURE (2026-01): About menu — the LAST card on the
                Account page. Surfaces App Version, Privacy Policy,
                Terms & Conditions, Contact Us (mailto), Rate Us
                (Play Store). Privacy + Terms text is admin-editable
                via /admin → Support & Privacy. ─── */}
          <AboutMenu />
        </div>
      </FocusableSection>

      <AddServerDialog
        open={showAdd}
        onClose={() => setShowAdd(false)}
        onSubmit={async (data) => {
          const created = await connect(data);
          if (created) setShowAdd(false);
        }}
      />
    </PageLayout>
  );
};

export default Account;
