"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { User, Settings, MessageSquare, BookOpen, Heart } from "lucide-react"
import { fetchApi } from "@/lib/api-client"
import { useAuth } from "@/components/auth-provider"

interface ProfileData {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  role: string;
  bio?: string;
  avatar_url?: string;
  created_at: string;
  questions?: any[];
  replies?: any[];
}

export default function ProfilePage() {
  const { user, loading, logout } = useAuth()
  const [profile, setProfile] = useState<ProfileData | null>(null)
  const [isLoadingProfile, setIsLoadingProfile] = useState(true)
  const [activeTab, setActiveTab] = useState("activity")
  const router = useRouter()

  useEffect(() => {
    if (!loading && !user) {
      router.push("/login")
      return
    }

    if (user) {
      const getProfile = async () => {
        try {
          const profileData = await fetchApi(`profile.php`)
          setProfile(profileData)
        } catch (error) {
          console.error("Failed to fetch profile:", error)
        } finally {
          setIsLoadingProfile(false)
        }
      }

      getProfile()
    }
  }, [user, loading, router])

  if (loading || isLoadingProfile) {
    return <div className="container mx-auto px-4 py-12 text-center">Loading...</div>
  }

  if (!user) return null;

  return (
    <main className="flex-1 container mx-auto px-4 py-12 max-w-5xl">
      <div className="flex flex-col md:flex-row gap-8 items-start">
        {/* Profile Sidebar */}
        <aside className="w-full md:w-64 space-y-6">
          <Card>
            <CardContent className="p-6 text-center space-y-4">
              <div className="mx-auto h-24 w-24 rounded-full bg-primary/10 flex items-center justify-center overflow-hidden">
                {profile?.avatar_url ? (
                  <img src={profile.avatar_url} alt="Profile" className="h-full w-full object-cover" />
                ) : (
                  <User className="h-12 w-12 text-primary" />
                )}
              </div>
              <div>
                <h2 className="text-xl font-bold">
                  {profile?.first_name} {profile?.last_name}
                </h2>
                <p className="text-sm text-muted-foreground capitalize">{profile?.role || "Member"}</p>
              </div>
              <Button variant="outline" size="sm" className="w-full bg-transparent">
                Edit Profile
              </Button>
            </CardContent>
          </Card>

          <nav className="flex flex-col gap-1">
            <Button 
              variant={activeTab === "activity" ? "secondary" : "ghost"} 
              className="justify-start gap-2"
              onClick={() => setActiveTab("activity")}
            >
              <MessageSquare className="h-4 w-4" /> My Posts
            </Button>
            <Button 
              variant={activeTab === "saved" ? "secondary" : "ghost"} 
              className="justify-start gap-2"
              onClick={() => setActiveTab("saved")}
            >
              <BookOpen className="h-4 w-4" /> Saved Articles
            </Button>
            <Button 
              variant={activeTab === "settings" ? "secondary" : "ghost"} 
              className="justify-start gap-2"
              onClick={() => setActiveTab("settings")}
            >
              <Settings className="h-4 w-4" /> Account Settings
            </Button>
          </nav>
        </aside>

        {/* Profile Content */}
        <div className="flex-1 space-y-8 w-full">
          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="grid w-full grid-cols-3 lg:w-96">
              <TabsTrigger value="activity">Activity</TabsTrigger>
              <TabsTrigger value="saved">Saved</TabsTrigger>
              <TabsTrigger value="settings">Settings</TabsTrigger>
            </TabsList>
            <TabsContent value="activity" className="pt-6 space-y-4">
              <h3 className="text-lg font-semibold">Recent Contributions</h3>
              <div className="space-y-4">
                {profile?.questions?.map((q) => (
                  <Card key={`q-${q.id}`}>
                    <Link href={`/forum/${q.id}`}>
                      <CardHeader className="p-4 pb-0">
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          <MessageSquare className="h-3 w-3" /> Question • {new Date(q.created_at).toLocaleDateString()}
                        </div>
                        <CardTitle className="text-base hover:text-primary transition-colors">{q.title}</CardTitle>
                      </CardHeader>
                      <CardContent className="p-4">
                        <p className="text-sm text-muted-foreground line-clamp-2">
                          {q.content}
                        </p>
                      </CardContent>
                    </Link>
                  </Card>
                ))}
                {profile?.replies?.map((r) => (
                  <Card key={`r-${r.id}`}>
                    <Link href={`/forum/${r.question_id}`}>
                      <CardHeader className="p-4 pb-0">
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          <MessageSquare className="h-3 w-3" /> Reply in: {r.question_title} • {new Date(r.created_at).toLocaleDateString()}
                        </div>
                      </CardHeader>
                      <CardContent className="p-4">
                        <p className="text-sm text-muted-foreground line-clamp-2">
                          {r.content}
                        </p>
                      </CardContent>
                    </Link>
                  </Card>
                ))}
                {(!profile?.questions?.length && !profile?.replies?.length) && (
                  <div className="text-center py-12 border rounded-lg bg-muted/20">
                    <p className="text-muted-foreground">You haven&apos;t made any contributions yet.</p>
                    <Button variant="link" asChild>
                      <Link href="/forum">Visit the Forum</Link>
                    </Button>
                  </div>
                )}
              </div>
            </TabsContent>
            <TabsContent value="saved" className="pt-6">
              <div className="flex flex-col items-center justify-center py-12 text-center space-y-4">
                <Heart className="h-12 w-12 text-muted-foreground opacity-20" />
                <p className="text-muted-foreground">You haven&apos;t saved any articles or posts yet.</p>
                <Button variant="outline" asChild>
                  <Link href="/insights">Browse Expert Insights</Link>
                </Button>
              </div>
            </TabsContent>
            <TabsContent value="settings" className="pt-6 space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>Account Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid gap-1">
                    <p className="text-sm font-medium text-muted-foreground">Email Address</p>
                    <p className="text-base">{profile?.email}</p>
                  </div>
                  <div className="grid gap-1">
                    <p className="text-sm font-medium text-muted-foreground">Full Name</p>
                    <p className="text-base">{profile?.first_name} {profile?.last_name}</p>
                  </div>
                  <div className="grid gap-1">
                    <p className="text-sm font-medium text-muted-foreground">Account Role</p>
                    <p className="text-base capitalize">{profile?.role}</p>
                  </div>
                </CardContent>
              </Card>

              <Card className="border-destructive/20">
                <CardHeader>
                  <CardTitle className="text-destructive">Danger Zone</CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-muted-foreground mb-4">
                    Logging out will end your current session. You will need to log back in to access your profile.
                  </p>
                  <Button variant="destructive" onClick={() => logout()}>
                    Log Out
                  </Button>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </main>
  )
}
