"use client"

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

const MOCK_FRINDLES: UserWithFrindleStatus[] = [
  {
    id: "1",
    name: "Jessica Williams",
    username: "@jessica_w",
    avatar: "/placeholder.svg?key=j93kd",
    mutualFrindles: 12,
    followers: 543,
    frindleStatus: "connected",
  },
  {
    id: "2",
    name: "David Brown",
    username: "@david_b",
    avatar: "/placeholder.svg?key=d82js",
    mutualFrindles: 8,
    followers: 321,
    frindleStatus: "connected",
  },
  {
    id: "3",
    name: "Lisa Garcia",
    username: "@lisa_g",
    avatar: "/placeholder.svg?key=l73kd",
    mutualFrindles: 15,
    followers: 789,
    frindleStatus: "connected",
  },
]

const MOCK_PENDING_REQUESTS: UserWithFrindleStatus[] = [
  {
    id: "7",
    name: "John Smith",
    username: "@john_s",
    avatar: "/placeholder.svg?key=j83kd",
    mutualFrindles: 4,
    followers: 234,
    frindleStatus: "pending_received",
  },
  {
    id: "8",
    name: "Maria Rodriguez",
    username: "@maria_r",
    avatar: "/placeholder.svg?key=m72js",
    mutualFrindles: 7,
    followers: 456,
    frindleStatus: "pending_received",
  },
]

const MOCK_SUGGESTIONS: UserWithFrindleStatus[] = [
  {
    id: "5",
    name: "Rachel Green",
    username: "@rachel_g",
    avatar: "/placeholder.svg?key=r51js",
    mutualFrindles: 5,
    followers: 412,
    frindleStatus: "none",
  },
  {
    id: "6",
    name: "Chris Evans",
    username: "@chris_e",
    avatar: "/placeholder.svg?key=c40kd",
    mutualFrindles: 3,
    followers: 678,
    frindleStatus: "none",
  },
]

export default function FriendliesPage() {
  const [activeTab, setActiveTab] = useState("frindles")
  const [searchQuery, setSearchQuery] = useState("")
  const [frindles, setFrindles] = useState<UserWithFrindleStatus[]>(MOCK_FRINDLES)
  const [pendingRequests, setPendingRequests] = useState<UserWithFrindleStatus[]>(MOCK_PENDING_REQUESTS)
  const [suggestions, setSuggestions] = useState<UserWithFrindleStatus[]>(MOCK_SUGGESTIONS)

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

  const handleAcceptRequest = (userId: string) => {
    const user = pendingRequests.find((u) => u.id === userId)
    if (user) {
      setPendingRequests(pendingRequests.filter((u) => u.id !== userId))
      setFrindles([...frindles, { ...user, frindleStatus: "connected" }])
    }
  }

  const handleRejectRequest = (userId: string) => {
    setPendingRequests(pendingRequests.filter((u) => u.id !== userId))
  }

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

  const handleRemoveConnection = (userId: string) => {
    const user = frindles.find((u) => u.id === userId)
    if (user) {
      setFrindles(frindles.filter((u) => u.id !== userId))
      setSuggestions([...suggestions, { ...user, frindleStatus: "none" }])
    }
  }

  const filteredFrindles = frindles.filter(
    (frindle) =>
      frindle.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      frindle.username.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  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="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-gradient-to-br from-violet-600 to-indigo-600 flex items-center justify-center">
              <Users className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-foreground">Frindles</h1>
              <p className="text-sm text-muted-foreground">{frindles.length} connections</p>
            </div>
          </div>

          <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 frindles..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 h-12"
            />
          </div>

          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="w-full grid grid-cols-3">
              <TabsTrigger value="frindles">
                Frindles
                <span className="ml-2 text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full">
                  {frindles.length}
                </span>
              </TabsTrigger>
              <TabsTrigger value="requests">
                Requests
                {pendingRequests.length > 0 && (
                  <span className="ml-2 px-2 py-0.5 bg-destructive text-destructive-foreground text-xs rounded-full">
                    {pendingRequests.length}
                  </span>
                )}
              </TabsTrigger>
              <TabsTrigger value="suggestions">Discover</TabsTrigger>
            </TabsList>

            <TabsContent value="frindles" className="space-y-2 mt-4">
              {filteredFrindles.length === 0 ? (
                <div className="text-center py-12">
                  <Users className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                  <p className="text-muted-foreground">No frindles yet</p>
                  <p className="text-sm text-muted-foreground mt-1">Start connecting with people!</p>
                </div>
              ) : (
                filteredFrindles.map((frindle) => (
                  <div key={frindle.id} className="bg-card rounded-xl border border-border p-4 flex items-center gap-4">
                    <Avatar className="w-12 h-12">
                      <AvatarImage src={frindle.avatar || "/placeholder.svg"} />
                      <AvatarFallback>
                        {frindle.name
                          .split(" ")
                          .map((n) => n[0])
                          .join("")}
                      </AvatarFallback>
                    </Avatar>

                    <div className="flex-1 min-w-0">
                      <h3 className="font-semibold text-foreground">{frindle.name}</h3>
                      <p className="text-sm text-muted-foreground">{frindle.username}</p>
                      <p className="text-xs text-muted-foreground">{frindle.mutualFrindles} mutual frindles</p>
                    </div>

                    <FrindleButton
                      userId={frindle.id}
                      status={frindle.frindleStatus}
                      onRemoveConnection={handleRemoveConnection}
                    />
                  </div>
                ))
              )}
            </TabsContent>

            <TabsContent value="requests" className="space-y-2 mt-4">
              {pendingRequests.length === 0 ? (
                <div className="text-center py-12">
                  <Clock className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                  <p className="text-muted-foreground">No pending requests</p>
                  <p className="text-sm text-muted-foreground mt-1">You're all caught up!</p>
                </div>
              ) : (
                pendingRequests.map((request) => (
                  <div
                    key={request.id}
                    className="bg-card rounded-xl border border-border p-4 flex items-center gap-4"
                  >
                    <Avatar className="w-12 h-12">
                      <AvatarImage src={request.avatar || "/placeholder.svg"} />
                      <AvatarFallback>
                        {request.name
                          .split(" ")
                          .map((n) => n[0])
                          .join("")}
                      </AvatarFallback>
                    </Avatar>

                    <div className="flex-1 min-w-0">
                      <h3 className="font-semibold text-foreground">{request.name}</h3>
                      <p className="text-sm text-muted-foreground">{request.username}</p>
                      <p className="text-xs text-muted-foreground">{request.mutualFrindles} mutual frindles</p>
                    </div>

                    <FrindleButton
                      userId={request.id}
                      status={request.frindleStatus}
                      onAcceptRequest={handleAcceptRequest}
                      onRejectRequest={handleRejectRequest}
                    />
                  </div>
                ))
              )}
            </TabsContent>

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

                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-foreground">{suggestion.name}</h3>
                    <p className="text-sm text-muted-foreground">{suggestion.username}</p>
                    <p className="text-xs text-muted-foreground">{suggestion.mutualFrindles} mutual frindles</p>
                  </div>

                  <FrindleButton
                    userId={suggestion.id}
                    status={suggestion.frindleStatus}
                    onSendRequest={handleSendRequest}
                    onCancelRequest={handleCancelRequest}
                  />
                </div>
              ))}
            </TabsContent>
          </Tabs>
        </div>
      </main>
      <BottomNav />
    </div>
  )
}
