"use client"

import { useState } from "react"
import { TopNav } from "@/components/layout/top-nav"
import { BottomNav } from "@/components/layout/bottom-nav"
import { Input } from "@/components/ui/input"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Search, Hash } from 'lucide-react'
import { PostCard } from "@/components/posts/post-card"
import { FrindleButton } from "@/components/frindle/frindle-button"
import type { Post } from "@/types/post"
import type { UserWithFrindleStatus } from "@/types/frindle"

interface SearchUser {
  id: string
  name: string
  username: string
  avatar: string
  followers: number
  isFollowing: boolean
}

const MOCK_USERS: UserWithFrindleStatus[] = [
  {
    id: "1",
    name: "Sarah Johnson",
    username: "@sarah_j",
    avatar: "/placeholder.svg?key=s74k2",
    followers: 1234,
    frindleStatus: "none",
  },
  {
    id: "2",
    name: "Mike Chen",
    username: "@mike_c",
    avatar: "/placeholder.svg?key=m83j3",
    followers: 856,
    frindleStatus: "connected",
  },
  {
    id: "3",
    name: "Alex Turner",
    username: "@alex_t",
    avatar: "/placeholder.svg?key=a62k1",
    followers: 432,
    frindleStatus: "pending_sent",
  },
]

const MOCK_POSTS: Post[] = [
  {
    id: "1",
    author: {
      id: "1",
      username: "digital_nomad",
      displayName: "Digital Nomad",
      avatar: "/placeholder.svg?key=d92k4",
    },
    content: "Just launched me first PWA! The feeling of seeing your code come to life is unmatched.",
    type: "thought",
    timestamp: "2m ago",
    likes: 12,
    comments: 3,
    isLiked: false,
  },
]

export default function SearchPage() {
  const [searchQuery, setSearchQuery] = useState("")
  const [activeTab, setActiveTab] = useState("all")
  const [users, setUsers] = useState<UserWithFrindleStatus[]>(MOCK_USERS)
  const [posts, setPosts] = useState<Post[]>(MOCK_POSTS)

  const handleSendRequest = (userId: string) => {
    setUsers(users.map((user) => (user.id === userId ? { ...user, frindleStatus: "pending_sent" as const } : user)))
  }

  const handleCancelRequest = (userId: string) => {
    setUsers(users.map((user) => (user.id === userId ? { ...user, frindleStatus: "none" as const } : user)))
  }

  const handleAcceptRequest = (userId: string) => {
    setUsers(users.map((user) => (user.id === userId ? { ...user, frindleStatus: "connected" as const } : user)))
  }

  const handleRejectRequest = (userId: string) => {
    setUsers(users.map((user) => (user.id === userId ? { ...user, frindleStatus: "rejected" as const } : user)))
  }

  const handleRemoveConnection = (userId: string) => {
    setUsers(users.map((user) => (user.id === userId ? { ...user, frindleStatus: "none" as const } : user)))
  }

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

  return (
    <div className="min-h-screen pb-20 bg-background">
      <TopNav />
      <main className="max-w-2xl mx-auto">
        <div className="p-4 space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
            <Input
              placeholder="Search for people, posts, or topics..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 h-14 text-base"
              autoFocus
            />
          </div>

          {searchQuery ? (
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="w-full grid grid-cols-3">
                <TabsTrigger value="all">All</TabsTrigger>
                <TabsTrigger value="people">People</TabsTrigger>
                <TabsTrigger value="posts">Posts</TabsTrigger>
              </TabsList>

              <TabsContent value="all" className="space-y-4 mt-4">
                <div className="space-y-2">
                  <h2 className="text-sm font-semibold text-muted-foreground px-1">People</h2>
                  {users.slice(0, 3).map((user) => (
                    <div key={user.id} className="bg-card rounded-xl border border-border p-4 flex items-center gap-4">
                      <Avatar className="w-12 h-12">
                        <AvatarImage src={user.avatar || "/placeholder.svg"} />
                        <AvatarFallback>
                          {user.name
                            .split(" ")
                            .map((n) => n[0])
                            .join("")}
                        </AvatarFallback>
                      </Avatar>

                      <div className="flex-1 min-w-0">
                        <h3 className="font-semibold text-foreground">{user.name}</h3>
                        <p className="text-sm text-muted-foreground">{user.username}</p>
                        <p className="text-xs text-muted-foreground">{user.followers.toLocaleString()} followers</p>
                      </div>

                      <FrindleButton
                        userId={user.id}
                        status={user.frindleStatus}
                        onSendRequest={handleSendRequest}
                        onCancelRequest={handleCancelRequest}
                        onAcceptRequest={handleAcceptRequest}
                        onRejectRequest={handleRejectRequest}
                        onRemoveConnection={handleRemoveConnection}
                      />
                    </div>
                  ))}
                </div>

                <div className="space-y-2">
                  <h2 className="text-sm font-semibold text-muted-foreground px-1">Posts</h2>
                  {posts.map((post) => (
                    <PostCard key={post.id} post={post} onLike={handleLike} />
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="people" className="space-y-2 mt-4">
                {users.map((user) => (
                  <div key={user.id} className="bg-card rounded-xl border border-border p-4 flex items-center gap-4">
                    <Avatar className="w-12 h-12">
                      <AvatarImage src={user.avatar || "/placeholder.svg"} />
                      <AvatarFallback>
                        {user.name
                          .split(" ")
                          .map((n) => n[0])
                          .join("")}
                      </AvatarFallback>
                    </Avatar>

                    <div className="flex-1 min-w-0">
                      <h3 className="font-semibold text-foreground">{user.name}</h3>
                      <p className="text-sm text-muted-foreground">{user.username}</p>
                      <p className="text-xs text-muted-foreground">{user.followers.toLocaleString()} followers</p>
                    </div>

                    <FrindleButton
                      userId={user.id}
                      status={user.frindleStatus}
                      onSendRequest={handleSendRequest}
                      onCancelRequest={handleCancelRequest}
                      onAcceptRequest={handleAcceptRequest}
                      onRejectRequest={handleRejectRequest}
                      onRemoveConnection={handleRemoveConnection}
                    />
                  </div>
                ))}
              </TabsContent>

              <TabsContent value="posts" className="space-y-4 mt-4">
                {posts.map((post) => (
                  <PostCard key={post.id} post={post} onLike={handleLike} />
                ))}
              </TabsContent>
            </Tabs>
          ) : (
            <div className="space-y-4 mt-8">
              <div>
                <h2 className="text-sm font-semibold text-muted-foreground mb-3">Trending Topics</h2>
                <div className="space-y-2">
                  {["#WebDevelopment", "#ReactJS", "#PWA", "#TechNews", "#Coding"].map((tag) => (
                    <button
                      key={tag}
                      className="flex items-center gap-3 w-full p-3 rounded-lg hover:bg-secondary transition-colors"
                    >
                      <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                        <Hash className="w-5 h-5 text-primary" />
                      </div>
                      <div className="text-left">
                        <p className="font-semibold text-foreground">{tag}</p>
                        <p className="text-xs text-muted-foreground">{Math.floor(Math.random() * 10000)} posts</p>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </main>
      <BottomNav />
    </div>
  )
}
