import { useState, useEffect, useCallback } from 'react';
import { Row, Col, Input, Select, Button, Pagination, message, Empty, Spin, Tooltip, Modal, Segmented, Grid } from 'antd';
import {
  SearchOutlined,
  GlobalOutlined,
  DeleteOutlined,
  AppstoreOutlined,
  BarsOutlined,
  UploadOutlined,
  CalendarOutlined,
  CloudDownloadOutlined,
  ThunderboltOutlined,
  OrderedListOutlined,
  LockOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  FolderOutlined,
  FolderAddOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { mediaApi } from '@/lib/media-api';
import { useDebounce } from '@/hooks/useDebounce';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import type { Video, VideosListResponse, VideosListParams, Photo, PhotosListResponse, PhotoAlbum } from '@/types/media';
import type { AppOutletContext } from '@/types/api';
import VideoCard from '@/components/media/VideoCard';
import PhotoCard from '@/components/media/PhotoCard';
import AlbumCard from '@/components/media/AlbumCard';
import BulkActionsBar from '@/components/media/BulkActionsBar';
import PublishModal from '@/components/media/PublishModal';
import DeleteConfirmModal from '@/components/media/DeleteConfirmModal';
import UploadVideoDrawer from '@/components/media/UploadVideoDrawer';
import UploadPhotoDrawer from '@/components/media/UploadPhotoDrawer';
import VideoViewerModal from '@/components/media/VideoViewerModal';
import PhotoViewerModal from '@/components/media/PhotoViewerModal';
import EditPhotoModal from '@/components/media/EditPhotoModal';
import AlbumDetailDrawer from '@/components/media/AlbumDetailDrawer';
import CreateAlbumModal from '@/components/media/CreateAlbumModal';
import QuickAnalyticsModal from '@/components/media/QuickAnalyticsModal';
import SchedulePublishModal from '@/components/media/SchedulePublishModal';
import ScheduleCalendarDrawer from '@/components/media/ScheduleCalendarDrawer';
import EditVideoModal from '@/components/media/EditVideoModal';
import FetchVideosDrawer from '@/components/media/FetchVideosDrawer';
import AddToPlaylistModal from '@/components/media/AddToPlaylistModal';
import BulkAddToPlaylistModal from '@/components/media/BulkAddToPlaylistModal';
import BulkAccessLevelModal from '@/components/media/BulkAccessLevelModal';
import DocumentsTab from '@/pages/media/DocumentsTab';
import { getErrorMessage } from '@/utils/getErrorMessage';
import { PageTour } from '@/components/tour/PageTour';

type MediaTab = 'Videos' | 'Photos' | 'Albums' | 'Documents';

export default function LibraryPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [mediaTab, setMediaTab] = useLocalStorage<MediaTab>('libraryMediaTab', 'Videos');

  // === Video state ===
  const [videos, setVideos] = useState<Video[]>([]);
  const [videoPagination, setVideoPagination] = useState({ page: 1, limit: 48, total: 0 });
  const [selectedVideoIds, setSelectedVideoIds] = useState<number[]>([]);
  const [viewerVideo, setViewerVideo] = useState<Video | null>(null);
  const [analyticsVideoId, setAnalyticsVideoId] = useState<number | null>(null);
  const [analyticsVideoTitle, setAnalyticsVideoTitle] = useState<string>('');
  const [scheduleVideo, setScheduleVideo] = useState<Video | null>(null);
  const [calendarModalOpen, setCalendarModalOpen] = useState(false);
  const [editVideo, setEditVideo] = useState<Video | null>(null);
  const [fetchDrawerOpen, setFetchDrawerOpen] = useState(false);
  const [shortsFilter, setShortsFilter] = useState<boolean | undefined>();
  const [scanningShorts, setScanningShorts] = useState(false);
  const [playlistVideoId, setPlaylistVideoId] = useState<number | null>(null);
  const [bulkPlaylistOpen, setBulkPlaylistOpen] = useState(false);
  const [bulkAccessLevelOpen, setBulkAccessLevelOpen] = useState(false);
  const [publishModalOpen, setPublishModalOpen] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [uploadVideoOpen, setUploadVideoOpen] = useState(false);

  // === Photo state ===
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [photoPagination, setPhotoPagination] = useState({ page: 1, limit: 48, total: 0 });
  const [selectedPhotoIds, setSelectedPhotoIds] = useState<number[]>([]);
  const [viewerPhoto, setViewerPhoto] = useState<Photo | null>(null);
  const [editPhoto, setEditPhoto] = useState<Photo | null>(null);
  const [uploadPhotoOpen, setUploadPhotoOpen] = useState(false);
  const [createAlbumOpen, setCreateAlbumOpen] = useState(false);
  const [formatFilter, setFormatFilter] = useState<string | undefined>();
  const [photoFormats, setPhotoFormats] = useState<string[]>([]);

  // === Album state ===
  const [albums, setAlbums] = useState<PhotoAlbum[]>([]);
  const [albumPagination, setAlbumPagination] = useState({ page: 1, limit: 48, total: 0 });
  const [selectedAlbumId, setSelectedAlbumId] = useState<number | null>(null);

  // === Shared state ===
  const [search, setSearch] = useState('');
  const [debouncedSearch] = useDebounce(search, 300);
  const [orientation, setOrientation] = useState<'H' | 'V' | 'S' | undefined>();
  const [selectedProducers, setSelectedProducers] = useState<string[]>([]);
  const [producers, setProducers] = useState<string[]>([]);
  const [viewMode, setViewMode] = useLocalStorage<'grid' | 'compact'>('mediaViewMode', 'grid');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setPageHeader({
      title: 'Media Library',
      subtitle: 'Manage videos, photos, and albums',
    });
  }, [setPageHeader]);

  useEffect(() => {
    fetchProducers();
    fetchPhotoFormats();
  }, []);

  // Fetch data when tab or filters change
  useEffect(() => {
    if (mediaTab === 'Videos') fetchVideos();
    else if (mediaTab === 'Photos') fetchPhotos();
    else if (mediaTab === 'Albums') fetchAlbums();
  }, [mediaTab, debouncedSearch, orientation, selectedProducers, shortsFilter, formatFilter,
      videoPagination.page, videoPagination.limit,
      photoPagination.page, photoPagination.limit,
      albumPagination.page, albumPagination.limit]);

  const fetchProducers = async () => {
    try {
      const { data } = await mediaApi.get<string[]>('/videos/producers');
      setProducers(data);
    } catch { /* ignore */ }
  };

  const fetchPhotoFormats = async () => {
    try {
      const { data } = await mediaApi.get<string[]>('/photos/formats');
      setPhotoFormats(data);
    } catch { /* ignore */ }
  };

  // === Video fetching ===
  const fetchVideos = useCallback(async () => {
    setLoading(true);
    try {
      const params: VideosListParams = {
        search: debouncedSearch || undefined,
        orientation: orientation === 'S' ? undefined : orientation as 'H' | 'V' | undefined,
        producers: selectedProducers.length > 0 ? selectedProducers : undefined,
        isShort: shortsFilter,
        offset: (videoPagination.page - 1) * videoPagination.limit,
        limit: videoPagination.limit,
      };
      const { data } = await mediaApi.get<VideosListResponse>('/videos', { params });
      setVideos(data.videos);
      setVideoPagination((prev) => ({ ...prev, total: data.total }));
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to load videos'));
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch, orientation, selectedProducers, shortsFilter, videoPagination.page, videoPagination.limit]);

  // === Photo fetching ===
  const fetchPhotos = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = {
        search: debouncedSearch || undefined,
        orientation,
        producer: selectedProducers[0] || undefined,
        format: formatFilter,
        offset: (photoPagination.page - 1) * photoPagination.limit,
        limit: photoPagination.limit,
      };
      const { data } = await mediaApi.get<PhotosListResponse>('/photos', { params });
      setPhotos(data.photos);
      setPhotoPagination((prev) => ({ ...prev, total: data.total }));
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to load photos'));
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch, orientation, selectedProducers, formatFilter, photoPagination.page, photoPagination.limit]);

  // === Album fetching ===
  const fetchAlbums = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = {
        search: debouncedSearch || undefined,
        offset: (albumPagination.page - 1) * albumPagination.limit,
        limit: albumPagination.limit,
      };
      const { data } = await mediaApi.get('/albums', { params });
      setAlbums(data.albums || []);
      setAlbumPagination((prev) => ({ ...prev, total: data.total }));
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to load albums'));
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch, albumPagination.page, albumPagination.limit]);

  // === Video handlers ===
  const handleScanShorts = async () => {
    setScanningShorts(true);
    try {
      const { data } = await mediaApi.post<{ classified: number; declassified: number; totalShorts: number }>('/shorts/scan');
      message.success(`Classified ${data.classified} shorts, declassified ${data.declassified}. Total shorts: ${data.totalShorts}`);
      fetchVideos();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to scan shorts'));
    } finally {
      setScanningShorts(false);
    }
  };

  const handleVideoSelect = (id: number) => {
    setSelectedVideoIds((prev) =>
      prev.includes(id) ? prev.filter((vid) => vid !== id) : [...prev, id]
    );
  };

  const handleVideoSelectAll = () => {
    if (selectedVideoIds.length === videos.length) setSelectedVideoIds([]);
    else setSelectedVideoIds(videos.map((v) => v.id));
  };

  const handleVideoDelete = async () => {
    setDeleting(true);
    try {
      await Promise.all(selectedVideoIds.map((id) => mediaApi.delete(`/videos/${id}`)));
      message.success(`Deleted ${selectedVideoIds.length} video(s)`);
      setDeleteModalOpen(false);
      setSelectedVideoIds([]);
      fetchVideos();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to delete videos'));
    } finally {
      setDeleting(false);
    }
  };

  const handleDeleteSingleVideo = (video: Video) => {
    Modal.confirm({
      title: 'Delete this video?',
      content: video.title || video.filename,
      okText: 'Delete',
      okType: 'danger',
      onOk: async () => {
        try {
          await mediaApi.delete(`/videos/${video.id}`);
          message.success('Video deleted');
          fetchVideos();
        } catch (error: unknown) {
          message.error(getErrorMessage(error, 'Failed to delete video'));
        }
      },
    });
  };

  const handleToggleVideoPublish = async (video: Video) => {
    try {
      if (video.isPublished) {
        await mediaApi.post(`/videos/${video.id}/unpublish`);
        message.success(`"${video.title || video.filename}" unpublished`);
      } else {
        await mediaApi.post(`/videos/${video.id}/publish`, { category: 'videos' });
        message.success(`"${video.title || video.filename}" published`);
      }
      fetchVideos();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to toggle publish'));
    }
  };

  // === Photo handlers ===
  const handlePhotoSelect = (id: number) => {
    setSelectedPhotoIds((prev) =>
      prev.includes(id) ? prev.filter((pid) => pid !== id) : [...prev, id]
    );
  };

  const handlePhotoSelectAll = () => {
    if (selectedPhotoIds.length === photos.length) setSelectedPhotoIds([]);
    else setSelectedPhotoIds(photos.map((p) => p.id));
  };

  const handleTogglePhotoPublish = async (photo: Photo) => {
    try {
      if (photo.isPublished) {
        await mediaApi.post(`/photos/${photo.id}/unpublish`);
        message.success('Photo unpublished');
      } else {
        await mediaApi.post(`/photos/${photo.id}/publish`);
        message.success('Photo published');
      }
      fetchPhotos();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to toggle publish'));
    }
  };

  const handleDeleteSinglePhoto = (photo: Photo) => {
    Modal.confirm({
      title: 'Delete this photo?',
      content: photo.title || photo.originalFilename || photo.filename,
      okText: 'Delete',
      okType: 'danger',
      onOk: async () => {
        try {
          await mediaApi.delete(`/photos/${photo.id}`);
          message.success('Photo deleted');
          fetchPhotos();
        } catch (error: unknown) {
          message.error(getErrorMessage(error, 'Failed to delete photo'));
        }
      },
    });
  };

  const handleBulkPhotoPublish = async () => {
    try {
      await mediaApi.post('/photos/bulk-publish', { ids: selectedPhotoIds });
      message.success(`Published ${selectedPhotoIds.length} photos`);
      setSelectedPhotoIds([]);
      fetchPhotos();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to publish photos'));
    }
  };

  const handleBulkPhotoDelete = async () => {
    try {
      await mediaApi.post('/photos/bulk-delete', { ids: selectedPhotoIds });
      message.success(`Deleted ${selectedPhotoIds.length} photos`);
      setSelectedPhotoIds([]);
      fetchPhotos();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to delete photos'));
    }
  };

  // Tab change clears selections
  const handleTabChange = (tab: string | number) => {
    setMediaTab(tab as MediaTab);
    setSelectedVideoIds([]);
    setSelectedPhotoIds([]);
    setSearch('');
  };

  const colSpan = viewMode === 'grid' ? { xs: 12, sm: 8, md: 6, lg: 4 } : { xs: 24, sm: 12, md: 8 };

  // Current pagination for active tab
  const activePagination = mediaTab === 'Videos' ? videoPagination : mediaTab === 'Photos' ? photoPagination : albumPagination;

  return (
    <div>
      {/* Media Type Toggle */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }} data-tour-media-tabs>
        <Segmented
          value={mediaTab}
          onChange={handleTabChange}
          options={[
            { value: 'Videos', icon: <VideoCameraOutlined />, label: 'Videos' },
            { value: 'Photos', icon: <PictureOutlined />, label: 'Photos' },
            { value: 'Albums', icon: <FolderOutlined />, label: 'Albums' },
            { value: 'Documents', icon: <FileTextOutlined />, label: 'Documents' },
          ]}
        />
      </div>

      {/* Documents tab owns its own layout */}
      {mediaTab === 'Documents' && <DocumentsTab />}

      {/* Toolbar — hidden for Documents tab */}
      {mediaTab !== 'Documents' && (
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center', marginBottom: 12 }} data-tour-media-filters>
        <Input
          placeholder={`Search ${mediaTab.toLowerCase()}...`}
          prefix={<SearchOutlined />}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          allowClear
          style={{ width: isMobile ? '100%' : 200 }}
        />

        {/* Orientation filter (Videos + Photos) */}
        {mediaTab !== 'Albums' && (
          <Select
            placeholder="Orientation"
            options={[
              { value: 'H', label: 'Horizontal' },
              { value: 'V', label: 'Vertical' },
              ...(mediaTab === 'Photos' ? [{ value: 'S', label: 'Square' }] : []),
            ]}
            value={orientation}
            onChange={setOrientation}
            allowClear
            style={{ width: 120 }}
          />
        )}

        {/* Producer filter (Videos + Photos) */}
        {mediaTab !== 'Albums' && (
          <Select
            mode="multiple"
            placeholder="Producer"
            options={producers.map((p) => ({ value: p, label: p }))}
            value={selectedProducers}
            onChange={setSelectedProducers}
            style={{ width: 140 }}
            maxTagCount={1}
          />
        )}

        {/* Video-specific: Shorts filter */}
        {mediaTab === 'Videos' && (
          <Select
            placeholder="Shorts"
            options={[
              { value: 'true', label: 'Shorts' },
              { value: 'false', label: 'Non-Shorts' },
            ]}
            value={shortsFilter === undefined ? undefined : String(shortsFilter)}
            onChange={(v) => setShortsFilter(v === undefined ? undefined : v === 'true')}
            allowClear
            style={{ width: 110 }}
          />
        )}

        {/* Photo-specific: Format filter */}
        {mediaTab === 'Photos' && photoFormats.length > 0 && (
          <Select
            placeholder="Format"
            options={photoFormats.map((f) => ({ value: f, label: f.toUpperCase() }))}
            value={formatFilter}
            onChange={setFormatFilter}
            allowClear
            style={{ width: 100 }}
          />
        )}

        <div style={{ flex: 1 }} />

        {/* Upload button */}
        {mediaTab === 'Videos' && (
          <>
            <Button type="primary" icon={<UploadOutlined />} onClick={() => setUploadVideoOpen(true)} data-tour-media-upload>Upload</Button>
            <Tooltip title="Fetch from URL">
              <Button icon={<CloudDownloadOutlined />} onClick={() => setFetchDrawerOpen(true)} />
            </Tooltip>
            <Tooltip title="Scan Shorts">
              <Button icon={<ThunderboltOutlined />} onClick={handleScanShorts} loading={scanningShorts} />
            </Tooltip>
            <Tooltip title="Schedule Calendar">
              <Button icon={<CalendarOutlined />} onClick={() => setCalendarModalOpen(true)} />
            </Tooltip>
          </>
        )}
        {mediaTab === 'Photos' && (
          <>
            <Button type="primary" icon={<UploadOutlined />} onClick={() => setUploadPhotoOpen(true)}>Upload</Button>
            {selectedPhotoIds.length >= 2 && (
              <Tooltip title="Create Album from Selected">
                <Button icon={<FolderAddOutlined />} onClick={() => setCreateAlbumOpen(true)}>Album</Button>
              </Tooltip>
            )}
          </>
        )}
        {mediaTab === 'Albums' && (
          <Button type="primary" icon={<FolderAddOutlined />} onClick={() => setCreateAlbumOpen(true)}>
            New Album
          </Button>
        )}

        <Tooltip title={viewMode === 'grid' ? 'Switch to Compact' : 'Switch to Grid'}>
          <Button
            icon={viewMode === 'grid' ? <AppstoreOutlined /> : <BarsOutlined />}
            onClick={() => setViewMode(viewMode === 'grid' ? 'compact' : 'grid')}
          />
        </Tooltip>

        {/* Select All (Videos + Photos) */}
        {mediaTab === 'Videos' && (
          <Button size="small" type="text" onClick={handleVideoSelectAll}>
            {selectedVideoIds.length === videos.length && videos.length > 0 ? 'Deselect' : 'Select All'}
          </Button>
        )}
        {mediaTab === 'Photos' && (
          <Button size="small" type="text" onClick={handlePhotoSelectAll}>
            {selectedPhotoIds.length === photos.length && photos.length > 0 ? 'Deselect' : 'Select All'}
          </Button>
        )}
      </div>
      )}

      {/* Stats (hidden for Documents) */}
      {mediaTab !== 'Documents' && (
      <div style={{ marginBottom: 8, color: '#999', fontSize: 13 }}>
        {activePagination.total} {mediaTab.toLowerCase().replace(/s$/, '')}{activePagination.total !== 1 ? 's' : ''}
        {mediaTab === 'Videos' && selectedVideoIds.length > 0 && ` · ${selectedVideoIds.length} selected`}
        {mediaTab === 'Photos' && selectedPhotoIds.length > 0 && ` · ${selectedPhotoIds.length} selected`}
      </div>
      )}

      {/* Content Grid (hidden for Documents) */}
      {mediaTab !== 'Documents' && (
      loading ? (
        <div style={{ textAlign: 'center', padding: 48 }}>
          <Spin size="large" />
        </div>
      ) : (
        <>
          {/* === Videos Tab === */}
          {mediaTab === 'Videos' && (
            videos.length === 0 ? (
              <Empty description="No videos found" />
            ) : (
              <Row gutter={[16, 16]}>
                {videos.map((video) => (
                  <Col {...colSpan} key={video.id}>
                    <VideoCard
                      video={video}
                      selected={selectedVideoIds.includes(video.id)}
                      onSelect={handleVideoSelect}
                      onClick={(v) => setViewerVideo(v)}
                      onEdit={(v) => setEditVideo(v)}
                      onPreview={(v) => setViewerVideo(v)}
                      onAnalytics={(v) => { setAnalyticsVideoId(v.id); setAnalyticsVideoTitle(v.title || v.filename); }}
                      onSchedule={(v) => setScheduleVideo(v)}
                      onDelete={handleDeleteSingleVideo}
                      onAddToPlaylist={(v) => setPlaylistVideoId(v.id)}
                      onRefresh={fetchVideos}
                      onTogglePublish={handleToggleVideoPublish}
                    />
                  </Col>
                ))}
              </Row>
            )
          )}

          {/* === Photos Tab === */}
          {mediaTab === 'Photos' && (
            photos.length === 0 ? (
              <Empty description="No photos found" />
            ) : (
              <Row gutter={[16, 16]}>
                {photos.map((photo) => (
                  <Col {...colSpan} key={photo.id}>
                    <PhotoCard
                      photo={photo}
                      selected={selectedPhotoIds.includes(photo.id)}
                      onSelect={handlePhotoSelect}
                      onClick={(p) => setViewerPhoto(p)}
                      onEdit={(p) => setEditPhoto(p)}
                      onPreview={(p) => setViewerPhoto(p)}
                      onDelete={handleDeleteSinglePhoto}
                      onTogglePublish={handleTogglePhotoPublish}
                    />
                  </Col>
                ))}
              </Row>
            )
          )}

          {/* === Albums Tab === */}
          {mediaTab === 'Albums' && (
            albums.length === 0 ? (
              <Empty description="No albums found" />
            ) : (
              <Row gutter={[16, 16]}>
                {albums.map((album) => (
                  <Col {...colSpan} key={album.id}>
                    <AlbumCard
                      album={album}
                      onClick={(a) => setSelectedAlbumId(a.id)}
                    />
                  </Col>
                ))}
              </Row>
            )
          )}

          {/* Pagination */}
          {activePagination.total > activePagination.limit && (
            <Pagination
              current={activePagination.page}
              pageSize={activePagination.limit}
              total={activePagination.total}
              onChange={(page) => {
                if (mediaTab === 'Videos') setVideoPagination((prev) => ({ ...prev, page }));
                else if (mediaTab === 'Photos') setPhotoPagination((prev) => ({ ...prev, page }));
                else setAlbumPagination((prev) => ({ ...prev, page }));
              }}
              style={{ marginTop: 24, textAlign: 'center' }}
              showSizeChanger
              onShowSizeChange={(_, size) => {
                if (mediaTab === 'Videos') setVideoPagination((prev) => ({ ...prev, limit: size, page: 1 }));
                else if (mediaTab === 'Photos') setPhotoPagination((prev) => ({ ...prev, limit: size, page: 1 }));
                else setAlbumPagination((prev) => ({ ...prev, limit: size, page: 1 }));
              }}
              pageSizeOptions={[24, 48, 96, 144]}
            />
          )}
        </>
      )
      )}

      {/* === Video Bulk Actions === */}
      {mediaTab === 'Videos' && (
        <BulkActionsBar
          selectedCount={selectedVideoIds.length}
          actions={[
            { key: 'publish', label: 'Publish', icon: <GlobalOutlined />, onClick: () => setPublishModalOpen(true), type: 'primary' },
            { key: 'access-level', label: 'Access Level', icon: <LockOutlined />, onClick: () => setBulkAccessLevelOpen(true) },
            { key: 'add-to-playlist', label: 'Add to Playlist', icon: <OrderedListOutlined />, onClick: () => setBulkPlaylistOpen(true) },
            { key: 'delete', label: 'Delete', icon: <DeleteOutlined />, onClick: () => setDeleteModalOpen(true), danger: true },
          ]}
        />
      )}

      {/* === Photo Bulk Actions === */}
      {mediaTab === 'Photos' && selectedPhotoIds.length > 0 && (
        <BulkActionsBar
          selectedCount={selectedPhotoIds.length}
          actions={[
            { key: 'publish', label: 'Publish', icon: <GlobalOutlined />, onClick: handleBulkPhotoPublish, type: 'primary' },
            { key: 'create-album', label: 'Create Album', icon: <FolderAddOutlined />, onClick: () => setCreateAlbumOpen(true) },
            { key: 'delete', label: 'Delete', icon: <DeleteOutlined />, onClick: handleBulkPhotoDelete, danger: true },
          ]}
        />
      )}

      {/* === Video Modals === */}
      <UploadVideoDrawer
        open={uploadVideoOpen}
        onClose={() => setUploadVideoOpen(false)}
        onSuccess={() => { setUploadVideoOpen(false); fetchVideos(); fetchProducers(); }}
      />

      <PublishModal
        open={publishModalOpen}
        videoIds={selectedVideoIds}
        onSuccess={() => { setPublishModalOpen(false); setSelectedVideoIds([]); fetchVideos(); }}
        onCancel={() => setPublishModalOpen(false)}
      />

      <DeleteConfirmModal
        open={deleteModalOpen}
        count={selectedVideoIds.length}
        onConfirm={handleVideoDelete}
        onCancel={() => setDeleteModalOpen(false)}
        loading={deleting}
      />

      <VideoViewerModal
        video={viewerVideo}
        open={!!viewerVideo}
        onClose={() => setViewerVideo(null)}
      />

      {analyticsVideoId && (
        <QuickAnalyticsModal
          videoId={analyticsVideoId}
          videoTitle={analyticsVideoTitle}
          open={!!analyticsVideoId}
          onClose={() => setAnalyticsVideoId(null)}
        />
      )}

      <SchedulePublishModal
        video={scheduleVideo}
        open={!!scheduleVideo}
        onClose={() => setScheduleVideo(null)}
        onSuccess={() => { setScheduleVideo(null); fetchVideos(); }}
      />

      <ScheduleCalendarDrawer
        open={calendarModalOpen}
        onClose={() => setCalendarModalOpen(false)}
        onRefresh={fetchVideos}
      />

      <EditVideoModal
        video={editVideo}
        open={!!editVideo}
        onClose={() => setEditVideo(null)}
        onSuccess={() => { setEditVideo(null); fetchVideos(); fetchProducers(); }}
      />

      <FetchVideosDrawer
        open={fetchDrawerOpen}
        onClose={() => setFetchDrawerOpen(false)}
        onSuccess={() => { fetchVideos(); fetchProducers(); }}
      />

      {playlistVideoId && (
        <AddToPlaylistModal
          videoId={playlistVideoId}
          open={!!playlistVideoId}
          onClose={() => setPlaylistVideoId(null)}
        />
      )}

      <BulkAccessLevelModal
        open={bulkAccessLevelOpen}
        videoIds={selectedVideoIds}
        onClose={() => setBulkAccessLevelOpen(false)}
        onSuccess={() => { setBulkAccessLevelOpen(false); setSelectedVideoIds([]); fetchVideos(); }}
      />

      <BulkAddToPlaylistModal
        videoIds={selectedVideoIds}
        open={bulkPlaylistOpen}
        onClose={() => setBulkPlaylistOpen(false)}
        onSuccess={() => { setBulkPlaylistOpen(false); setSelectedVideoIds([]); }}
      />

      {/* === Photo Modals === */}
      <UploadPhotoDrawer
        open={uploadPhotoOpen}
        onClose={() => setUploadPhotoOpen(false)}
        onSuccess={() => { setUploadPhotoOpen(false); fetchPhotos(); fetchPhotoFormats(); }}
      />

      <PhotoViewerModal
        photo={viewerPhoto}
        open={!!viewerPhoto}
        onClose={() => setViewerPhoto(null)}
      />

      <EditPhotoModal
        photo={editPhoto}
        open={!!editPhoto}
        onClose={() => setEditPhoto(null)}
        onSuccess={() => { setEditPhoto(null); fetchPhotos(); }}
      />

      <CreateAlbumModal
        open={createAlbumOpen}
        onClose={() => setCreateAlbumOpen(false)}
        onSuccess={() => {
          setCreateAlbumOpen(false);
          setSelectedPhotoIds([]);
          fetchPhotos();
          fetchAlbums();
        }}
        selectedPhotoIds={selectedPhotoIds}
      />

      <AlbumDetailDrawer
        albumId={selectedAlbumId}
        open={!!selectedAlbumId}
        onClose={() => setSelectedAlbumId(null)}
        onRefresh={fetchAlbums}
      />
      <PageTour sectionId="media-library" />
    </div>
  );
}
