"use client";

import React, { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import AppImage from "@/components/ui/AppImage";

interface ForumUserProfile {
  username: string;
  display_name: string;
  bio: string | null;
  avatar_url: string | null;
  role_title: string | null;
  company: string | null;
  location_city: string | null;
  location_country: string | null;
  years_experience: number | null;
  expertise_level: string | null;
  expertise_tags: string[];
  signature: string | null;
  join_date: string | null;
  last_seen_at: string | null;
  thread_count: number;
  reply_count: number;
  post_count: number;
}

interface UserThread {
  id: string;
  title: string;
  reply_count: number;
  view_count: number;
  vote_score: number;
  created_at: string;
  forum_categories?: { name: string; slug: string };
}

interface UserReply {
  id: string;
  thread_id: string;
  body: string;
  vote_score: number;
  created_at: string;
  forum_threads?: { title: string };
}

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleDateString("en-US", { month: "long", year: "numeric" });
  } catch { return iso.slice(0, 10); }
}

export default function ForumUserPage() {
  const params = useParams();
  const username = params?.username as string;
  const [data, setData] = useState<{ profile: ForumUserProfile; threads: UserThread[]; replies: UserReply[] } | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [isOwnProfile, setIsOwnProfile] = useState(false);

  useEffect(() => {
    if (!username) return;
    setLoading(true);
    fetch(`/api/forum/user-by-username/${encodeURIComponent(username)}`, { cache: "no-store" })
      .then(async (r) => {
        if (r.status === 404) { setNotFound(true); return null; }
        if (!r.ok) return null;
        return r.json();
      })
      .then((d) => { if (d) setData(d); })
      .finally(() => setLoading(false));
  }, [username]);

  useEffect(() => {
    if (!data?.profile) return;
    fetch('/api/forum/profile/me')
      .then(async (r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d?.profile?.username && d.profile.username === data.profile.username) {
          setIsOwnProfile(true);
        }
      })
      .catch(() => {});
  }, [data]);

  if (loading) {
    return (
      <>
        <Header />
        <main className="bg-[#F8FAFC] min-h-screen">
          <div className="max-w-container mx-auto px-4 py-12">
            <p className="font-body text-sm text-[#666]">Loading profile…</p>
          </div>
        </main>
        <Footer />
      </>
    );
  }
  if (notFound || !data) {
    return (
      <>
        <Header />
        <main className="bg-[#F8FAFC] min-h-screen">
          <div className="max-w-container mx-auto px-4 py-12">
            <h1 className="font-heading text-2xl font-bold text-[#0F172A] mb-2">User not found</h1>
            <p className="font-body text-sm text-[#888]">No forum member with username "{username}".</p>
            <Link href="/forum" className="font-body text-sm text-[#1D4ED8] hover:underline mt-4 inline-block">← Back to The Integration Room</Link>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  const { profile, threads, replies } = data;
  const location = [profile.location_city, profile.location_country].filter(Boolean).join(", ");

  return (
    <>
      <Header />
      <main className="bg-[#F8FAFC] min-h-screen">
        <div className="max-w-container mx-auto px-4 py-8">
          {/* Header card */}
          <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-6 mb-6">
            <div className="flex flex-col sm:flex-row sm:items-start gap-5">
              <div className="w-20 h-20 sm:w-24 sm:h-24 rounded-full overflow-hidden border-2 border-[#DCE6F2] flex-shrink-0 bg-[#F8FAFC] flex items-center justify-center">
                {profile.avatar_url ? (
                  <AppImage src={profile.avatar_url} alt={profile.display_name} width={96} height={96} className="w-full h-full object-cover" />
                ) : (
                  <span className="font-heading text-2xl font-bold text-[#1D4ED8]">
                    {profile.display_name.charAt(0).toUpperCase()}
                  </span>
                )}
              </div>

              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between gap-3 flex-wrap">
                  <h1 className="font-heading text-2xl md:text-3xl font-bold text-[#0F172A] leading-tight">
                    {profile.display_name}
                  </h1>
                  {isOwnProfile && (
                    <Link
                      href="/forum/profile/edit"
                      className="text-xs font-body font-bold uppercase tracking-wider bg-[#1D4ED8] hover:bg-[#1E3A8A] text-white px-3 py-1.5 rounded-sm transition-colors"
                    >
                      Edit Profile
                    </Link>
                  )}
                </div>
                <p className="font-body text-sm text-[#1D4ED8] mt-0.5">@{profile.username}</p>

                <div className="flex flex-wrap items-center gap-2 mt-3">
                  {profile.expertise_level && (
                    <span className="font-body text-[10px] font-bold uppercase tracking-wider text-[#a78bfa] bg-[#a78bfa]/10 border border-[#a78bfa]/40 px-2 py-1 rounded-sm">
                      {profile.expertise_level}
                    </span>
                  )}
                  {profile.role_title && (
                    <span className="font-body text-[10px] font-bold uppercase tracking-wider text-[#475569] bg-[#9ca3af]/10 border border-[#9ca3af]/30 px-2 py-1 rounded-sm">
                      {profile.role_title}
                    </span>
                  )}
                </div>

                <div className="flex flex-wrap items-center gap-x-5 gap-y-1 mt-3 text-xs text-[#888]">
                  {profile.company && <span>{profile.company}</span>}
                  {location && <span>📍 {location}</span>}
                  {profile.years_experience && <span>{profile.years_experience}y experience</span>}
                  <span>Joined {fmtDate(profile.join_date)}</span>
                </div>
              </div>
            </div>

            {profile.bio && (
              <p className="font-body text-sm text-[#1e293b] leading-relaxed mt-5 pt-5 border-t border-[#DCE6F2]">
                {profile.bio}
              </p>
            )}

            {profile.expertise_tags && profile.expertise_tags.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-4">
                {profile.expertise_tags.map((tag) => (
                  <span key={tag} className="font-body text-[11px] text-[#475569] bg-[#F8FAFC] border border-[#DCE6F2] px-2 py-0.5 rounded-sm">
                    #{tag}
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* Activity grid */}
          <div className="grid grid-cols-1 lg:grid-cols-[2fr,1fr] gap-6">
            <div>
              <h2 className="font-heading text-lg font-bold text-[#0F172A] mb-3">
                Threads started ({profile.thread_count})
              </h2>
              {threads.length === 0 ? (
                <p className="font-body text-sm text-[#666] mb-6">No threads yet.</p>
              ) : (
                <ul className="space-y-2 mb-8">
                  {threads.map((t) => (
                    <li key={t.id} className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-3 hover:border-[#1D4ED8]/50 transition-colors">
                      <Link href={`/forum/thread/${t.id}`} className="font-body text-sm font-semibold text-[#0F172A] hover:text-[#1D4ED8] block">
                        {t.title}
                      </Link>
                      <div className="flex items-center gap-3 mt-1 text-[11px] text-[#666]">
                        {t.forum_categories?.name && <span>{t.forum_categories.name}</span>}
                        <span>·</span>
                        <span>{t.reply_count} replies</span>
                        <span>·</span>
                        <span>{t.view_count} views</span>
                        <span>·</span>
                        <time>{new Date(t.created_at).toLocaleDateString()}</time>
                      </div>
                    </li>
                  ))}
                </ul>
              )}

              <h2 className="font-heading text-lg font-bold text-[#0F172A] mb-3">
                Recent replies
              </h2>
              {replies.length === 0 ? (
                <p className="font-body text-sm text-[#666]">No replies yet.</p>
              ) : (
                <ul className="space-y-2">
                  {replies.map((r) => (
                    <li key={r.id} className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-3">
                      <Link href={`/forum/thread/${r.thread_id}`} className="font-body text-xs font-semibold text-[#1D4ED8] hover:underline">
                        {r.forum_threads?.title || "(thread)"}
                      </Link>
                      <p className="font-body text-sm text-[#1e293b] leading-relaxed mt-1 line-clamp-3">{r.body}</p>
                      <div className="mt-1 text-[11px] text-[#666]">
                        <time>{new Date(r.created_at).toLocaleDateString()}</time>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>

            <aside>
              <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-4 sticky top-4">
                <h3 className="font-body text-xs font-bold uppercase tracking-wider text-[#888] mb-2">Profile facts</h3>
                <dl className="text-sm space-y-2">
                  <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Role</dt><dd className="text-[#0F172A]">{profile.role_title || "—"}</dd></div>
                  {profile.company && <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Company</dt><dd className="text-[#0F172A]">{profile.company}</dd></div>}
                  <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Posts</dt><dd className="text-[#0F172A]">{profile.post_count}</dd></div>
                  <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Threads</dt><dd className="text-[#0F172A]">{profile.thread_count}</dd></div>
                  <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Replies</dt><dd className="text-[#0F172A]">{profile.reply_count}</dd></div>
                  {profile.years_experience && <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Years in industry</dt><dd className="text-[#0F172A]">{profile.years_experience}</dd></div>}
                  <div><dt className="text-[#666] text-[11px] uppercase tracking-wider">Member since</dt><dd className="text-[#0F172A]">{fmtDate(profile.join_date)}</dd></div>
                </dl>
              </div>
            </aside>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}
