"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";

interface Profile {
  id: string;
  slug: string;
  display_name: string;
  bio: string | null;
  avatar_url: string | null;
}

interface Product {
  id: string;
  title: string;
  description: string | null;
  url: string;
  image_url: string | null;
  category: string;
  display_order: number;
}

const CATEGORY_EMOJI: Record<string, string> = { feeding: "🍼", sleep: "💤", play: "🎮", clothing: "👗", general: "🛍️" };

export default function MamaPage() {
  const params = useParams();
  const slug = params.slug as string;
  const [profile, setProfile] = useState<Profile | null>(null);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    fetch(`/api/profile/${slug}`)
      .then(r => {
        if (!r.ok) { setNotFound(true); setLoading(false); return null; }
        return r.json();
      })
      .then(d => {
        if (!d) return;
        setProfile(d.profile);
        setProducts(d.products || []);
        setLoading(false);
      })
      .catch(() => { setNotFound(true); setLoading(false); });
  }, [slug]);

  async function handleClick(productId: string, url: string) {
    try {
      await fetch(`/api/profile/${slug}/click`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ productId }),
      });
    } catch {}
    window.open(url, "_blank", "noopener,noreferrer");
  }

  if (loading) return (
    <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-pink-50 to-purple-50">
      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-pink-400" />
    </div>
  );

  if (notFound || !profile) return (
    <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-pink-50 to-purple-50">
      <div className="text-center">
        <div className="text-5xl mb-4">🍼</div>
        <h1 className="text-xl font-bold text-gray-700">Page not found</h1>
        <p className="text-gray-500 text-sm mt-2">This profile doesn&apos;t exist or is private.</p>
      </div>
    </div>
  );

  const initials = profile.display_name.split(" ").map((w: string) => w[0]).join("").slice(0, 2).toUpperCase();

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-50 via-purple-50 to-rose-50">
      <div className="max-w-2xl mx-auto px-4 py-10">
        {/* Profile header */}
        <div className="text-center mb-10">
          <div className="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center text-2xl font-bold text-white shadow-lg"
            style={{ background: "linear-gradient(135deg, #f472b6, #a78bfa)" }}>
            {profile.avatar_url
              ? <img src={profile.avatar_url} alt={profile.display_name} className="w-20 h-20 rounded-full object-cover" />
              : initials
            }
          </div>
          <h1 className="text-2xl font-bold text-gray-900">{profile.display_name}</h1>
          {profile.bio && <p className="text-gray-500 mt-2 max-w-xs mx-auto text-sm">{profile.bio}</p>}
        </div>

        {/* Products */}
        {products.length > 0 && (
          <>
            <h2 className="text-lg font-bold text-gray-800 mb-4 text-center">Products I Love 💕</h2>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
              {products.map(p => (
                <div key={p.id} className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-md transition-shadow">
                  <div className={`h-32 flex items-center justify-center text-4xl ${
                    p.image_url ? "" : "bg-gradient-to-br from-pink-100 to-purple-100"
                  }`}>
                    {p.image_url
                      ? <img src={p.image_url} alt={p.title} className="h-32 w-full object-cover" />
                      : CATEGORY_EMOJI[p.category] || "🛍️"
                    }
                  </div>
                  <div className="p-3">
                    <p className="font-medium text-gray-900 text-sm line-clamp-2">{p.title}</p>
                    {p.description && (
                      <p className="text-xs text-gray-500 mt-1 line-clamp-2">{p.description}</p>
                    )}
                    <div className="flex items-center justify-between mt-2">
                      <span className="text-xs text-gray-400">{CATEGORY_EMOJI[p.category]}</span>
                      <button
                        onClick={() => handleClick(p.id, p.url)}
                        className="text-xs font-semibold text-pink-600 hover:text-pink-700"
                      >
                        Shop →
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}

        {products.length === 0 && (
          <p className="text-center text-gray-400 py-8">No recommendations yet.</p>
        )}

        {/* Footer */}
        <p className="text-center text-xs text-gray-400 mt-12">Made with Tia 👶</p>
      </div>
    </div>
  );
}
