"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
  User,
  ShoppingBag,
  Heart,
  Clock,
  Settings,
  ChevronRight,
  Store,
  Package,
  MapPin,
  Mail,
  Phone,
  BadgeCheck,
  Wallet,
} from "lucide-react";
import Cookies from "js-cookie";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import { useAppSelector } from "@/store/hooks";

/* ─── API shape ──────────────────────────────────────────────────────────────── */
interface ProfileData {
  id: number;
  channel_id: string;
  channel_name: string;
  full_name: string;
  email: string;
  country_code: string;
  mobile_number: string;
  image: string;
  cover_img?: string;
  description?: string;
  city?: string;
  state?: string;
  address?: string;
  wallet_balance?: number;
  wallet_amount?: string;
  is_account_verify?: number;
  total_content?: number;
  total_subscriber?: number;
  reference_code?: string;
  created_at?: string;
}

/* ─── Menu items ─────────────────────────────────────────────────────────────── */
const MENU_ITEMS = [
  { icon: ShoppingBag, label: "My Orders", href: "/marketplace/orders" },
  { icon: Heart, label: "Wishlist", href: "/marketplace/wishlist" },
  { icon: Store, label: "My Listings", href: "/marketplace/seller/listings" },
  {
    icon: Package,
    label: "Seller Dashboard",
    href: "/marketplace/seller/dashboard",
  },
  { icon: Clock, label: "Recently Viewed", href: "/marketplace/history" },
  { icon: Settings, label: "Settings", href: "/marketplace/settings" },
];

/* ─── Skeleton ───────────────────────────────────────────────────────────────── */
function ProfileSkeleton() {
  return (
    <div className="p-4 md:p-6  mx-auto animate-pulse space-y-4">
      <div
        className="rounded-2xl p-5 flex items-center gap-4"
        style={{ background: "var(--card)", border: "1px solid var(--border)" }}
      >
        <div
          className="w-16 h-16 rounded-full"
          style={{ background: "var(--deep)" }}
        />
        <div className="flex-1 space-y-2">
          <div
            className="h-4 w-32 rounded"
            style={{ background: "var(--deep)" }}
          />
          <div
            className="h-3 w-44 rounded"
            style={{ background: "var(--deep)" }}
          />
          <div
            className="h-3 w-24 rounded"
            style={{ background: "var(--deep)" }}
          />
        </div>
      </div>
      <div className="grid grid-cols-3 gap-3">
        {[0, 1, 2].map((i) => (
          <div
            key={i}
            className="rounded-2xl p-3 h-16"
            style={{
              background: "var(--card)",
              border: "1px solid var(--border)",
            }}
          />
        ))}
      </div>
      <div
        className="rounded-2xl overflow-hidden"
        style={{ border: "1px solid var(--border)" }}
      >
        {MENU_ITEMS.map((_, i) => (
          <div
            key={i}
            className="h-12 px-4 flex items-center gap-3"
            style={{
              background: "var(--card)",
              borderBottom:
                i < MENU_ITEMS.length - 1 ? "1px solid var(--border)" : "none",
            }}
          >
            <div
              className="w-4 h-4 rounded"
              style={{ background: "var(--deep)" }}
            />
            <div
              className="h-3 w-28 rounded"
              style={{ background: "var(--deep)" }}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── Component ──────────────────────────────────────────────────────────────── */
export function MarketplaceProfile() {
  const router = useRouter();
  const authUser = useAppSelector((s) => s.auth.user);
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);

  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const userId = Cookies.get("user_id");
    if (!userId) {
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    apiClient
      .post(API_ENDPOINTS.AUTH.PROFILE, { to_user_id: userId })
      .then((res) => {
        const data = res.data?.result?.[0];
        if (data) setProfile(data);
        else setError("Could not load profile.");
      })
      .catch(() => setError("Failed to load profile. Please try again."))
      .finally(() => setIsLoading(false));
  }, []);

  if (isLoading) return <ProfileSkeleton />;

  /* Fallback to Redux auth user if API failed */
  const name = profile?.full_name ?? authUser?.full_name ?? "—";
  const email = profile?.email ?? authUser?.email ?? "";
  const phone = profile?.mobile_number ?? authUser?.mobile_number ?? "";
  const countryCode = profile?.country_code ?? authUser?.country_code ?? "";
  const avatar = profile?.image ?? authUser?.image ?? "";
  const channelName = profile?.channel_name ?? authUser?.channel_name ?? "";
  const description = profile?.description ?? authUser?.description ?? "";
  const city = profile?.city ?? authUser?.city ?? "";
  const state = profile?.state ?? authUser?.state ?? "";
  const walletAmount = parseFloat(profile?.wallet_amount ?? "0") || 0;
  const verified =
    (profile?.is_account_verify ?? authUser?.is_account_verify ?? 0) === 1;
  const totalContent = profile?.total_content ?? 0;
  const totalSubscriber = profile?.total_subscriber ?? 0;
  const location = [city, state].filter(Boolean).join(", ");

  const isDefaultAvatar =
    !avatar || avatar.includes("default.png") || avatar.includes("no_img");

  return (
    <div className="p-4 md:p-6  mx-auto space-y-4">
      {error && (
        <div
          className="text-xs px-3 py-2 rounded-xl"
          style={{
            background: "rgba(252,0,0,0.07)",
            color: "var(--accent)",
            border: "1px solid rgba(252,0,0,0.15)",
          }}
        >
          {error} Showing cached data.
        </div>
      )}

      {/* Profile card */}
      <div
        className="rounded-2xl overflow-hidden"
        style={{ background: "var(--card)", border: "1px solid var(--border)" }}
      >
        {/* Cover */}
        <div
          className="h-20 w-full"
          style={{
            background:
              "linear-gradient(135deg, rgba(252,0,0,0.18) 0%, rgba(252,0,0,0.06) 100%)",
          }}
        />

        {/* Avatar + info */}
        <div className="px-5 pb-5">
          <div className="flex items-end justify-between -mt-8 mb-3">
            <div
              className="w-16 h-16 rounded-full border-2 overflow-hidden flex items-center justify-center flex-shrink-0"
              style={{ background: "var(--deep)", borderColor: "var(--card)" }}
            >
              {isDefaultAvatar ? (
                <User size={28} style={{ color: "var(--text-muted)" }} />
              ) : (
                /* eslint-disable-next-line @next/next/no-img-element */
                <img
                  src={avatar}
                  alt={name}
                  className="w-full h-full object-cover"
                />
              )}
            </div>
            <button
              onClick={() => router.push("/marketplace/settings")}
              className="flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-lg border transition-all"
              style={{
                borderColor: "var(--border)",
                color: "var(--text-muted)",
                background: "var(--deep)",
              }}
            >
              <Settings size={12} />
              Edit Profile
            </button>
          </div>

          {/* Name + verification */}
          <div className="flex items-center gap-1.5 mb-0.5">
            <p
              className="text-base font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              {name}
            </p>
            {verified && <BadgeCheck size={15} style={{ color: "#3b82f6" }} />}
          </div>

          {/* Channel name */}
          {channelName && (
            <p
              className="text-xs font-medium mb-2"
              style={{ color: "var(--accent)" }}
            >
              {channelName}
            </p>
          )}

          {/* Description */}
          {description && description !== "Hey, I am user on DoliPlay App." && (
            <p
              className="text-xs leading-relaxed mb-3"
              style={{ color: "var(--text-muted)" }}
            >
              {description}
            </p>
          )}

          {/* Contact info */}
          <div className="space-y-1.5">
            {email && (
              <div
                className="flex items-center gap-2 text-xs"
                style={{ color: "var(--text-muted)" }}
              >
                <Mail size={12} style={{ color: "var(--accent)" }} />
                {email}
              </div>
            )}
            {phone && (
              <div
                className="flex items-center gap-2 text-xs"
                style={{ color: "var(--text-muted)" }}
              >
                <Phone size={12} style={{ color: "var(--accent)" }} />
                {countryCode} {phone}
              </div>
            )}
            {location && (
              <div
                className="flex items-center gap-2 text-xs"
                style={{ color: "var(--text-muted)" }}
              >
                <MapPin size={12} style={{ color: "var(--accent)" }} />
                {location}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: "Listings", value: totalContent },
          { label: "Subscribers", value: totalSubscriber },
          {
            label: "Withdrawable",
            value: `${currencyCode}${walletAmount.toFixed(2)}`,
            small: true,
          },
        ].map((s) => (
          <div
            key={s.label}
            className="rounded-2xl p-3 text-center"
            style={{
              background: "var(--card)",
              border: "1px solid var(--border)",
            }}
          >
            <p
              className={`font-bold ${s.small ? "text-base" : "text-xl"}`}
              style={{
                color:
                  s.label === "Withdrawable"
                    ? "var(--accent)"
                    : "var(--text-primary)",
              }}
            >
              {s.value}
            </p>
            <p
              className="text-xs mt-0.5"
              style={{ color: "var(--text-muted)" }}
            >
              {s.label}
            </p>
          </div>
        ))}
      </div>

      {/* Wallet balance detail */}
      <div
        className="rounded-2xl px-4 py-3 flex items-center gap-3"
        style={{ background: "var(--card)", border: "1px solid var(--border)" }}
      >
        <div
          className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
          style={{ background: "rgba(252,0,0,0.1)" }}
        >
          <Wallet size={16} className="text-[#fc0000]" />
        </div>
        <div className="flex-1 min-w-0">
          <p
            className="text-xs font-semibold"
            style={{ color: "var(--text-muted)" }}
          >
            Withdrawable Amount
          </p>
          <p
            className="text-base font-black"
            style={{ color: "var(--text-primary)" }}
          >
            {currencyCode}{walletAmount.toFixed(2)}
          </p>
        </div>
        <button
          onClick={() => router.push("/wallet")}
          className="text-xs font-bold px-3 py-1.5 rounded-lg"
          style={{ background: "rgba(252,0,0,0.08)", color: "var(--accent)" }}
        >
          View
        </button>
      </div>

      {/* Menu */}
      <div
        className="rounded-2xl overflow-hidden"
        style={{ border: "1px solid var(--border)" }}
      >
        {MENU_ITEMS.map((item, i) => (
          <button
            key={item.href}
            onClick={() => router.push(item.href)}
            className="w-full flex items-center gap-3 px-4 py-3.5 hover:opacity-80 transition-opacity"
            style={{
              background: "var(--card)",
              borderBottom:
                i < MENU_ITEMS.length - 1 ? "1px solid var(--border)" : "none",
            }}
          >
            <item.icon size={17} style={{ color: "var(--text-muted)" }} />
            <span
              className="flex-1 text-left text-sm"
              style={{ color: "var(--text-primary)" }}
            >
              {item.label}
            </span>
            <ChevronRight size={14} style={{ color: "var(--text-muted)" }} />
          </button>
        ))}
      </div>
    </div>
  );
}
