'use client';

import dynamic from 'next/dynamic';
import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import AlbumBreadcrumb from './album-breadcrumb.jsx';
import AlbumCard from './album-card.jsx';
import AlbumFolderGrid from './album-folder-grid.jsx';
import AlbumToolbar from './album-toolbar.jsx';
import MigrationBanner from './migration-banner.jsx';
import { itemKey } from './album-utils.js';
import { useProjectAlbum } from './project-album-context.jsx';
import { useAlbumState } from './use-album-state.js';

const FloatingArtifactWindow = dynamic(() => import('./floating-artifact-window.jsx'));
const MarkdownThumbnail = dynamic(() => import('./album-thumbnails/markdown.jsx'), {
  loading: () => <div className="project-album-thumb-tile" data-kind="markdown"><span>MD</span></div>,
});
const SharePanel = dynamic(() => import('./share-panel.jsx'));
void SharePanel;

export default function ProjectAlbum({ items, folders = [], projectId, projectSlug, rootFolderId = null, currentFolderId = null }) {
  const router = useRouter();
  const [deletingKey, setDeletingKey] = useState(null);
  const [movingKey, setMovingKey] = useState(null);
  const [dragOverFolderId, setDragOverFolderId] = useState(null);
  const [protectError, setProtectError] = useState(null);
  const [migrationBanner, setMigrationBanner] = useState(false);
  const [keyHintKey, setKeyHintKey] = useState(null);
  const [spaces, setSpaces] = useState([]);
  const [bookmarkingKey, setBookmarkingKey] = useState(null);
  const { privacy, openSetupModal, openUnlockModal, applyItemPatch, removeItem, items: liveItems, folders: liveFolders } = useProjectAlbum();
  void projectId;

  const albumItems = liveItems || items;
  const albumFolders = liveFolders || folders;
  const { configured, unlocked } = privacy;
  const album = useAlbumState({ items: albumItems, folders: albumFolders, currentFolderId, rootFolderId, unlocked });

  useEffect(() => {
    try {
      const hadBlur = window.localStorage.getItem('madarx-album-privacy-blur') === '1';
      if (!hadBlur) return;
      if (configured) window.localStorage.removeItem('madarx-album-privacy-blur');
      else setMigrationBanner(true);
    } catch {}
  }, [configured]);

  useEffect(() => {
    let cancelled = false;
    fetch('/api/dashboard/spaces')
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (cancelled || !data) return;
        if (Array.isArray(data.spaces)) setSpaces(data.spaces);
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  const bookmarkToSpace = useCallback(async (item, targetSpaceId) => {
    if (!item || item.source_type !== 'artifact' || !targetSpaceId) return;
    const key = itemKey(item);
    setBookmarkingKey(key);
    try {
      const res = await fetch(`/api/dashboard/spaces/${encodeURIComponent(targetSpaceId)}/move`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ artifact_id: item.id }),
      });
      if (!res.ok) throw new Error(await res.text().catch(() => '') || `bookmark failed (${res.status})`);
      applyItemPatch({ ...item, space_id: targetSpaceId });
    } catch (err) {
      console.error('[project-album] bookmark to space failed', err);
      window.alert(`Could not pin this artifact to the space.\n${err?.message || err}`);
    } finally {
      setBookmarkingKey(null);
    }
  }, [applyItemPatch]);

  const dismissMigration = useCallback(() => {
    try { window.localStorage.removeItem('madarx-album-privacy-blur'); } catch {}
    setMigrationBanner(false);
  }, []);

  const deleteItem = useCallback(async (item) => {
    if (!item || deletingKey) return;
    const key = itemKey(item);
    setDeletingKey(key);
    try {
      const url = item.source_type === 'artifact'
        ? `/api/artifacts/${encodeURIComponent(item.id)}`
        : `/api/disk/files/${encodeURIComponent(item.id)}`;
      const res = await fetch(url, { method: 'DELETE' });
      if (!res.ok) throw new Error(await res.text().catch(() => '') || `delete failed (${res.status})`);
      album.setSelectedKey(null);
      removeItem(item);
    } catch (err) {
      console.error('[project-album] delete failed', err);
      window.alert('Could not delete this item. See console for details.');
    } finally {
      setDeletingKey(null);
    }
  }, [album, deletingKey, removeItem]);

  const toggleProtect = useCallback(async (item, currentlyProtected) => {
    setProtectError(null);
    try {
      const res = await fetch(`/api/artifacts/${item.id}/protect`, {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ is_protected: !currentlyProtected }),
      });
      const data = await res.json();
      if (data.need_passphrase_setup) {
        album.setSelectedKey(null);
        openSetupModal();
        return;
      }
      if (!res.ok) {
        setProtectError(data.error || `protect failed (${res.status})`);
        return;
      }
      applyItemPatch({ ...item, is_protected: data.is_protected });
    } catch (err) {
      setProtectError(err?.message || 'Protect toggle failed.');
    }
  }, [album, applyItemPatch, openSetupModal]);

  const navigateToFolder = useCallback((folderId) => {
    const url = folderId && folderId !== rootFolderId
      ? `/projects/${projectSlug}?folder=${encodeURIComponent(folderId)}`
      : `/projects/${projectSlug}`;
    router.push(url);
  }, [projectSlug, rootFolderId, router]);

  const moveItem = useCallback(async (item, targetFolderId) => {
    if (!item) return;
    const url = item.source_type === 'artifact'
      ? `/api/artifacts/${encodeURIComponent(item.id)}`
      : `/api/disk/files/${encodeURIComponent(item.id)}`;
    setMovingKey(itemKey(item));
    try {
      const res = await fetch(url, {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ folder_id: targetFolderId || null }),
      });
      if (!res.ok) throw new Error(await res.text().catch(() => '') || `move failed (${res.status})`);
      const data = await res.json().catch(() => ({}));
      applyItemPatch(data.artifact || data.file || { ...item, folder_id: targetFolderId || null });
    } catch (err) {
      console.error('[project-album] move failed', err);
      window.alert(`Could not move this item.\n${err?.message || err}`);
    } finally {
      setMovingKey(null);
    }
  }, [applyItemPatch]);

  const openItem = (it) => {
    const isLocked = it.is_protected && !unlocked && !album.titleMatchesQuery(it);
    if (!isLocked) album.setSelectedKey(itemKey(it));
  };

  const doubleClickItem = (it) => {
    const isLocked = it.is_protected && !unlocked && !album.titleMatchesQuery(it);
    if (isLocked) openUnlockModal();
    else album.setSelectedKey(itemKey(it));
  };

  return (
    <div className="project-album">
      <AlbumToolbar query={album.query} setQuery={album.setQuery} filters={album.FILTERS} filterId={album.filterId} setFilterId={album.setFilterId} itemsInFolder={album.itemsInFolder} />
      {migrationBanner ? <MigrationBanner onSetup={() => { setMigrationBanner(false); openSetupModal(); }} onDismiss={dismissMigration} /> : null}
      <AlbumBreadcrumb breadcrumb={album.breadcrumb} dragOverFolderId={dragOverFolderId} setDragOverFolderId={setDragOverFolderId} navigateToFolder={navigateToFolder} albumItems={albumItems} moveItem={moveItem} rootFolderId={rootFolderId} />
      <AlbumFolderGrid subFolders={album.subFolders} dragOverFolderId={dragOverFolderId} setDragOverFolderId={setDragOverFolderId} navigateToFolder={navigateToFolder} albumItems={albumItems} moveItem={moveItem} />

      {album.visible.length ? (
        <div className="project-album-grid">
          {album.visible.map((it) => {
            const isLocked = it.is_protected && !unlocked && !album.titleMatchesQuery(it);
            const highlighted = it.is_protected && !isLocked && Boolean(album.queryLower);
            const key = itemKey(it);
            return (
              <AlbumCard
                key={key}
                item={it}
                onOpen={() => openItem(it)}
                onDoubleOpen={() => doubleClickItem(it)}
                onOpenUnlock={openUnlockModal}
                blurred={isLocked}
                highlighted={highlighted}
                protectedFlag={Boolean(it.is_protected)}
                keyHintVisible={keyHintKey === key}
                onShowKeyHint={() => setKeyHintKey(key)}
                onHideKeyHint={() => setKeyHintKey(null)}
                draggable
                onDragStart={(e) => {
                  e.dataTransfer.effectAllowed = 'move';
                  e.dataTransfer.setData('text/madarx-item-key', key);
                }}
                moving={movingKey === key}
                MarkdownThumbnail={MarkdownThumbnail}
              />
            );
          })}
        </div>
      ) : (
        <div className="project-album-empty">
          {album.query ? <><b>No matches for &ldquo;{album.query}&rdquo;.</b><small>Try a different keyword, or clear the search.</small></>
            : album.isRoot ? <><b>Nothing here yet.</b><small>Upload a document, create an artifact, or add a folder.</small></>
              : <><b>This folder is empty.</b><small>Drag an item here, or upload directly to this folder.</small></>}
        </div>
      )}

      <FloatingArtifactWindow
        item={album.selected}
        onClose={() => { album.setSelectedKey(null); setProtectError(null); }}
        isProtected={album.selected ? Boolean(album.selected.is_protected) : false}
        onToggleProtect={() => album.selected && toggleProtect(album.selected, Boolean(album.selected.is_protected))}
        protectError={protectError}
        onDelete={() => album.selected && deleteItem(album.selected)}
        deleting={album.selected ? deletingKey === itemKey(album.selected) : false}
        folders={albumFolders}
        rootFolderId={rootFolderId}
        onMove={(folderId) => album.selected && moveItem(album.selected, folderId)}
        moving={album.selected ? movingKey === itemKey(album.selected) : false}
        spaces={spaces}
        onBookmarkToSpace={(spaceId) => album.selected && bookmarkToSpace(album.selected, spaceId)}
        bookmarking={album.selected ? bookmarkingKey === itemKey(album.selected) : false}
      />
    </div>
  );
}
