import { useState, useEffect, useCallback } from 'react';
import { Typography, Spin, Empty, Button, Grid, Input, Popconfirm, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ShareAltOutlined, LockOutlined, GlobalOutlined, SearchOutlined } from '@ant-design/icons';
import FeaturedPlaylistCarousel from '@/components/media/FeaturedPlaylistCarousel';
import PlaylistCard from '@/components/media/PlaylistCard';
import CreatePlaylistModal from '@/components/media/CreatePlaylistModal';
import EditPlaylistModal from '@/components/media/EditPlaylistModal';
import { mediaPublicApi } from '@/lib/media-public-api';
import { mediaApi } from '@/lib/media-api';
import { useAuthStore } from '@/stores/auth.store';
import { useDebounce } from '@/hooks/useDebounce';
import type { PlaylistSummary } from '@/types/media';

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;

export default function PlaylistBrowsePage() {
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const user = useAuthStore((s) => s.user);

  const [popularPlaylists, setPopularPlaylists] = useState<PlaylistSummary[]>([]);
  const [myPlaylists, setMyPlaylists] = useState<PlaylistSummary[]>([]);
  const [loadingPopular, setLoadingPopular] = useState(true);
  const [loadingMy, setLoadingMy] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  const [editPlaylistId, setEditPlaylistId] = useState<number | null>(null);

  // Search state
  const [searchInput, setSearchInput] = useState('');
  const debouncedSearch = useDebounce(searchInput, 300);
  const [searchResults, setSearchResults] = useState<PlaylistSummary[]>([]);
  const [searchTotal, setSearchTotal] = useState(0);
  const [searchLoading, setSearchLoading] = useState(false);
  const [searchPage, setSearchPage] = useState(1);
  const searchPageSize = 24;

  const isSearching = debouncedSearch.trim().length > 0;

  const fetchPopular = useCallback(async () => {
    try {
      setLoadingPopular(true);
      const { data } = await mediaPublicApi.get('/playlists/popular', {
        params: { limit: 12 },
      });
      setPopularPlaylists(data.data || []);
    } catch {
      // Silent
    } finally {
      setLoadingPopular(false);
    }
  }, []);

  const fetchMyPlaylists = useCallback(async () => {
    if (!user) return;
    try {
      setLoadingMy(true);
      const { data } = await mediaApi.get('/playlists/my');
      setMyPlaylists(data.data || []);
    } catch {
      // Silent
    } finally {
      setLoadingMy(false);
    }
  }, [user]);

  // Search effect
  useEffect(() => {
    if (!isSearching) {
      setSearchResults([]);
      setSearchTotal(0);
      return;
    }

    const doSearch = async () => {
      try {
        setSearchLoading(true);
        const { data } = await mediaPublicApi.get('/playlists/popular', {
          params: {
            search: debouncedSearch,
            limit: searchPageSize,
            offset: (searchPage - 1) * searchPageSize,
          },
        });
        setSearchResults(data.data || []);
        setSearchTotal(data.total || 0);
      } catch {
        // Silent
      } finally {
        setSearchLoading(false);
      }
    };

    doSearch();
  }, [debouncedSearch, searchPage, isSearching]);

  // Reset search page when query changes
  useEffect(() => {
    setSearchPage(1);
  }, [debouncedSearch]);

  useEffect(() => {
    fetchPopular();
  }, [fetchPopular]);

  useEffect(() => {
    fetchMyPlaylists();
  }, [fetchMyPlaylists]);

  const handleDelete = async (playlistId: number) => {
    try {
      await mediaApi.delete(`/playlists/${playlistId}`);
      message.success('Playlist deleted');
      fetchMyPlaylists();
      fetchPopular();
    } catch {
      message.error('Failed to delete playlist');
    }
  };

  const handleShare = async (playlist: PlaylistSummary) => {
    try {
      let shareToken = playlist.shareToken;
      if (!shareToken) {
        const { data } = await mediaApi.post(`/playlists/${playlist.id}/share`);
        shareToken = data.shareToken;
      }
      const url = `${window.location.origin}/gallery/curated/share/${shareToken}`;
      await navigator.clipboard.writeText(url);
      message.success('Share link copied to clipboard');
    } catch {
      message.error('Failed to generate share link');
    }
  };

  const gridStyle = {
    display: 'grid',
    gridTemplateColumns: isMobile
      ? '1fr'
      : 'repeat(auto-fill, minmax(260px, 1fr))',
    gap: 16,
  };

  const totalSearchPages = Math.ceil(searchTotal / searchPageSize);

  return (
    <div>
      {/* Search bar */}
      <div style={{ marginBottom: 24 }}>
        <Input
          placeholder="Search playlists..."
          prefix={<SearchOutlined />}
          value={searchInput}
          onChange={(e) => setSearchInput(e.target.value)}
          allowClear
          size="large"
          style={{ maxWidth: 500 }}
        />
      </div>

      {isSearching ? (
        /* Search results mode */
        <div style={{ marginBottom: 32 }}>
          <Title level={5} style={{ marginBottom: 16 }}>
            {searchLoading
              ? 'Searching...'
              : `${searchTotal} result${searchTotal !== 1 ? 's' : ''} for "${debouncedSearch}"`}
          </Title>

          {searchLoading ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <Spin />
            </div>
          ) : searchResults.length === 0 ? (
            <Empty description="No playlists found" />
          ) : (
            <>
              <div style={gridStyle}>
                {searchResults.map((p) => (
                  <PlaylistCard key={p.id} playlist={p} />
                ))}
              </div>

              {/* Pagination */}
              {totalSearchPages > 1 && (
                <div style={{ textAlign: 'center', marginTop: 24 }}>
                  <Button
                    disabled={searchPage <= 1}
                    onClick={() => setSearchPage((p) => p - 1)}
                    style={{ marginRight: 8 }}
                  >
                    Previous
                  </Button>
                  <Text type="secondary">
                    Page {searchPage} of {totalSearchPages}
                  </Text>
                  <Button
                    disabled={searchPage >= totalSearchPages}
                    onClick={() => setSearchPage((p) => p + 1)}
                    style={{ marginLeft: 8 }}
                  >
                    Next
                  </Button>
                </div>
              )}
            </>
          )}
        </div>
      ) : (
        /* Normal browse mode */
        <>
          {/* Featured Playlists */}
          <FeaturedPlaylistCarousel />

          {/* Popular Playlists */}
          <div style={{ marginBottom: 32 }}>
            <Title level={5} style={{ marginBottom: 16 }}>
              Popular Playlists
            </Title>

            {loadingPopular ? (
              <div style={{ textAlign: 'center', padding: 40 }}>
                <Spin />
              </div>
            ) : popularPlaylists.length === 0 ? (
              <Empty description="No public playlists yet" />
            ) : (
              <div style={gridStyle}>
                {popularPlaylists.map((p) => (
                  <PlaylistCard key={p.id} playlist={p} />
                ))}
              </div>
            )}
          </div>

          {/* My Playlists (authenticated only) */}
          {user && (
            <div style={{ marginBottom: 32 }}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  marginBottom: 16,
                }}
              >
                <Title level={5} style={{ margin: 0 }}>
                  My Playlists
                </Title>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => setCreateOpen(true)}
                >
                  Create Playlist
                </Button>
              </div>

              {loadingMy ? (
                <div style={{ textAlign: 'center', padding: 40 }}>
                  <Spin />
                </div>
              ) : myPlaylists.length === 0 ? (
                <Empty description="You haven't created any playlists yet">
                  <Button type="primary" onClick={() => setCreateOpen(true)}>
                    Create Your First Playlist
                  </Button>
                </Empty>
              ) : (
                <div style={gridStyle}>
                  {myPlaylists.map((p) => (
                    <div key={p.id} style={{ position: 'relative' }}>
                      <PlaylistCard playlist={p} />
                      {/* Action overlay */}
                      <div
                        style={{
                          position: 'absolute',
                          top: 8,
                          right: 8,
                          display: 'flex',
                          gap: 4,
                          zIndex: 10,
                        }}
                      >
                        <Button
                          size="small"
                          type="primary"
                          ghost
                          icon={p.isPublic ? <GlobalOutlined /> : <LockOutlined />}
                          style={{ fontSize: 11, padding: '0 6px', height: 24 }}
                          title={p.isPublic ? 'Public' : 'Private'}
                        />
                        <Button
                          size="small"
                          icon={<ShareAltOutlined />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleShare(p);
                          }}
                          style={{ padding: '0 6px', height: 24 }}
                        />
                        <Button
                          size="small"
                          icon={<EditOutlined />}
                          onClick={(e) => {
                            e.stopPropagation();
                            setEditPlaylistId(p.id);
                          }}
                          style={{ padding: '0 6px', height: 24 }}
                        />
                        <Popconfirm
                          title="Delete this playlist?"
                          onConfirm={() => handleDelete(p.id)}
                          okText="Delete"
                          okType="danger"
                        >
                          <Button
                            size="small"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={(e) => e.stopPropagation()}
                            style={{ padding: '0 6px', height: 24 }}
                          />
                        </Popconfirm>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </>
      )}

      {/* Modals */}
      <CreatePlaylistModal
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        onCreated={() => {
          fetchMyPlaylists();
          fetchPopular();
        }}
      />
      <EditPlaylistModal
        playlistId={editPlaylistId}
        open={!!editPlaylistId}
        onClose={() => setEditPlaylistId(null)}
        onUpdated={() => {
          fetchMyPlaylists();
          fetchPopular();
        }}
      />
    </div>
  );
}
