"use client";

import { useState } from "react";
import { useAuthStore, useAppStore } from "@/lib/store";
import { useApi, apiPost } from "@/lib/api";
import { Poster } from "../poster";
import { Spinner, EmptyState } from "../skeleton";
import { cn } from "@/lib/utils";
import { toPersianDigits, formatToman, formatViews } from "@/lib/poster";
import {
  User, Crown, Wallet, Heart, Clock, Monitor, Shield, LogOut, Mail, Lock, UserPlus,
  Tv, Film, Smartphone, Globe, Check, ChevronLeft, Gift, CreditCard, Smartphone as Phone,
} from "lucide-react";
import type { PosterItem } from "../poster";

interface ProfileViewProps {
  initialTab?: string;
}

export function ProfileView({ initialTab }: ProfileViewProps) {
  const user = useAuthStore((s) => s.user);
  const setUser = useAuthStore((s) => s.setUser);
  const logoutStore = useAuthStore((s) => s.logout);
  const navigate = useAppStore((s) => s.navigate);

  const [tab, setTab] = useState(initialTab ?? "overview");

  if (!user) return <AuthCard />;

  const tabs = [
    { id: "overview", label: "نمای کلی", icon: User },
    { id: "favorites", label: "علاقه‌مندی‌ها", icon: Heart },
    { id: "history", label: "تاریخچه تماشا", icon: Clock },
    { id: "wallet", label: "کیف پول", icon: Wallet },
    { id: "subscription", label: "اشتراک", icon: Crown },
    { id: "devices", label: "دستگاه‌ها", icon: Monitor },
    { id: "security", label: "امنیت", icon: Shield },
  ];

  const handleLogout = () => {
    logoutStore();
    try { localStorage.removeItem("peepbox_user"); } catch {}
    navigate("home");
  };

  return (
    <div className="px-4 md:px-8 py-6">
      {/* Header */}
      <div className="glass rounded-2xl p-5 mb-6 flex flex-col md:flex-row items-center md:items-start gap-4">
        <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-gradient-brand text-3xl font-black text-white shrink-0">
          {user.name.charAt(0)}
        </div>
        <div className="flex-1 text-center md:text-right">
          <div className="flex items-center gap-2 justify-center md:justify-start mb-1">
            <h1 className="text-2xl font-black">{user.name}</h1>
            {user.isAdmin && <span className="rounded-md bg-gradient-brand px-2 py-0.5 text-[10px] font-bold text-white">مدیر</span>}
          </div>
          <p className="text-sm text-muted-foreground mb-2">{user.email}</p>
          <div className="flex items-center gap-2 justify-center md:justify-start flex-wrap">
            <span className="inline-flex items-center gap-1 rounded-full bg-primary/20 text-primary px-3 py-1 text-xs font-bold">
              <Crown className="h-3 w-3" /> {user.planName}
            </span>
            <span className="inline-flex items-center gap-1 rounded-full glass px-3 py-1 text-xs">
              <Gift className="h-3 w-3" /> کد دعوت: {user.referralCode}
            </span>
            <button onClick={() => navigate("admin")} className="inline-flex items-center gap-1 rounded-full glass px-3 py-1 text-xs hover:bg-primary/20 transition">
              پنل مدیریت ←
            </button>
          </div>
        </div>
        <button onClick={handleLogout} className="inline-flex items-center gap-2 rounded-xl glass hover:bg-destructive/20 px-4 py-2 text-sm font-medium transition">
          <LogOut className="h-4 w-4" /> خروج
        </button>
      </div>

      <div className="grid md:grid-cols-[220px_1fr] gap-6">
        {/* Tabs */}
        <aside className="space-y-1 h-fit md:sticky md:top-20">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={cn("w-full flex items-center gap-2 rounded-xl px-3 py-2.5 text-sm font-medium transition", tab === t.id ? "bg-primary text-white" : "glass text-muted-foreground hover:text-white")}
            >
              <t.icon className="h-4 w-4" /> {t.label}
            </button>
          ))}
        </aside>

        {/* Content */}
        <div>
          {tab === "overview" && <OverviewTab user={user} />}
          {tab === "favorites" && <FavoritesTab />}
          {tab === "history" && <HistoryTab />}
          {tab === "wallet" && <WalletTab balance={user.walletBalance} />}
          {tab === "subscription" && <SubscriptionTab plan={user.planName} />}
          {tab === "devices" && <DevicesTab />}
          {tab === "security" && <SecurityTab />}
        </div>
      </div>
    </div>
  );
}

// ===================== Auth Card =====================
function AuthCard() {
  const setUser = useAuthStore((s) => s.setUser);
  const navigate = useAppStore((s) => s.navigate);
  const [mode, setMode] = useState<"login" | "register">("login");
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await apiPost<{ user: any }>(`/api/auth/${mode}`, mode === "login" ? { email, password } : { name, email, password });
      setUser(res.user);
      try { localStorage.setItem("peepbox_user", JSON.stringify(res.user)); } catch {}
      navigate("home");
    } catch (e: any) {
      setError(e?.message ?? "خطا");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-[70vh] flex items-center justify-center px-4">
      <div className="w-full max-w-md glass rounded-3xl p-6 md:p-8">
        <div className="text-center mb-6">
          <div className="inline-flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-brand mb-3 shadow-glow">
            <User className="h-7 w-7 text-white" />
          </div>
          <h1 className="text-2xl font-black">{mode === "login" ? "ورود به حساب" : "ساخت حساب جدید"}</h1>
          <p className="text-sm text-muted-foreground mt-1">به PeepBox خوش آمدید</p>
        </div>

        <div className="flex glass rounded-full p-1 mb-6">
          <button onClick={() => setMode("login")} className={cn("flex-1 rounded-full py-2 text-sm font-bold transition", mode === "login" ? "bg-primary text-white" : "text-muted-foreground")}>ورود</button>
          <button onClick={() => setMode("register")} className={cn("flex-1 rounded-full py-2 text-sm font-bold transition", mode === "register" ? "bg-primary text-white" : "text-muted-foreground")}>ثبت‌نام</button>
        </div>

        <form onSubmit={submit} className="space-y-3">
          {mode === "register" && (
            <div className="flex items-center glass rounded-xl px-3">
              <UserPlus className="h-4 w-4 text-muted-foreground ml-2" />
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="نام و نام خانوادگی" required className="bg-transparent flex-1 py-3 text-sm outline-none placeholder:text-muted-foreground" />
            </div>
          )}
          <div className="flex items-center glass rounded-xl px-3">
            <Mail className="h-4 w-4 text-muted-foreground ml-2" />
            <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder="ایمیل" required className="bg-transparent flex-1 py-3 text-sm outline-none placeholder:text-muted-foreground" />
          </div>
          <div className="flex items-center glass rounded-xl px-3">
            <Lock className="h-4 w-4 text-muted-foreground ml-2" />
            <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" placeholder="رمز عبور" required className="bg-transparent flex-1 py-3 text-sm outline-none placeholder:text-muted-foreground" />
          </div>
          {error && <p className="text-sm text-destructive text-center">{error}</p>}
          <button type="submit" disabled={loading} className="w-full rounded-xl bg-gradient-brand py-3 font-bold text-white hover:opacity-90 transition disabled:opacity-50 flex items-center justify-center gap-2">
            {loading ? <Spinner className="h-5 w-5" /> : mode === "login" ? "ورود" : "ساخت حساب"}
          </button>
        </form>

        <div className="mt-4 p-3 rounded-xl bg-accent/10 border border-accent/20 text-xs text-muted-foreground text-center">
          برای آزمایش با حساب مدیر وارد شوید: <span className="font-bold text-accent">admin@peepboxtv.me</span> (هر رمز عبوری)
        </div>
      </div>
    </div>
  );
}

// ===================== Tabs =====================
function OverviewTab({ user }: { user: any }) {
  const { data } = useApi<{ continueWatching: PosterItem[]; rows: { items: PosterItem[] }[] }>("/api/content/home");
  const stats = [
    { label: "اشتراک فعال", value: user.planName, icon: Crown, color: "#7C3AED" },
    { label: "موجودی کیف پول", value: formatToman(user.walletBalance), icon: Wallet, color: "#10B981" },
    { label: "علاقه‌مندی‌ها", value: toPersianDigits(12), icon: Heart, color: "#EC4899" },
    { label: "ساعت تماشا", value: `${toPersianDigits(47)} ساعت`, icon: Clock, color: "#22D3EE" },
  ];
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3">
        {stats.map((s) => (
          <div key={s.label} className="glass rounded-2xl p-4">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl mb-3" style={{ background: `${s.color}30` }}>
              <s.icon className="h-5 w-5" style={{ color: s.color }} />
            </div>
            <div className="text-xl font-black">{s.value}</div>
            <div className="text-xs text-muted-foreground">{s.label}</div>
          </div>
        ))}
      </div>
      {data && data.continueWatching.length > 0 && (
        <div className="glass rounded-2xl p-4">
          <h3 className="font-bold mb-3 flex items-center gap-2"><Clock className="h-4 w-4 text-accent" /> ادامه تماشا</h3>
          <div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
            {data.continueWatching.slice(0, 4).map((it, i) => <Poster key={i} item={it} className="w-full" />)}
          </div>
        </div>
      )}
      <div className="glass rounded-2xl p-4">
        <h3 className="font-bold mb-3 flex items-center gap-2"><Tv className="h-4 w-4 text-accent" /> پیشنهاد امروز PeepBox</h3>
        <div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
          {data?.rows?.[0]?.items?.slice(0, 4).map((it, i) => <Poster key={i} item={it} className="w-full" />)}
        </div>
      </div>
    </div>
  );
}

function FavoritesTab() {
  const { data } = useApi<{ rows: { items: PosterItem[] }[] }>("/api/content/home");
  const items = data?.rows?.flatMap((r) => r.items).slice(0, 8) ?? [];
  if (!data) return <Spinner />;
  return items.length ? (
    <div className="grid grid-cols-3 sm:grid-cols-4 gap-3">
      {items.map((it, i) => <Poster key={i} item={it} className="w-full" />)}
    </div>
  ) : <EmptyState icon={Heart} title="لیست علاقه‌مندی‌ها خالی است" subtitle="با علامت ❤ محتوا را اضافه کنید." />;
}

function HistoryTab() {
  const { data } = useApi<{ continueWatching: PosterItem[] }>("/api/content/home");
  if (!data) return <Spinner />;
  return data.continueWatching.length ? (
    <div className="space-y-2">
      {data.continueWatching.map((it, i) => (
        <div key={i} className="glass rounded-xl p-3 flex items-center gap-3">
          <Poster item={it} className="w-12 shrink-0" />
          <div className="flex-1 min-w-0">
            <div className="font-bold text-sm truncate">{it.persianTitle}</div>
            <div className="text-xs text-muted-foreground">{formatViews(it.views)} بازدید</div>
            <div className="mt-1 h-1 rounded-full bg-white/10 overflow-hidden"><div className="h-full bg-primary" style={{ width: `${it.progress ?? 30}%` }} /></div>
          </div>
          <button onClick={() => useAppStore.getState().navigate("watch", { contentType: it.type, contentSlug: it.slug })} className="rounded-lg bg-primary px-3 py-1.5 text-xs font-bold text-white">ادامه</button>
        </div>
      ))}
    </div>
  ) : <EmptyState icon={Clock} title="تاریخچه‌ای موجود نیست" />;
}

function WalletTab({ balance }: { balance: number }) {
  const [amount, setAmount] = useState(50000);
  const transactions = [
    { id: 1, type: "deposit", amount: 100000, desc: "افزایش موجودی - درگاه زرین‌پال", date: "۲ روز پیش" },
    { id: 2, type: "subscription", amount: -99000, desc: "تمدید اشتراک استاندارد", date: "۵ روز پیش" },
    { id: 3, type: "gift", amount: 20000, desc: "اعتبار هدیه ورود", date: "۱ هفته پیش" },
    { id: 4, type: "referral", amount: 15000, desc: "پورسانت دعوت دوست", date: "۲ هفته پیش" },
  ];
  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-5 bg-gradient-to-l from-primary/20 to-transparent">
        <div className="text-sm text-muted-foreground mb-1">موجودی فعلی</div>
        <div className="text-3xl font-black">{formatToman(balance)}</div>
      </div>
      <div className="glass rounded-2xl p-4">
        <h3 className="font-bold mb-3 flex items-center gap-2"><CreditCard className="h-4 w-4 text-accent" /> افزایش موجودی</h3>
        <div className="flex gap-2 mb-3 flex-wrap">
          {[50000, 100000, 200000, 500000].map((a) => (
            <button key={a} onClick={() => setAmount(a)} className={cn("rounded-lg px-3 py-1.5 text-sm font-medium transition", amount === a ? "bg-primary text-white" : "glass text-muted-foreground hover:text-white")}>{toPersianDigits(a.toLocaleString("en-US"))}</button>
          ))}
        </div>
        <button className="w-full rounded-xl bg-gradient-brand py-3 font-bold text-white hover:opacity-90 transition">پرداخت {toPersianDigits(amount.toLocaleString("en-US"))} تومان</button>
      </div>
      <div className="glass rounded-2xl p-4">
        <h3 className="font-bold mb-3">تراکنش‌های اخیر</h3>
        <div className="space-y-2">
          {transactions.map((t) => (
            <div key={t.id} className="flex items-center justify-between p-2 rounded-lg hover:bg-white/5">
              <div>
                <div className="text-sm font-medium">{t.desc}</div>
                <div className="text-xs text-muted-foreground">{t.date}</div>
              </div>
              <div className={cn("font-bold text-sm", t.amount > 0 ? "text-success" : "text-destructive")}>{t.amount > 0 ? "+" : ""}{toPersianDigits(Math.abs(t.amount).toLocaleString("en-US"))} ت</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function SubscriptionTab({ plan }: { plan: string }) {
  const navigate = useAppStore((s) => s.navigate);
  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-5 bg-gradient-to-l from-primary/20 to-transparent">
        <div className="flex items-center gap-2 mb-2"><Crown className="h-5 w-5 text-primary" /><span className="font-bold">اشتراک فعلی</span></div>
        <div className="text-2xl font-black">{plan}</div>
        <div className="text-sm text-muted-foreground mt-1">تاریخ انقضا: {toPersianDigits("۱۴۰۳/۰۹/۱۵")}</div>
      </div>
      <button onClick={() => navigate("subscription")} className="w-full rounded-xl bg-gradient-brand py-3 font-bold text-white hover:opacity-90 transition">ارتقا یا تغییر اشتراک</button>
      <div className="glass rounded-2xl p-4">
        <h3 className="font-bold mb-3">تاریخچه اشتراک</h3>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between p-2 rounded-lg bg-white/5"><span>استاندارد (ماهانه)</span><span className="text-muted-foreground">{toPersianDigits("۹۹,۰۰۰")} ت</span></div>
          <div className="flex justify-between p-2 rounded-lg"><span>پایه (ماهانه)</span><span className="text-muted-foreground">{toPersianDigits("۴۹,۰۰۰")} ت</span></div>
        </div>
      </div>
    </div>
  );
}

function DevicesTab() {
  const devices = [
    { name: "Chrome / Windows", type: "desktop", os: "Windows 11", last: "اکنون", current: true },
    { name: "PeepBox / Android", type: "mobile", os: "Android 14", last: "۲ ساعت پیش", current: false },
    { name: "Safari / iPhone", type: "mobile", os: "iOS 17", last: "دیروز", current: false },
    { name: "PeepBox / Smart TV", type: "tv", os: "Tizen", last: "۳ روز پیش", current: false },
  ];
  return (
    <div className="space-y-3">
      {devices.map((d, i) => (
        <div key={i} className="glass rounded-xl p-4 flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/20">
            {d.type === "mobile" ? <Phone className="h-5 w-5 text-primary" /> : d.type === "tv" ? <Tv className="h-5 w-5 text-primary" /> : <Monitor className="h-5 w-5 text-primary" />}
          </div>
          <div className="flex-1">
            <div className="font-bold text-sm flex items-center gap-2">{d.name} {d.current && <span className="rounded bg-success/20 text-success px-1.5 py-0.5 text-[9px] font-bold">فعلی</span>}</div>
            <div className="text-xs text-muted-foreground">{d.os} • آخرین فعالیت: {d.last}</div>
          </div>
          {!d.current && <button className="rounded-lg glass px-3 py-1.5 text-xs hover:bg-destructive/20 transition">خروج</button>}
        </div>
      ))}
      <button className="w-full rounded-xl glass hover:bg-destructive/20 py-3 text-sm font-medium transition">خروج از همه دستگاه‌ها</button>
    </div>
  );
}

function SecurityTab() {
  const [twoFA, setTwoFA] = useState(false);
  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-4">
        <h3 className="font-bold mb-3 flex items-center gap-2"><Lock className="h-4 w-4 text-accent" /> تغییر رمز عبور</h3>
        <div className="space-y-2">
          <input type="password" placeholder="رمز فعلی" className="w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none" />
          <input type="password" placeholder="رمز جدید" className="w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none" />
          <input type="password" placeholder="تکرار رمز جدید" className="w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none" />
          <button className="rounded-xl bg-primary px-4 py-2 text-sm font-bold text-white">ذخیره</button>
        </div>
      </div>
      <div className="glass rounded-2xl p-4 flex items-center justify-between">
        <div>
          <div className="font-bold text-sm flex items-center gap-2"><Shield className="h-4 w-4 text-accent" /> احراز هویت دو مرحله‌ای (۲FA)</div>
          <div className="text-xs text-muted-foreground mt-1">افزایش امنیت حساب با کد یکبار مصرف</div>
        </div>
        <button onClick={() => setTwoFA(!twoFA)} className={cn("relative h-7 w-12 rounded-full transition", twoFA ? "bg-primary" : "bg-white/20")}>
          <span className={cn("absolute top-1 h-5 w-5 rounded-full bg-white transition-all", twoFA ? "right-1" : "right-6")} />
        </button>
      </div>
      <div className="glass rounded-2xl p-4">
        <h3 className="font-bold mb-3">لاگ‌های امنیتی اخیر</h3>
        <div className="space-y-2 text-sm">
          {[
            { event: "ورود موفق", ip: "5.124.x.x", device: "Chrome / Windows", time: "۲ ساعت پیش", ok: true },
            { event: "ورود ناموفق", ip: "91.80.x.x", device: "ناشناس", time: "۵ ساعت پیش", ok: false },
            { event: "تغییر رمز", ip: "5.124.x.x", device: "Chrome / Windows", time: "دیروز", ok: true },
          ].map((l, i) => (
            <div key={i} className="flex items-center gap-2 p-2 rounded-lg bg-white/5">
              <span className={cn("h-2 w-2 rounded-full", l.ok ? "bg-success" : "bg-destructive")} />
              <span className="font-medium">{l.event}</span>
              <span className="text-xs text-muted-foreground">{l.ip} • {l.device}</span>
              <span className="text-xs text-muted-foreground mr-auto">{l.time}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
