import { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Search, Music, Library, Users, X } from 'lucide-react';
import { searchTracks } from '@/features/tracks/services/trackListService';
import { searchPlaylists } from '@/features/playlists/services/playlistService';
import { searchUsers } from '@/features/search/services/searchService';
import { PlaylistCard } from '@/features/playlists/components/PlaylistCard';
import { Avatar } from '@/components/ui/avatar';
import { Link } from 'react-router-dom';
import { useDebounce } from '@/hooks/useDebounce';
import { Pagination } from '@/components/navigation/Pagination';
import type { Track } from '@/features/player/types';
import type { Playlist } from '@/features/playlists/types';

// FE-PAGE-013: Add Search page

type SearchType = 'all' | 'tracks' | 'playlists' | 'users';

export function SearchPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState(searchParams.get('q') || '');
  const [activeTab, setActiveTab] = useState<SearchType>(
    (searchParams.get('type') as SearchType) || 'all',
  );
  const [page, setPage] = useState(1);
  const limit = 20;

  const debouncedQuery = useDebounce(searchQuery, 500);

  // Update URL when query or tab changes
  useEffect(() => {
    const params = new URLSearchParams();
    if (debouncedQuery) params.set('q', debouncedQuery);
    if (activeTab !== 'all') params.set('type', activeTab);
    setSearchParams(params, { replace: true });
  }, [debouncedQuery, activeTab, setSearchParams]);

  // Reset page when query or tab changes
  useEffect(() => {
    setPage(1);
  }, [debouncedQuery, activeTab]);

  // Search Tracks
  const {
    data: tracksData,
    isLoading: isTracksLoading,
    isError: isTracksError,
  } = useQuery({
    queryKey: ['searchTracks', debouncedQuery, page, limit],
    queryFn: () =>
      searchTracks(debouncedQuery, {
        pagination: { page, limit },
      }),
    enabled:
      (activeTab === 'all' || activeTab === 'tracks') &&
      !!debouncedQuery.trim(),
  });

  // Search Playlists
  const {
    data: playlistsData,
    isLoading: isPlaylistsLoading,
    isError: isPlaylistsError,
  } = useQuery({
    queryKey: ['searchPlaylists', debouncedQuery, page, limit],
    queryFn: () =>
      searchPlaylists({
        q: debouncedQuery,
        page,
        limit,
      }),
    enabled:
      (activeTab === 'all' || activeTab === 'playlists') &&
      !!debouncedQuery.trim(),
  });

  // Search Users
  const {
    data: usersData,
    isLoading: isUsersLoading,
    isError: isUsersError,
  } = useQuery({
    queryKey: ['searchUsers', debouncedQuery, page, limit],
    queryFn: () =>
      searchUsers({
        query: debouncedQuery,
        page,
        limit,
      }),
    enabled:
      (activeTab === 'all' || activeTab === 'users') && !!debouncedQuery.trim(),
  });

  const tracks = tracksData?.data || [];
  const playlists = playlistsData?.playlists || [];
  const users = usersData?.users || [];

  const totalTracks = tracksData?.total || 0;
  const totalPlaylists = playlistsData?.total || 0;
  const totalUsers = usersData?.total || 0;

  const totalResults = totalTracks + totalPlaylists + totalUsers;
  const isLoading = isTracksLoading || isPlaylistsLoading || isUsersLoading;
  const hasError = isTracksError || isPlaylistsError || isUsersError;

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      setPage(1);
    }
  };

  const handleClear = () => {
    setSearchQuery('');
    setPage(1);
  };

  const hasResults = totalResults > 0;
  const hasQuery = debouncedQuery.trim().length > 0;

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold mb-2">Search</h1>
          <p className="text-muted-foreground">
            Search for tracks, playlists, and users
          </p>
        </div>

        {/* Search Bar */}
        <Card className="mb-6">
          <CardContent className="pt-6">
            <form onSubmit={handleSearch} className="space-y-4">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                <Input
                  type="text"
                  placeholder="Search tracks, playlists, users..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-10"
                />
                {searchQuery && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="absolute right-1 top-1/2 transform -translate-y-1/2 h-8 w-8"
                    onClick={handleClear}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                )}
              </div>
            </form>
          </CardContent>
        </Card>

        {/* Results */}
        {hasQuery && (
          <div className="space-y-6">
            {isLoading && (
              <div className="flex justify-center py-12">
                <LoadingSpinner />
              </div>
            )}

            {hasError && (
              <Card>
                <CardContent className="pt-6">
                  <div className="text-center text-destructive">
                    <p>An error occurred while searching. Please try again.</p>
                  </div>
                </CardContent>
              </Card>
            )}

            {!isLoading && !hasError && !hasResults && (
              <Card>
                <CardContent className="pt-6">
                  <div className="text-center py-12">
                    <Search className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                    <p className="text-muted-foreground">
                      No results found for &quot;{debouncedQuery}&quot;
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}

            {!isLoading && !hasError && hasResults && (
              <Tabs
                value={activeTab}
                onValueChange={(v) => setActiveTab(v as SearchType)}
              >
                <TabsList className="grid w-full grid-cols-4">
                  <TabsTrigger value="all">All ({totalResults})</TabsTrigger>
                  <TabsTrigger value="tracks">
                    <Music className="h-4 w-4 mr-2" />
                    Tracks ({totalTracks})
                  </TabsTrigger>
                  <TabsTrigger value="playlists">
                    <Library className="h-4 w-4 mr-2" />
                    Playlists ({totalPlaylists})
                  </TabsTrigger>
                  <TabsTrigger value="users">
                    <Users className="h-4 w-4 mr-2" />
                    Users ({totalUsers})
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="all" className="mt-6">
                  <div className="space-y-6">
                    {/* Tracks */}
                    {totalTracks > 0 && (
                      <div>
                        <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
                          <Music className="h-5 w-5" />
                          Tracks ({totalTracks})
                        </h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {tracks.slice(0, 6).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 ? (
                                    <img
                                      src={track.cover}
                                      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>
                        {totalTracks > 6 && (
                          <div className="mt-4 text-center">
                            <Button
                              variant="outline"
                              onClick={() => setActiveTab('tracks')}
                            >
                              View All Tracks
                            </Button>
                          </div>
                        )}
                      </div>
                    )}

                    {/* Playlists */}
                    {totalPlaylists > 0 && (
                      <div>
                        <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
                          <Library className="h-5 w-5" />
                          Playlists ({totalPlaylists})
                        </h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {playlists.slice(0, 6).map((playlist: Playlist) => (
                            <Link
                              key={playlist.id}
                              to={`/playlists/${playlist.id}`}
                            >
                              <PlaylistCard playlist={playlist} />
                            </Link>
                          ))}
                        </div>
                        {totalPlaylists > 6 && (
                          <div className="mt-4 text-center">
                            <Button
                              variant="outline"
                              onClick={() => setActiveTab('playlists')}
                            >
                              View All Playlists
                            </Button>
                          </div>
                        )}
                      </div>
                    )}

                    {/* Users */}
                    {totalUsers > 0 && (
                      <div>
                        <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
                          <Users className="h-5 w-5" />
                          Users ({totalUsers})
                        </h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {users.slice(0, 6).map((user) => (
                            <Link key={user.id} to={`/u/${user.username}`}>
                              <Card className="hover:shadow-lg transition-shadow cursor-pointer">
                                <CardContent className="p-4">
                                  <div className="flex items-center gap-4">
                                    <Avatar
                                      src={user.avatar_url || ''}
                                      fallback={user.username[0].toUpperCase()}
                                      size="md"
                                    />
                                    <div className="flex-1 min-w-0">
                                      <h3 className="font-medium truncate">
                                        {user.username}
                                      </h3>
                                      {user.first_name || user.last_name ? (
                                        <p className="text-sm text-muted-foreground truncate">
                                          {user.first_name} {user.last_name}
                                        </p>
                                      ) : null}
                                    </div>
                                  </div>
                                </CardContent>
                              </Card>
                            </Link>
                          ))}
                        </div>
                        {totalUsers > 6 && (
                          <div className="mt-4 text-center">
                            <Button
                              variant="outline"
                              onClick={() => setActiveTab('users')}
                            >
                              View All Users
                            </Button>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </TabsContent>

                <TabsContent value="tracks" className="mt-6">
                  {isTracksLoading ? (
                    <div className="flex justify-center py-12">
                      <LoadingSpinner />
                    </div>
                  ) : totalTracks === 0 ? (
                    <Card>
                      <CardContent className="pt-6">
                        <div className="text-center py-12">
                          <Music className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                          <p className="text-muted-foreground">
                            No tracks found
                          </p>
                        </div>
                      </CardContent>
                    </Card>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {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 ? (
                                <img
                                  src={track.cover}
                                  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>
                  )}
                  {/* FE-COMP-006: Pagination component */}
                  {totalTracks > limit && (
                    <Pagination
                      currentPage={page}
                      totalPages={Math.ceil(totalTracks / limit)}
                      onPageChange={setPage}
                      totalItems={totalTracks}
                      itemsPerPage={limit}
                      showItemsInfo={true}
                      className="mt-6"
                    />
                  )}
                </TabsContent>

                <TabsContent value="playlists" className="mt-6">
                  {isPlaylistsLoading ? (
                    <div className="flex justify-center py-12">
                      <LoadingSpinner />
                    </div>
                  ) : totalPlaylists === 0 ? (
                    <Card>
                      <CardContent className="pt-6">
                        <div className="text-center py-12">
                          <Library className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                          <p className="text-muted-foreground">
                            No playlists found
                          </p>
                        </div>
                      </CardContent>
                    </Card>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {playlists.map((playlist: Playlist) => (
                        <Link
                          key={playlist.id}
                          to={`/playlists/${playlist.id}`}
                        >
                          <PlaylistCard playlist={playlist} />
                        </Link>
                      ))}
                    </div>
                  )}
                  {/* FE-COMP-006: Pagination component */}
                  {totalPlaylists > limit && (
                    <Pagination
                      currentPage={page}
                      totalPages={Math.ceil(totalPlaylists / limit)}
                      onPageChange={setPage}
                      totalItems={totalPlaylists}
                      itemsPerPage={limit}
                      showItemsInfo={true}
                      className="mt-6"
                    />
                  )}
                </TabsContent>

                <TabsContent value="users" className="mt-6">
                  {isUsersLoading ? (
                    <div className="flex justify-center py-12">
                      <LoadingSpinner />
                    </div>
                  ) : totalUsers === 0 ? (
                    <Card>
                      <CardContent className="pt-6">
                        <div className="text-center py-12">
                          <Users className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                          <p className="text-muted-foreground">
                            No users found
                          </p>
                        </div>
                      </CardContent>
                    </Card>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {users.map((user) => (
                        <Link key={user.id} to={`/u/${user.username}`}>
                          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
                            <CardContent className="p-4">
                              <div className="flex items-center gap-4">
                                <Avatar
                                  src={user.avatar_url || ''}
                                  fallback={user.username[0].toUpperCase()}
                                  size="md"
                                />
                                <div className="flex-1 min-w-0">
                                  <h3 className="font-medium truncate">
                                    {user.username}
                                  </h3>
                                  {user.first_name || user.last_name ? (
                                    <p className="text-sm text-muted-foreground truncate">
                                      {user.first_name} {user.last_name}
                                    </p>
                                  ) : null}
                                  {user.bio && (
                                    <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
                                      {user.bio}
                                    </p>
                                  )}
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        </Link>
                      ))}
                    </div>
                  )}
                  {/* FE-COMP-006: Pagination component */}
                  {totalUsers > limit && (
                    <Pagination
                      currentPage={page}
                      totalPages={Math.ceil(totalUsers / limit)}
                      onPageChange={setPage}
                      totalItems={totalUsers}
                      itemsPerPage={limit}
                      showItemsInfo={true}
                      className="mt-6"
                    />
                  )}
                </TabsContent>
              </Tabs>
            )}
          </div>
        )}

        {/* Empty State - No Query */}
        {!hasQuery && (
          <Card>
            <CardContent className="pt-6">
              <div className="text-center py-12">
                <Search className="h-16 w-16 mx-auto mb-4 text-muted-foreground opacity-50" />
                <h2 className="text-xl font-semibold mb-2">Start Searching</h2>
                <p className="text-muted-foreground">
                  Enter a search query to find tracks, playlists, and users
                </p>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
