"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter, useParams } from "next/navigation";
import {
  ArrowLeft,
  Star,
  User,
  ShoppingBag,
  Clock,
  Loader2,
} from "lucide-react";

// ── Types ─────────────────────────────────────────────────────────────────────

interface SellerListing {
  id: string;
  title: string;
  description: string;
  category: string;
  subcategory: string | null;
  priceFlh: number;
  packages: string | null;
  tags: string | null;
  images: string | null;
  deliveryDays: number | null;
  rating: number;
  reviewCount: number;
  salesCount: number;
  status: string;
  createdAt: string;
  seller: {
    id: string;
    name: string;
    email: string;
    avatar: string | null;
  };
}

interface SellerProfile {
  id: string;
  name: string;
  email: string;
  avatar: string | null;
  memberSince: string;
  listingsCount: number;
  averageRating: number;
  reviewCount: number;
  salesCount: number;
  listings: SellerListing[];
}

// ── Helpers ────────────────────────────────────────────────────────────────────

function getInitials(name: string): string {
  return name
    .split(" ")
    .map((n) => n.charAt(0).toUpperCase())
    .slice(0, 2)
    .join("");
}

function renderStars(rating: number) {
  const full = Math.floor(rating);
  const half = rating - full >= 0.5;
  const empty = 5 - full - (half ? 1 : 0);
  return (
    <span className="inline-flex items-center gap-0.5">
      {"★".repeat(full)}
      {half && "½"}
      {"☆".repeat(empty)}
    </span>
  );
}

const CATEGORY_VISUALS: Record<string, { emoji: string; bg: string }> = {
  "graphics-design":       { emoji: "🎨", bg: "from-pink-900/40 to-pink-800/20" },
  "digital-marketing":     { emoji: "📈", bg: "from-emerald-900/40 to-emerald-800/20" },
  "writing-translation":   { emoji: "✍️", bg: "from-amber-900/40 to-amber-800/20" },
  "video-animation":       { emoji: "🎬", bg: "from-red-900/40 to-red-800/20" },
  "music-audio":           { emoji: "🎵", bg: "from-purple-900/40 to-purple-800/20" },
  "programming-tech":      { emoji: "💻", bg: "from-blue-900/40 to-blue-800/20" },
  "ai-services":           { emoji: "🤖", bg: "from-cyan-900/40 to-cyan-800/20" },
  "consulting":            { emoji: "💼", bg: "from-slate-700/40 to-slate-600/20" },
  "data":                  { emoji: "📊", bg: "from-teal-900/40 to-teal-800/20" },
  "business":              { emoji: "🏢", bg: "from-indigo-900/40 to-indigo-800/20" },
  "personal-growth":       { emoji: "🌱", bg: "from-lime-900/40 to-lime-800/20" },
  "photography":           { emoji: "📷", bg: "from-orange-900/40 to-orange-800/20" },
  "finance":               { emoji: "💰", bg: "from-yellow-900/40 to-yellow-800/20" },
};

function listingVisual(cat?: string): { emoji: string; bg: string } {
  if (cat && CATEGORY_VISUALS[cat]) return CATEGORY_VISUALS[cat];
  return { emoji: "🛍️", bg: "from-gray-800/40 to-gray-700/20" };
}

function formatFlh(amount: number): string {
  if (amount >= 1_000_000) return `FLH ${(amount / 1_000_000).toFixed(1)}M`;
  if (amount >= 1_000) return `FLH ${(amount / 1_000).toFixed(1)}K`;
  return `FLH ${amount.toLocaleString()}`;
}

// ── Listing Card (same style as browse page) ──────────────────────────────────

function ListingCard({
  listing,
  router,
}: {
  listing: SellerListing;
  router: ReturnType<typeof useRouter>;
}) {
  const vis = listingVisual(listing.category);
  const rating = listing.rating ?? 0;

  return (
    <button
      onClick={() => router.push(`/souq/${listing.id}`)}
      className="bg-[#111118] border border-gray-800/60 rounded-2xl overflow-hidden text-left active:scale-[0.97] transition"
    >
      <div className={`h-24 bg-gradient-to-br ${vis.bg} flex items-center justify-center`}>
        <span className="text-3xl">{vis.emoji}</span>
      </div>
      <div className="p-3 space-y-1">
        <p className="text-sm font-semibold text-white leading-tight line-clamp-2 min-h-[2.5rem]">
          {listing.title}
        </p>
        <div className="flex items-center gap-1">
          <span className="text-[11px] text-amber-400">{renderStars(rating)}</span>
          {rating > 0 && <span className="text-[10px] text-gray-600">{rating.toFixed(1)}</span>}
        </div>
        <div className="flex items-center justify-between pt-0.5">
          <p className="text-sm font-bold text-[#D4AF37]">
            {formatFlh(listing.priceFlh)}
          </p>
          {listing.deliveryDays ? (
            <span className="flex items-center gap-0.5 text-[10px] text-gray-500">
              <Clock size={9} /> {listing.deliveryDays}d
            </span>
          ) : null}
        </div>
      </div>
    </button>
  );
}

// ── Page Component ────────────────────────────────────────────────────────────

export default function SellerProfilePage() {
  const { user, token, loading } = useAuth();
  const router = useRouter();
  const params = useParams();
  const sellerId = params?.id as string;

  const [seller, setSeller] = useState<SellerProfile | null>(null);
  const [fetching, setFetching] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!loading && !token) router.push("/auth");
  }, [loading, token, router]);

  useEffect(() => {
    if (!token || !sellerId) return;
    setFetching(true);
    setError(null);
    fetch(`/mobile/api/souq/sellers/${sellerId}`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => {
        if (!r.ok) throw new Error("Seller not found");
        return r.json();
      })
      .then((data) => setSeller(data.seller))
      .catch((err) => setError(err.message))
      .finally(() => setFetching(false));
  }, [token, sellerId]);

  if (loading) {
    return (
      <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
      </div>
    );
  }

  if (!user) return null;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-36">
      {/* ── Header ──────────────────────────────────────────────────────── */}
      <div className="sticky top-0 z-20 bg-[#0a0a0f]/90 backdrop-blur-lg border-b border-gray-800/40">
        <div className="flex items-center gap-3 px-4 h-14">
          <button
            onClick={() => router.back()}
            className="w-9 h-9 rounded-xl bg-[#111118] border border-gray-800/60 flex items-center justify-center active:scale-90 transition"
          >
            <ArrowLeft size={16} className="text-gray-400" />
          </button>
          <h1 className="text-sm font-semibold text-white">Seller Profile</h1>
        </div>
      </div>

      <div className="px-4 pt-5 space-y-5">
        {fetching ? (
          <div className="flex flex-col items-center justify-center py-20">
            <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin mb-3" />
            <p className="text-xs text-gray-600">Loading seller…</p>
          </div>
        ) : error || !seller ? (
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-8 text-center">
            <User size={32} className="mx-auto text-gray-700 mb-3" />
            <p className="text-sm text-gray-500">{error || "Seller not found"}</p>
            <button
              onClick={() => router.back()}
              className="mt-4 text-xs text-[#D4AF37] underline underline-offset-2"
            >
              Go back
            </button>
          </div>
        ) : (
          <>
            {/* ── Seller Info Card ────────────────────────────────────────── */}
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
              <div className="flex items-center gap-4 mb-5">
                {seller.avatar ? (
                  <img
                    src={seller.avatar}
                    alt={seller.name}
                    className="w-16 h-16 rounded-full object-cover"
                  />
                ) : (
                  <div className="w-16 h-16 rounded-full bg-gradient-to-br from-[#D4AF37]/20 to-gray-800/60 flex items-center justify-center text-xl font-bold text-[#D4AF37]">
                    {getInitials(seller.name)}
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <h2 className="text-lg font-bold text-white truncate">
                    {seller.name}
                  </h2>
                  <p className="text-xs text-gray-500 mt-0.5 flex items-center gap-1.5">
                    <Clock size={11} className="text-gray-600" />
                    Member since{" "}
                    {new Date(seller.memberSince).toLocaleDateString("en-US", {
                      month: "long",
                      year: "numeric",
                    })}
                  </p>
                </div>
              </div>

              {/* Stats grid */}
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-gray-800/30 rounded-xl px-3 py-3 text-center">
                  <div className="flex items-center justify-center gap-1 text-[#D4AF37] mb-0.5">
                    <Star size={13} className="fill-[#D4AF37]" />
                    <span className="text-lg font-bold text-white">
                      {seller.averageRating.toFixed(1)}
                    </span>
                  </div>
                  <p className="text-[10px] text-gray-500">Rating</p>
                </div>

                <div className="bg-gray-800/30 rounded-xl px-3 py-3 text-center">
                  <p className="text-lg font-bold text-white">
                    {seller.reviewCount}
                  </p>
                  <p className="text-[10px] text-gray-500">
                    {seller.reviewCount === 1 ? "Review" : "Reviews"}
                  </p>
                </div>

                <div className="bg-gray-800/30 rounded-xl px-3 py-3 text-center">
                  <p className="text-lg font-bold text-white">
                    {seller.salesCount}
                  </p>
                  <p className="text-[10px] text-gray-500">
                    {seller.salesCount === 1 ? "Sale" : "Sales"}
                  </p>
                </div>
              </div>
            </div>

            {/* ── Listings Section ─────────────────────────────────────────── */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-semibold text-white flex items-center gap-2">
                  <ShoppingBag size={14} className="text-[#D4AF37]" />
                  Services by this seller
                </h3>
                <span className="text-xs text-gray-600">
                  {seller.listingsCount} item
                  {seller.listingsCount !== 1 ? "s" : ""}
                </span>
              </div>

              {seller.listings.length === 0 ? (
                <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-8 text-center">
                  <ShoppingBag size={28} className="mx-auto text-gray-700 mb-2" />
                  <p className="text-sm text-gray-500">No active services yet</p>
                </div>
              ) : (
                <div className="grid grid-cols-2 gap-3">
                  {seller.listings.map((listing) => (
                    <ListingCard
                      key={listing.id}
                      listing={listing}
                      router={router}
                    />
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
