"use client"

import { useState } from "react"
import { useParams } from 'next/navigation'
import { TopNav } from "@/components/layout/top-nav"
import { BottomNav } from "@/components/layout/bottom-nav"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { PostCard } from "@/components/posts/post-card"
import { FrindleButton } from "@/components/frindle/frindle-button"
import { ArrowLeft, MessageCircle } from 'lucide-react'
import Link from "next/link"
import { useRouter } from 'next/navigation'
import type { Post } from "@/types/post"
import type { FrindleStatus } from "@/types/frindle"

// Mock user data - in real app, fetch based on userId
const MOCK_USER_DATA = {
  "user-1": {
    id: "user-1",
    username: "digital_nomad",
    displayName: "Digital Nomad",
    avatar: "/placeholder.svg?height=200&width=200",
    bio: "Software developer | Tech enthusiast | Coffee addict ☕",
    postsCount: 128,
    followersCount: 1200,
    followingCount: 842,
    frindleStatus: "none" as FrindleStatus,
  },
  "user-2": {
    id: "user-2",
    username: "sarah_codes",
    displayName: "Sarah Chen",
    avatar: "/placeholder.svg?height=200&width=200",
    bio: "Full-stack developer | Open source contributor | Building cool stuff 🚀",
    postsCount: 89,
    followersCount: 2400,
    followingCount: 567,
    frindleStatus: "connected" as FrindleStatus,
  },
}

const MOCK_USER_POSTS: Record<string, Post[]> = {
  "user-1": [
    {
      id: "1",
      author: {
        id: "user-1",
        username: "digital_nomad",
        displayName: "Digital Nomad",
        avatar: "/placeholder.svg?height=200&width=200",
      },
      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: "user-1",
        username: "digital_nomad",
        displayName: "Digital Nomad",
        avatar: "/placeholder.svg?height=200&width=200",
      },
      content: "Working on some new features today. Excited to share soon!",
      type: "thought",
      timestamp: "1d ago",
      likes: 18,
      comments: 3,
      isLiked: false,
    },
  ],
  "user-2": [
    {
      id: "3",
      author: {
        id: "user-2",
        username: "sarah_codes",
        displayName: "Sarah Chen",
        avatar: "/placeholder.svg?height=200&width=200",
      },
      content: "Finally fixed that bug that's been haunting me for days! 🎉",
      type: "thought",
      timestamp: "3h ago",
      likes: 45,
      comments: 8,
      isLiked: false,
    },
  ],
}

const generateMockUserData = (userId: string) => {
  const userVariants = [
    { username: "digital_nomad", name: "Digital Nomad", bio: "Software developer | Tech enthusiast | Coffee addict ☕" },
    { username: "sarah_codes", name: "Sarah Chen", bio: "Full-stack developer | Open source contributor | Building cool stuff 🚀" },
    { username: "alex_design", name: "Alex Rivera", bio: "UI/UX Designer | Creating beautiful experiences | Design systems lover 🎨" },
    { username: "tech_writer", name: "Jordan Lee", bio: "Technical writer | Making tech accessible | Documentation enthusiast 📝" },
    { username: "data_ninja", name: "Morgan Smith", bio: "Data scientist | ML engineer | Turning data into insights 📊" },
  ]
  
  const index = userId.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0) % userVariants.length
  const variant = userVariants[index]
  
  return {
    id: userId,
    username: variant.username,
    displayName: variant.name,
    avatar: `/placeholder.svg?height=200&width=200&text=${variant.name.charAt(0)}`,
    bio: variant.bio,
    postsCount: Math.floor(Math.random() * 200) + 20,
    followersCount: Math.floor(Math.random() * 5000) + 100,
    followingCount: Math.floor(Math.random() * 1000) + 50,
    frindleStatus: "none" as FrindleStatus,
  }
}

const generateMockPosts = (userId: string, userData: any): Post[] => {
  const postContents = [
    "Just launched my first PWA! The feeling of seeing your code come to life is unmatched.",
    "Finally fixed that bug that's been haunting me for days! 🎉",
    "Working on some new features today. Excited to share soon!",
    "Love how this community supports each other. You all are amazing!",
    "Debugging is like being a detective in a crime movie where you are also the murderer.",
  ]
  
  return [0, 1].map((i) => ({
    id: `${userId}-post-${i}`,
    author: {
      id: userId,
      username: userData.username,
      displayName: userData.displayName,
      avatar: userData.avatar,
    },
    content: postContents[i % postContents.length],
    type: "thought" as const,
    timestamp: i === 0 ? "2h ago" : "1d ago",
    likes: Math.floor(Math.random() * 50) + 5,
    comments: Math.floor(Math.random() * 10) + 1,
    isLiked: false,
  }))
}

export default function UserProfilePage() {
  const params = useParams()
  const router = useRouter()
  const userId = params.userId as string

  const userData = generateMockUserData(userId)
  const [posts, setPosts] = useState<Post[]>(generateMockPosts(userId, userData))
  const [activeTab, setActiveTab] = useState("posts")
  const [frindleStatus, setFrindleStatus] = useState<FrindleStatus>(userData.frindleStatus)

  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,
      ),
    )
  }

  const handleSendRequest = (targetUserId: string) => {
    console.log("[v0] Sending Frindle request to:", targetUserId)
    setFrindleStatus("pending_sent")
  }

  const handleAcceptRequest = (targetUserId: string) => {
    console.log("[v0] Accepting Frindle request from:", targetUserId)
    setFrindleStatus("connected")
  }

  const handleRejectRequest = (targetUserId: string) => {
    console.log("[v0] Rejecting Frindle request from:", targetUserId)
    setFrindleStatus("rejected")
  }

  const handleCancelRequest = (targetUserId: string) => {
    console.log("[v0] Canceling Frindle request to:", targetUserId)
    setFrindleStatus("none")
  }

  const handleRemoveConnection = (targetUserId: string) => {
    console.log("[v0] Removing Frindle connection with:", targetUserId)
    setFrindleStatus("none")
  }

  return (
    <div className="min-h-screen pb-20 bg-background">
      <TopNav />
      <main className="max-w-2xl mx-auto">
        {/* Back button */}
        <div className="px-4 py-3 border-b border-border">
          <Button variant="ghost" size="sm" onClick={() => router.back()} className="gap-2">
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
        </div>

        {/* Profile header */}
        <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">
              <Avatar className="w-32 h-32 border-4 border-card">
                <AvatarImage src={userData.avatar || "/placeholder.svg"} />
                <AvatarFallback className="text-2xl">{userData.displayName[0]}</AvatarFallback>
              </Avatar>

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

                  <div className="flex gap-2">
                    <FrindleButton
                      userId={userData.id}
                      status={frindleStatus}
                      onSendRequest={handleSendRequest}
                      onAcceptRequest={handleAcceptRequest}
                      onRejectRequest={handleRejectRequest}
                      onCancelRequest={handleCancelRequest}
                      onRemoveConnection={handleRemoveConnection}
                    />
                    {frindleStatus === "connected" && (
                      <Button size="sm" variant="outline" className="gap-2">
                        <MessageCircle className="w-4 h-4" />
                        Message
                      </Button>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <p className="mt-4 text-foreground">{userData.bio}</p>

            <div className="flex gap-6 mt-4">
              <div>
                <span className="font-bold text-foreground">{userData.postsCount}</span>
                <span className="text-muted-foreground ml-1">Posts</span>
              </div>
              <button className="hover:underline">
                <span className="font-bold text-foreground">{userData.followersCount.toLocaleString()}</span>
                <span className="text-muted-foreground ml-1">Frindles</span>
              </button>
              <button className="hover:underline">
                <span className="font-bold text-foreground">{userData.followingCount}</span>
                <span className="text-muted-foreground ml-1">Following</span>
              </button>
            </div>
          </div>
        </div>

        {/* Profile tabs */}
        <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="media"
              className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
            >
              Media
            </TabsTrigger>
          </TabsList>

          <TabsContent value="posts" className="p-4 space-y-4">
            {posts.length > 0 ? (
              posts.map((post) => <PostCard key={post.id} post={post} onLike={handleLike} />)
            ) : (
              <p className="text-center text-muted-foreground py-8">No posts yet</p>
            )}
          </TabsContent>

          <TabsContent value="media" className="p-4">
            <div className="grid grid-cols-3 gap-2">
              {posts.filter((p) => p.imageUrl).length > 0 ? (
                posts
                  .filter((p) => p.imageUrl)
                  .map((post) => (
                    <div key={post.id} className="aspect-square bg-secondary rounded-lg overflow-hidden">
                      <img src={post.imageUrl || "/placeholder.svg"} alt="Media" className="w-full h-full object-cover" />
                    </div>
                  ))
              ) : (
                <p className="col-span-3 text-center text-muted-foreground py-8">No media posts yet</p>
              )}
            </div>
          </TabsContent>
        </Tabs>
      </main>
      <BottomNav />
    </div>
  )
}
