import { useState, useEffect } from "react"
import { useParams } from "react-router-dom"
import MainLayout from "../layouts/MainLayout"
import DealCardMain from "../components/Shared/DealCardMain"
import CommentCard from "../components/Profile/CommentCard"
import ProfileHeader from "../components/Profile/ProfileHeader"
import { fetchUserProfile } from "../services/userService"
import { timeAgo } from "../utils/timeAgo"

import type { UserProfile } from "../models/user/UserProfile"

export default function ProfilePage() {
  const { userName } = useParams<{ userName: string }>()
  const [activeTab, setActiveTab] = useState<"deals" | "comments">("deals")
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null)

  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!userName) return

    const loadUser = async () => {
      setLoading(true)
      setError(null)
      try {
        const profile = await fetchUserProfile(userName)
        setUserProfile(profile)
      } catch (err: any) {
        console.error(err)
        setError(err.message || "Sunucu hatası")
      } finally {
        setLoading(false)
      }
    }

    loadUser()
  }, [userName])

  if (loading) return <p className="p-6 text-center text-text-muted">Yükleniyor...</p>
  if (error) return <p className="p-6 text-center text-danger">{error}</p>
  if (!userProfile) return <p className="p-6 text-center text-text-muted">Kullanıcı bulunamadı.</p>


  return (
    <MainLayout>
      <div className="max-w-5xl mx-auto px-4 py-8 space-y-8">
        {/* ÜST: profil header */}
        <ProfileHeader
          username={userProfile.user.username}
          avatarUrl={userProfile.user.avatarUrl ?? undefined}
          totalLikes={userProfile.stats.totalLikes}
          totalShares={userProfile.stats.totalShares}
          totalComments={userProfile.stats.totalComments}
        />

        {/* TAB BAR */}
        <div className="rounded-2xl bg-surface border border-border p-2 flex items-center justify-center gap-2">
          <button
            type="button"
            onClick={() => setActiveTab("deals")}
            className={[
              "px-4 py-2 rounded-xl text-sm font-semibold transition",
              activeTab === "deals"
                ? "bg-background border border-border text-primary"
                : "text-text-muted hover:text-text",
            ].join(" ")}
          >
            Paylaşımlar
            <span className="ml-2 text-xs text-text-muted">
              {userProfile.deals?.length ?? 0}
            </span>
          </button>

          <button
            type="button"
            onClick={() => setActiveTab("comments")}
            className={[
              "px-4 py-2 rounded-xl text-sm font-semibold transition",
              activeTab === "comments"
                ? "bg-background border border-border text-primary"
                : "text-text-muted hover:text-text",
            ].join(" ")}
          >
            Yorumlar
            <span className="ml-2 text-xs text-text-muted">
              {userProfile.comments?.length ?? 0}
            </span>
          </button>
        </div>

        {/* İÇERİK */}
        <div className="min-h-[300px]">
          {activeTab === "deals" ? (
            <div className="space-y-4">
              {userProfile.deals?.length > 0 ? (
                userProfile.deals.map((deal) => (
                  <DealCardMain
                    key={deal.id}
                    id={deal.id}
                    image={deal.imageUrl || `${import.meta.env.BASE_URL}placeholders/placeholder-deal.png`}
                    title={deal.title}
                    price={deal.price != null ? `${deal.price}₺` : ""}
                    
                    store={deal.seller?.name ?? ""}
                    postedBy={deal.user?.username ?? "unknown"}
                    score={deal.score}
                    comments={deal.commentsCount}
                    postedAgo={timeAgo(deal.createdAt)}
                    myVote={deal.myVote}
                    onRequireLogin={() => {}}
                  />
                ))
              ) : (
                <div className="rounded-2xl bg-surface border border-border p-6 text-center">
                  <div className="text-sm font-semibold text-text">Henüz paylaşım yok</div>
                  <div className="text-xs text-text-muted mt-1">
                    Bu kullanıcı daha fırsat paylaşmamış.
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="space-y-4">
              {userProfile.comments?.length > 0 ? (
                userProfile.comments.map((c) => (
                  <CommentCard key={c.id} comment={c} />
                ))
              ) : (
                <div className="rounded-2xl bg-surface border border-border p-6 text-center">
                  <div className="text-sm font-semibold text-text">Henüz yorum yok</div>
                  <div className="text-xs text-text-muted mt-1">
                    Bu kullanıcı daha yorum yapmamış.
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </MainLayout>
  )
}
