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 { fetchUserProfile } from "../services/userService"
import type { Deal, Comment } from "../models"
import type { PublicUserSummary } from "../models/User"


export default function ProfilePage() {
  const { userName } = useParams<{ userName: string }>()
  const [activeTab, setActiveTab] = useState<"deals" | "comments">("deals")
  const [user, setUser] = useState<PublicUserSummary | null>(null)
  const [deals, setDeals] = useState<Deal[]>([])
  const [comments, setComments] = useState<Comment[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!userName) return
    const loadUser = async () => {
      setLoading(true)
      try {
        const { user, deals, comments } = await fetchUserProfile(userName)
        setUser(user)
        setDeals(deals)
        setComments(comments)
      } catch (err: any) {
        console.error(err)
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }
    loadUser()
  }, [userName])

  if (loading) return <p className="p-4 text-center">Yükleniyor...</p>
  if (error) return <p className="p-4 text-center text-red-600">{error}</p>
  if (!user) return <p className="p-4 text-center">Kullanıcı bulunamadı.</p>

  return (
    <MainLayout>
      <div className="max-w-5xl mx-auto px-4 py-8 space-y-8">
        {/* ÜST: profil bilgisi */}
        <div className="bg-surface/50 rounded-lg p-6 flex flex-col items-center text-center shadow-sm">
          <img
            src={user.avatarUrl || `${import.meta.env.BASE_URL}placeholders/placeholder-profile.png`}
            alt="avatar"
            className="w-24 h-24 rounded-full mb-3 border"
          />
          <h1 className="text-xl font-semibold">{user.username}</h1>
          <p className="text-xs text-muted-foreground mt-1">
            Katılma: {new Date(user.createdAt).toLocaleDateString("tr-TR")}
          </p>
        </div>

        {/* MENÜ */}
        <div className="border-b border-border flex justify-center gap-8 text-sm font-medium">
          <button
            onClick={() => setActiveTab("deals")}
            className={`py-2 ${
              activeTab === "deals"
                ? "text-primary border-b-2 border-primary"
                : "text-muted-foreground"
            }`}
          >
            Paylaşımlar
          </button>
          <button
            onClick={() => setActiveTab("comments")}
            className={`py-2 ${
              activeTab === "comments"
                ? "text-primary border-b-2 border-primary"
                : "text-muted-foreground"
            }`}
          >
            Yorumlar
          </button>
        </div>

        {/* İÇERİK */}
        <div className="min-h-[300px]">
          {activeTab === "deals" ? (
            <div className="space-y-4">
                {deals.length > 0 ? (
                deals.map((deal) => {
                    const firstImage = deal.images?.[0]?.imageUrl || "/placeholder.png"
                    const postedAgo = new Date(deal.createdAt).toLocaleDateString("tr-TR")

                    return (
                    <DealCardMain
                        key={deal.id}
                        id={deal.id}
                        image={firstImage}
                        title={deal.title}
                        price={`${deal.price ?? 0}₺`}
                        store={ "Bilinmiyor"}
                        postedBy={user.username}
                        score={deal.score}
                        comments={0}
                        postedAgo={postedAgo}
                        onRequireLogin={() => {}}
                    />
                    )
                })
                ) : (
                <p className="text-center text-muted-foreground py-8">
                    Henüz paylaşım yok.
                </p>
                )}

            </div>
          ) : (
            <div className="space-y-4">
                {comments.length > 0 ? (
                comments.map((c) => <CommentCard key={c.id} comment={c} />)
                ) : (
                <p className="text-center text-muted-foreground py-8">
                    Henüz yorum yok.
                </p>
                )}
            </div>
          )}
        </div>
      </div>
    </MainLayout>
  )
}
