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 { fetchUserDeals } from "../services/userDealsService"
import { timeAgo } from "../utils/timeAgo"

import type { DealCard } from "../models/deal/DealCard"
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 [userDeals, setUserDeals] = useState<DealCard[]>([])

  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [dealsLoading, setDealsLoading] = useState(true)
  const [dealsError, setDealsError] = 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])

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

    const loadDeals = async () => {
      setDealsLoading(true)
      setDealsError(null)
      try {
        const deals = await fetchUserDeals(userName)
        setUserDeals(deals)
      } catch (err: any) {
        console.error(err)
        setDealsError(err.message || "Paylaşımlar alınamadı")
      } finally {
        setDealsLoading(false)
      }
    }

    loadDeals()
  }, [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">
        <ProfileHeader
          username={userProfile.user.username}
          avatarUrl={userProfile.user.avatarUrl ?? undefined}
          totalLikes={userProfile.stats.totalLikes}
          totalShares={userProfile.stats.totalShares}
          totalComments={userProfile.stats.totalComments}
        />

        <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">{userDeals.length}</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>

        <div className="min-h-[300px]">
          {activeTab === "deals" ? (
            <div className="space-y-4">
              {dealsLoading ? (
                <p className="text-center py-4 text-text-muted">Yükleniyor...</p>
              ) : dealsError ? (
                <p className="text-center py-4 text-danger">{dealsError}</p>
              ) : userDeals.length > 0 ? (
                userDeals.map((deal) => (
                <DealCardMain key={deal.id} deal={deal} 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>
  )
}
