"use client"

import { useState, useEffect } from "react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { ShapedAvatar } from "@/components/ui/shaped-avatar"
import { PREDEFINED_SHAPES, ProfileShape, loadProfileState } from "@/lib/profile-shapes"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { PostCard } from "@/components/posts/post-card"
import { Settings, Loader2 } from "lucide-react"
import Link from "next/link"
import type { Post } from "@/types/post"
import { getMyProfile } from "@/actions/profile-actions"
import { logout } from "@/actions/auth-actions"
import { useUserStore } from "@/lib/store"
import { useRouter } from "next/navigation"

const MOCK_USER_POSTS: Post[] = [
  {
    id: "1",
    author: {
      id: "current-user",
      username: "your_username",
      displayName: "Your Name",
      avatar: "/placeholder.svg?key=2sjn8",
    },
    content: "Just launched my first PWA! The feeling of seeing your code come to life is unmatched.",
    type: "thought",
    timestamp: "2h ago",
    likes: 24,
    comments: 5,
    isLiked: false,
  },
  {
    id: "2",
    author: {
      id: "current-user",
      username: "your_username",
      displayName: "Your Name",
      avatar: "/placeholder.svg?key=o92jq",
    },
    content: "Working on some new features today. Excited to share soon!",
    type: "thought",
    timestamp: "1d ago",
    likes: 18,
    comments: 3,
    isLiked: false,
  },
]

export default function ProfilePage() {
  const router = useRouter()
  const { user, setUser, isLoading, setLoading, error, setError } = useUserStore()
  const [posts, setPosts] = useState<Post[]>(MOCK_USER_POSTS)
  const [activeTab, setActiveTab] = useState("posts")
  
  // Load profile picture and shape from localStorage
  const [profilePicUrl, setProfilePicUrl] = useState<string | undefined>()
  const [profileShape, setProfileShape] = useState<ProfileShape>(PREDEFINED_SHAPES[0])
  
  useEffect(() => {
    const savedState = loadProfileState()
    if (savedState) {
      if (savedState.profilePicUrl) {
        setProfilePicUrl(savedState.profilePicUrl)
      }
      if (savedState.profileShape) {
        setProfileShape(savedState.profileShape)
      }
    }
  }, [])

  // Fetch profile data from backend
  useEffect(() => {
    const fetchProfile = async () => {
      setLoading(true)
      setError(null)

      try {
        const result = await getMyProfile()

        if (result.success && result.profile) {
          setUser(result.profile)
        } else {
          // Check if error is related to invalid token
          const errorMsg = result.error || "Failed to load profile"
          
          if (errorMsg.includes("token") || errorMsg.includes("authenticated") || errorMsg.includes("auth")) {
            // Invalid token - logout and redirect
            await logout()
            router.push("/login")
            return
          }
          
          setError(errorMsg)
        }
      } catch (err) {
        setError("An unexpected error occurred")
      } finally {
        setLoading(false)
      }
    }

    fetchProfile()
  }, [setUser, setLoading, setError, router])

  const handleLike = (postId: string) => {
    setPosts(
      posts.map((post) =>
        post.id === postId
          ? { ...post, isLiked: !post.isLiked, likes: post.isLiked ? post.likes - 1 : post.likes + 1 }
          : post,
      ),
    )
  }

  if (isLoading) {
    return (
      <div className="p-2 sm:p-4 flex items-center justify-center min-h-screen">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-primary" />
          <p className="text-muted-foreground">Loading profile...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="p-2 sm:p-4">
        <div className="bg-destructive/10 border border-destructive/20 rounded-xl p-6 text-center">
          <p className="text-destructive font-semibold mb-2">Error loading profile</p>
          <p className="text-sm text-muted-foreground mb-4">{error}</p>
          <Button onClick={() => window.location.reload()}>Retry</Button>
        </div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="p-2 sm:p-4">
        <div className="bg-card border border-border rounded-xl p-6 text-center">
          <p className="text-muted-foreground mb-4">No profile found</p>
          <Button onClick={() => router.push("/profile/settings")}>Setup Profile</Button>
        </div>
      </div>
    )
  }

  // Get initials for avatar fallback
  const initials = user.name
    ? user.name.split(' ').map(n => n[0]).join('').toUpperCase()
    : user.username?.[0]?.toUpperCase() || '?'

  return (
    <div className="p-2 sm:p-4">
        <div className="relative">
          <div className="h-32 bg-gradient-to-br from-primary/20 to-primary/5"></div>

          <div className="px-4 pb-4">
            <div className="flex items-end gap-4 -mt-16">
              {/* Use ShapedAvatar to show custom profile shapes */}
              <div className="relative">
                <ShapedAvatar 
                  src={user.image || profilePicUrl || "/placeholder.svg?key=k43d9"}
                  fallback={<span className="text-2xl font-medium">{initials}</span>}
                  className="w-32 h-32 border-4 border-card"
                  shape={profileShape}
                />
              </div>

              <div className="flex-1 pb-2">
                <div className="flex items-center justify-between">
                  <div>
                    <h1 className="text-2xl font-bold text-foreground">{user.name}</h1>
                    <p className="text-muted-foreground">@{user.username}</p>
                  </div>

                  <div className="flex gap-2">
                    <Button variant="outline" size="icon" asChild>
                      <Link href="/profile/settings">
                        <Settings className="w-5 h-5" />
                      </Link>
                    </Button>
                  </div>
                </div>
              </div>
            </div>

            <p className="mt-4 text-foreground">{user.bio || "No bio yet"}</p>

            <div className="flex gap-6 mt-4">
              <div>
                <span className="font-bold text-foreground">{user.postsCount || 0}</span>
                <span className="text-muted-foreground ml-1">Posts</span>
              </div>
              <div>
                <span className="font-bold text-foreground">{user.starsRetained || 0}</span>
                <span className="text-muted-foreground ml-1">Followers</span>
              </div>
              <div>
                <span className="font-bold text-foreground">{user.totalStars || 5}</span>
                <span className="text-muted-foreground ml-1">Following</span>
              </div>
            </div>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="mt-6">
          <TabsList className="w-full justify-start border-b rounded-none h-auto p-0 bg-transparent">
            <TabsTrigger
              value="posts"
              className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
            >
              Posts
            </TabsTrigger>
            <TabsTrigger
              value="videos"
              className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
            >
              Videos
            </TabsTrigger>
            <TabsTrigger
              value="likes"
              className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
            >
              Likes
            </TabsTrigger>
          </TabsList>

          <TabsContent value="posts" className="p-4 space-y-4">
            {posts.map((post) => (
              <PostCard key={post.id} post={post} onLike={handleLike} />
            ))}
          </TabsContent>

          <TabsContent value="videos" className="p-4">
            <div className="grid grid-cols-3 gap-2">
              {[1, 2, 3, 4, 5, 6].map((i) => (
                <div key={i} className="aspect-square bg-secondary rounded-lg"></div>
              ))}
            </div>
          </TabsContent>

          <TabsContent value="likes" className="p-4 space-y-4">
            <p className="text-center text-muted-foreground py-8">No liked posts yet</p>
          </TabsContent>
        </Tabs>
    </div>
  )
}
