import { useParams, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { usersApi, type UserProfile } from '@/services/api/users';
import { tracksApi } from '@/services/api/tracks';
import { playlistsApi } from '@/services/api/playlists';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { FollowButton } from '../components/FollowButton';
import { format } from 'date-fns';
import { Avatar } from '@/components/ui/avatar';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import type { Track } from '@/features/tracks/types/track';
import { PlaylistCard } from '@/features/playlists/components/PlaylistCard';
import { Music, Library, MessageSquare, MapPin, Calendar, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useUser } from '@/features/auth/hooks/useUser';
import { socialService } from '@/services/socialService';

export function UserProfilePage() {
  const { username } = useParams<{ username: string }>();
  const { data: currentUser } = useUser();

  const {
    data: profile,
    isLoading,
    error,
  } = useQuery<UserProfile | null>({
    queryKey: ['userProfile', username],
    queryFn: async () => {
      if (!username) throw new Error('Username is required');
      return usersApi.getProfileByUsername(username);
    },
    enabled: !!username,
    retry: false,
  });

  const { data: tracksData, isLoading: isTracksLoading } = useQuery({
    queryKey: ['userTracks', profile?.id],
    queryFn: () => tracksApi.list(1, 12, { userId: profile?.id }),
    enabled: !!profile?.id,
  });

  const { data: postsData, isLoading: isPostsLoading } = useQuery({
    queryKey: ['userPosts', profile?.id],
    queryFn: () => socialService.getPostsByUser(profile!.id, 1, profile),
    enabled: !!profile?.id,
  });

  const { data: playlistsData, isLoading: isPlaylistsLoading } = useQuery({
    queryKey: ['userPlaylists', profile?.id],
    queryFn: () => playlistsApi.list(1, 12, profile?.id),
    enabled: !!profile?.id,
  });

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8 flex items-center justify-center min-h-[600px]">
        <LoadingSpinner />
      </div>
    );
  }

  if (error || !username || !profile) {
    return (
      <div className="container mx-auto px-4 py-8 flex flex-col items-center justify-center min-h-[600px] text-center">
        <div className="text-9xl mb-4">👾</div>
        <h2 className="text-3xl font-display font-bold text-destructive mb-2">User Not Found</h2>
        <p className="text-muted-foreground text-lg max-w-md">
          The signal was lost in the void. We couldn't find the profile you were looking for.
        </p>
        <Button variant="outline" className="mt-8" asChild>
          <Link to="/dashboard">Return to Base</Link>
        </Button>
      </div>
    );
  }

  const displayName = profile.first_name || profile.last_name
    ? `${profile.first_name || ''} ${profile.last_name || ''}`.trim()
    : profile.username;

  const initials = displayName.split(' ').map((n) => n[0]).join('').toUpperCase().slice(0, 2);
  const memberSince = profile.created_at ? format(new Date(profile.created_at), 'MMM yyyy') : null;

  return (
    <div className="min-h-screen pb-24">
      {/* 1. Hero Banner Gradient */}
      <div className="h-64 md:h-80 w-full relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-r from-cyan-900/40 via-purple-900/40 to-magenta-900/40" />
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-white/10 to-transparent opacity-50" />

        {/* Noise overlay */}
        <div className="absolute inset-0 noise opacity-20" />
      </div>

      <div className="container mx-auto px-4 md:px-8 relative -mt-24 z-10">

        {/* 2. Profile Header Card */}
        <Card variant="glass" className="mb-8 overflow-visible border-white/10 shadow-[0_20px_50px_rgba(0,0,0,0.5)] bg-black/40 backdrop-blur-2xl">
          <CardContent className="pt-0 md:pt-0 pb-8 px-6 md:px-10">
            <div className="flex flex-col md:flex-row items-start md:items-end gap-6 md:gap-10">

              {/* Avatar with Ring */}
              <div className="relative -mt-16 md:-mt-20 group">
                <div className="absolute inset-0 rounded-3xl bg-gradient-to-br from-cyan-400 to-magenta-500 blur-lg opacity-50 group-hover:opacity-100 transition-opacity duration-500" />
                <Avatar
                  src={profile.avatar_url || undefined}
                  alt={profile.username}
                  fallback={initials}
                  size="3xl"
                  className="h-32 w-32 md:h-40 md:w-40 rounded-3xl border-4 border-background shadow-2xl relative z-10"
                />
              </div>

              {/* Info */}
              <div className="flex-1 pt-4 md:pt-6 md:pb-2">
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div>
                    <h1 className="text-4xl md:text-5xl font-display font-bold text-white tracking-tight mb-2">
                      {displayName}
                    </h1>
                    <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-muted-foreground/80 font-medium">
                      <span className="flex items-center gap-1.5 text-primary">
                        <span className="text-primary-foreground/50">@</span>{profile.username}
                      </span>
                      {profile.location && (
                        <span className="flex items-center gap-1.5">
                          <MapPin className="w-4 h-4" /> {profile.location}
                        </span>
                      )}
                      {memberSince && (
                        <span className="flex items-center gap-1.5">
                          <Calendar className="w-4 h-4" /> Joined {memberSince}
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Action Button */}
                  <div className="flex-shrink-0">
                    <FollowButton userId={profile.id.toString()} />
                  </div>
                </div>
              </div>

            </div>

            {/* Bio & Stats Grid */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mt-10">
              {/* Bio */}
              <div className="md:col-span-2">
                <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-2">
                  <User className="w-4 h-4" /> About
                </h3>
                <p className="text-lg leading-relaxed text-foreground/90 whitespace-pre-wrap">
                  {profile.bio || <span className="text-muted-foreground italic">Systems online. No bio data available.</span>}
                </p>
              </div>

              {/* Stats (Glass Blocks) */}
              <div className="flex items-center justify-between md:justify-end gap-2 bg-white/5 rounded-2xl p-2 border border-white/5">
                <div className="flex-1 text-center p-3 rounded-xl hover:bg-white/5 transition-colors cursor-default">
                  <div className="text-2xl font-bold font-display text-white">{tracksData?.pagination.total || 0}</div>
                  <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-bold">Tracks</div>
                </div>
                <div className="w-px h-10 bg-white/10" />
                <div className="flex-1 text-center p-3 rounded-xl hover:bg-white/5 transition-colors cursor-default">
                  <div className="text-2xl font-bold font-display text-white">{playlistsData?.total || 0}</div>
                  <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-bold">Playlists</div>
                </div>
                <div className="w-px h-10 bg-white/10" />
                <div className="flex-1 text-center p-3 rounded-xl hover:bg-white/5 transition-colors cursor-default">
                  <div className="text-2xl font-bold font-display text-white">{profile.followers_count || 0}</div>
                  <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-bold">Followers</div>
                </div>
              </div>
            </div>

          </CardContent>
        </Card>

        {/* 3. Content Tabs */}
        <Tabs defaultValue="tracks" className="w-full">
          <TabsList className="bg-transparent border-b border-white/10 w-full justify-start h-auto p-0 rounded-none gap-8">
            <TabsTrigger
              value="tracks"
              className="rounded-none border-b-2 border-transparent data-[state=active]:bg-transparent data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none py-4 px-0 text-lg font-display bg-transparent"
            >
              Tracks <span className="ml-2 text-xs bg-white/10 px-2 py-0.5 rounded-full text-muted-foreground align-middle">{tracksData?.pagination.total || 0}</span>
            </TabsTrigger>
            <TabsTrigger
              value="playlists"
              className="rounded-none border-b-2 border-transparent data-[state=active]:bg-transparent data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none py-4 px-0 text-lg font-display bg-transparent"
            >
              Playlists <span className="ml-2 text-xs bg-white/10 px-2 py-0.5 rounded-full text-muted-foreground align-middle">{playlistsData?.total || 0}</span>
            </TabsTrigger>
            <TabsTrigger
              value="posts"
              className="rounded-none border-b-2 border-transparent data-[state=active]:bg-transparent data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none py-4 px-0 text-lg font-display bg-transparent"
            >
              Feed
            </TabsTrigger>
          </TabsList>

          <div className="mt-8 animate-slide-up">
            <TabsContent value="tracks" className="m-0">
              {(!tracksData?.tracks || tracksData.tracks.length === 0) ? (
                <div className="text-center py-20 bg-muted/5 rounded-3xl border border-dashed border-white/10">
                  <Music className="h-16 w-16 mx-auto mb-6 text-muted-foreground opacity-20" />
                  <h3 className="text-xl font-bold mb-2">No audio signals detected</h3>
                  <p className="text-muted-foreground">This user currently has no public tracks.</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {tracksData.tracks.map((track: Track) => (
                    <Link key={track.id} to={`/tracks/${track.id}`}>
                      <Card variant="glass" className="overflow-hidden hover:-translate-y-2 hover:shadow-[0_20px_40px_rgba(0,0,0,0.4)] transition-all duration-300 group border-white/5">
                        <div className="relative aspect-video bg-black/50 overflow-hidden">
                          {track.cover_art_path ? (
                            <img
                              src={track.cover_art_path}
                              alt={track.title}
                              className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center bg-muted/10">
                              <Music className="h-12 w-12 text-muted-foreground/30" />
                            </div>
                          )}
                          {/* Overlay Gradient */}
                          <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-60 group-hover:opacity-80 transition-opacity" />

                          <div className="absolute bottom-4 left-4 right-4">
                            <h3 className="font-bold text-lg text-white truncate drop-shadow-md">{track.title}</h3>
                            <p className="text-sm text-white/70 truncate">{track.artist || 'Unknown Artist'}</p>
                          </div>

                          <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-black/20 backdrop-blur-[2px]">
                            <div className="w-16 h-16 rounded-full bg-primary/90 text-primary-foreground flex items-center justify-center shadow-glow-cyan hover:scale-110 transition-transform">
                              <Play className="w-6 h-6 ml-1 fill-current" />
                            </div>
                          </div>
                        </div>
                      </Card>
                    </Link>
                  ))}
                </div>
              )}
            </TabsContent>

            <TabsContent value="playlists" className="m-0">
              {(!playlistsData?.playlists || playlistsData.playlists.length === 0) ? (
                <div className="text-center py-20 bg-muted/5 rounded-3xl border border-dashed border-white/10">
                  <Library className="h-16 w-16 mx-auto mb-6 text-muted-foreground opacity-20" />
                  <h3 className="text-xl font-bold mb-2">Archive empty</h3>
                  <p className="text-muted-foreground">No public playlists found in this sector.</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {playlistsData.playlists.map((playlist) => (
                    <Link key={playlist.id} to={`/playlists/${playlist.id}`}>
                      <PlaylistCard playlist={playlist} />
                    </Link>
                  ))}
                </div>
              )}
            </TabsContent>

            <TabsContent value="posts" className="m-0">
              {/* Simplified Feed View */}
              {(!postsData?.posts || postsData.posts.length === 0) ? (
                <div className="text-center py-20 bg-muted/5 rounded-3xl border border-dashed border-white/10">
                  <MessageSquare className="h-16 w-16 mx-auto mb-6 text-muted-foreground opacity-20" />
                  <h3 className="text-xl font-bold mb-2">No transmissions</h3>
                  <p className="text-muted-foreground">This frequency is silent.</p>
                </div>
              ) : (
                <div className="space-y-4 max-w-2xl mx-auto">
                  {postsData.posts.map((post) => (
                    <Card key={post.id} variant="glass" className="p-6">
                      <div className="flex items-start gap-4">
                        <Avatar
                          src={post.author.avatar}
                          alt={post.author.name}
                          fallback={post.author.name[0]}
                          className="mt-1"
                        />
                        <div className="flex-1">
                          <div className="flex items-baseline justify-between">
                            <h4 className="font-bold text-white">
                              {post.author.name}
                              <span className="ml-2 text-sm font-normal text-muted-foreground">
                                {post.author.handle}
                              </span>
                            </h4>
                            <span className="text-xs text-muted-foreground font-mono">
                              {new Date(post.timestamp).toLocaleDateString()}
                            </span>
                          </div>
                          <p className="mt-3 text-base text-white/80 leading-relaxed font-sans">{post.content}</p>
                          <div className="mt-4 flex items-center gap-6 text-xs font-mono text-muted-foreground">
                            <span className="hover:text-primary cursor-pointer transition-colors">❤️ {post.likes} Likes</span>
                            <span className="hover:text-primary cursor-pointer transition-colors">💬 {post.comments} Comments</span>
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </TabsContent>
          </div>
        </Tabs>
      </div>
    </div>
  );
}
