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 } 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';

// FE-PAGE-010: Complete User Profile page implementation

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

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

  // FE-PAGE-010: Fetch user posts
  const { data: postsData, isLoading: isPostsLoading } = useQuery({
    queryKey: ['userPosts', profile?.id],
    queryFn: () => socialService.getPostsByUser(profile!.id, 1, profile),
    enabled: !!profile?.id,
  });

  // FE-PAGE-010: Fetch user playlists
  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">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <LoadingSpinner />
            <p className="mt-4 text-muted-foreground">Loading profile...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error || !username) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-destructive mb-2">
                Error
              </h2>
              <p className="text-muted-foreground">
                {error instanceof Error
                  ? error.message
                  : !username
                    ? 'Username is required'
                    : 'Failed to load profile'}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center">
              <h2 className="text-2xl font-bold mb-2">User Not Found</h2>
              <p className="text-muted-foreground">
                The user profile you're looking for doesn't exist.
              </p>
            </div>
          </CardContent>
        </Card>
      </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), 'M/d/yyyy')
    : null;

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        <Card>
          <CardHeader>
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-4">
                <Avatar
                  src={profile.avatar_url || undefined}
                  alt={profile.username}
                  fallback={initials}
                  size="3xl"
                  className="h-24 w-24"
                />
                <div>
                  <CardTitle className="text-3xl mb-1">
                    {profile.username}
                  </CardTitle>
                  {displayName !== profile.username && (
                    <p className="text-xl text-muted-foreground">
                      {displayName}
                    </p>
                  )}
                  {memberSince && (
                    <p className="text-sm text-muted-foreground mt-2">
                      Member since {memberSince}
                    </p>
                  )}
                </div>
              </div>
              <FollowButton userId={profile.id.toString()} />
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {/* FE-PAGE-010: Stats */}
              <div className="grid grid-cols-3 gap-4 pb-4 border-b">
                <div className="text-center">
                  <div className="text-2xl font-bold">
                    {tracksData?.pagination.total || 0}
                  </div>
                  <div className="text-sm text-muted-foreground">Tracks</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold">
                    {playlistsData?.total || 0}
                  </div>
                  <div className="text-sm text-muted-foreground">Playlists</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold">
                    {profile.followers_count || 0}
                  </div>
                  <div className="text-sm text-muted-foreground">Followers</div>
                </div>
              </div>

              {profile.bio && (
                <div>
                  <h3 className="font-semibold mb-2">Bio</h3>
                  <p className="text-muted-foreground whitespace-pre-wrap">
                    {profile.bio}
                  </p>
                </div>
              )}

              {profile.location && (
                <div>
                  <h3 className="font-semibold mb-2">Location</h3>
                  <p className="text-muted-foreground">{profile.location}</p>
                </div>
              )}

              {!profile.bio && !profile.location && (
                <p className="text-muted-foreground italic">
                  No additional information available.
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* FE-PAGE-010: Tabs for Tracks, Playlists */}
        <Tabs defaultValue="tracks" className="w-full mt-6">
          <TabsList>
            <TabsTrigger value="posts">
              <MessageSquare className="mr-2 h-4 w-4" />
              Posts
            </TabsTrigger>
            <TabsTrigger value="tracks">
              <Music className="mr-2 h-4 w-4" />
              Tracks ({tracksData?.pagination.total || 0})
            </TabsTrigger>
            <TabsTrigger value="playlists">
              <Library className="mr-2 h-4 w-4" />
              Playlists ({playlistsData?.total || 0})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="posts" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Posts</CardTitle>
              </CardHeader>
              <CardContent>
                {isPostsLoading ? (
                  <div className="flex justify-center py-8">
                    <LoadingSpinner />
                  </div>
                ) : postsData?.posts && postsData.posts.length > 0 ? (
                  <div className="space-y-4">
                    {postsData.posts.map((post) => (
                      <Card key={post.id} className="p-4">
                        <div className="flex items-start gap-3">
                          <Avatar
                            src={post.author.avatar}
                            alt={post.author.name}
                            fallback={post.author.name[0]}
                          />
                          <div className="flex-1">
                            <div className="flex items-baseline justify-between">
                              <h4 className="font-semibold">
                                {post.author.name}{' '}
                                <span className="text-sm font-normal text-muted-foreground">
                                  {post.author.handle}
                                </span>
                              </h4>
                              <span className="text-xs text-muted-foreground">
                                {new Date(post.timestamp).toLocaleDateString()}
                              </span>
                            </div>
                            <p className="mt-2 text-sm">{post.content}</p>
                            <div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
                              <span>{post.likes} Likes</span>
                              <span>{post.comments} Comments</span>
                            </div>
                          </div>
                        </div>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <MessageSquare className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                    <h3 className="text-lg font-semibold mb-2">No posts yet</h3>
                    <p className="text-muted-foreground">
                      This user hasn't posted anything yet.
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="tracks" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Tracks</CardTitle>
              </CardHeader>
              <CardContent>
                {isTracksLoading ? (
                  <div className="flex justify-center py-8">
                    <LoadingSpinner />
                  </div>
                ) : tracksData?.tracks && tracksData.tracks.length > 0 ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {tracksData.tracks.map((track: Track) => (
                      <Link key={track.id} to={`/tracks/${track.id}`}>
                        <Card className="overflow-hidden hover:shadow-lg transition-shadow cursor-pointer">
                          <div className="relative aspect-square bg-muted flex items-center justify-center">
                            {track.cover_art_path ? (
                              <img
                                src={track.cover_art_path}
                                alt={track.title}
                                className="w-full h-full object-cover"
                              />
                            ) : (
                              <Music className="h-16 w-16 text-muted-foreground/50" />
                            )}
                          </div>
                          <CardContent className="p-4">
                            <h3 className="font-medium truncate">
                              {track.title}
                            </h3>
                            {track.artist && (
                              <p className="text-sm text-muted-foreground truncate">
                                {track.artist}
                              </p>
                            )}
                          </CardContent>
                        </Card>
                      </Link>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <Music className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                    <h3 className="text-lg font-semibold mb-2">
                      No tracks yet
                    </h3>
                    <p className="text-muted-foreground">
                      {currentUser?.id === profile.id
                        ? 'Start by uploading your first track to share with others.'
                        : 'This user has not uploaded any tracks yet.'}
                    </p>
                  </div>
                )}
                {tracksData && tracksData.pagination.total > 12 && (
                  <div className="mt-4 text-center">
                    <Button variant="outline" asChild>
                      <Link to={`/tracks?user_id=${profile.id}`}>
                        View All Tracks
                      </Link>
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="playlists" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Playlists</CardTitle>
              </CardHeader>
              <CardContent>
                {isPlaylistsLoading ? (
                  <div className="flex justify-center py-8">
                    <LoadingSpinner />
                  </div>
                ) : playlistsData?.playlists &&
                  playlistsData.playlists.length > 0 ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {playlistsData.playlists.map((playlist) => (
                      <Link key={playlist.id} to={`/playlists/${playlist.id}`}>
                        <PlaylistCard playlist={playlist} />
                      </Link>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <Library className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                    <h3 className="text-lg font-semibold mb-2">
                      No playlists yet
                    </h3>
                    <p className="text-muted-foreground">
                      {currentUser?.id === profile.id
                        ? 'Create your first playlist to organize your favorite tracks.'
                        : 'This user has not created any playlists yet.'}
                    </p>
                  </div>
                )}
                {playlistsData && playlistsData.total > 12 && (
                  <div className="mt-4 text-center">
                    <Button variant="outline" asChild>
                      <Link to={`/playlists?user_id=${profile.id}`}>
                        View All Playlists
                      </Link>
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
