'use client';

import Link from 'next/link';
import dynamic from 'next/dynamic';
import { useCallback, useState } from 'react';
import AdminModal from '../../components/admin/admin-modal.jsx';
import { useProjectAlbum } from './project-album-context.jsx';

const PrivacyPassphraseModal = dynamic(() => import('./privacy-passphrase-modal.jsx').then((mod) => mod.PrivacyPassphraseModal));
const PrivacyUnlockModal = dynamic(() => import('./privacy-unlock-modal.jsx').then((mod) => mod.PrivacyUnlockModal));
const SharePanel = dynamic(() => import('./share-panel.jsx'));

/**
 * Project detail header actions. Three buttons, top-right:
 *   1. Activity (icon-only link to the log)
 *   2. Lock chip (privacy state — no-passphrase / locked / unlocked)
 *   3. New folder (opens modal that creates a real OS folder on disk)
 *
 * Modal state is routed through ProjectAlbumProvider so album cards and header
 * actions share the same privacy session without window event coupling.
 */
export default function ProjectHeaderActions({ projectId, projectName = '', slug, lockedCount = 0, currentFolderId = null, rootFolderId = null }) {
  const {
    privacy,
    setupModalOpen,
    unlockModalOpen,
    openSetupModal,
    closeSetupModal,
    openUnlockModal,
    closeUnlockModal,
    refreshLibrary,
  } = useProjectAlbum();
  const { configured, unlocked, lock } = privacy;

  // Project-level share panel
  const [shareOpen, setShareOpen] = useState(false);

  // Folder creation state
  const [folderModalOpen, setFolderModalOpen] = useState(false);
  const [folderName, setFolderName] = useState('');
  const [folderError, setFolderError] = useState(null);
  const [creatingFolder, setCreatingFolder] = useState(false);


  const openFolderModal = useCallback(() => {
    setFolderName('');
    setFolderError(null);
    setFolderModalOpen(true);
  }, []);

  const closeFolderModal = useCallback(() => {
    if (creatingFolder) return;
    setFolderModalOpen(false);
  }, [creatingFolder]);

  const submitFolder = useCallback(async (event) => {
    if (event) event.preventDefault();
    if (creatingFolder) return;
    const name = String(folderName || '').trim();
    if (!name) { setFolderError('Name is required.'); return; }
    if (/[\\/]/.test(name)) { setFolderError('Name cannot contain slashes.'); return; }
    setCreatingFolder(true);
    setFolderError(null);
    try {
      const parentId = currentFolderId && currentFolderId !== rootFolderId ? currentFolderId : null;
      const res = await fetch('/api/disk/folders', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ project_id: projectId, name, parent_id: parentId }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data?.error || `create failed (${res.status})`);
      setFolderModalOpen(false);
      setFolderName('');
      await refreshLibrary();
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error('[project-header] create folder failed', err);
      setFolderError(err?.message || String(err));
    } finally {
      setCreatingFolder(false);
    }
  }, [creatingFolder, folderName, projectId, currentFolderId, rootFolderId, refreshLibrary]);

  const lockChip = (() => {
    if (!configured) {
      return (
        <button
          type="button"
          className="project-album-lock-chip no-passphrase"
          onClick={openSetupModal}
          aria-label="Set up passphrase protection"
          title="Protect individual artifacts with a passphrase"
        >
          <LockIcon />
        </button>
      );
    }
    if (unlocked) {
      return (
        <button
          type="button"
          className="project-album-lock-chip unlocked"
          onClick={lock}
          aria-label="Lock protected artifacts"
          title="Click to lock"
        >
          <UnlockIcon />
        </button>
      );
    }
    return (
      <button
        type="button"
        className="project-album-lock-chip locked"
        onClick={openUnlockModal}
        aria-label={`Unlock ${lockedCount} protected artifacts`}
        title="Click to unlock"
      >
        <LockIcon />
        {lockedCount > 0 ? <span className="project-album-lock-chip-count">{lockedCount}</span> : null}
      </button>
    );
  })();

  return (
    <>
      <Link className="project-activity-link icon-only" href={`/projects/${slug}/log`} aria-label="Open project activity" title="Activity">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <circle cx="8" cy="8" r="6" />
          <path d="M8 5v3.5l2.2 1.3" />
        </svg>
      </Link>

      {lockChip}

      <button
        type="button"
        className="project-album-folder-new"
        onClick={() => setShareOpen(true)}
        aria-label="Share this project"
        title="Share this project with your organization"
      >
        <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <circle cx="12" cy="3.5" r="2" />
          <circle cx="4" cy="8" r="2" />
          <circle cx="12" cy="12.5" r="2" />
          <path d="M5.7 7 10.3 4.5M5.7 9l4.6 2.5" />
        </svg>
        Share
      </button>

      <button
        type="button"
        className="project-album-folder-new"
        onClick={openFolderModal}
        aria-label="Create new folder"
        title="Create a new folder on disk"
      >
        <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M2 5a1 1 0 0 1 1-1h3.5l1.5 1.5H13a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V5Z" />
          <path d="M8 8v4M6 10h4" />
        </svg>
        New folder
      </button>

      <AdminModal
        open={folderModalOpen}
        onClose={closeFolderModal}
        eyebrow="Library"
        title="New folder"
      >
        <form className="agents-modal-form" onSubmit={submitFolder}>
          <p className="agents-modal-help">
            Creates a real folder on disk under this project. Use it to organize uploaded documents and artifacts.
          </p>

          <section className="agents-modal-section">
            <label className="agents-modal-field wide">
              <span>Folder name</span>
              <input
                type="text"
                value={folderName}
                onChange={(event) => { setFolderName(event.target.value); if (folderError) setFolderError(null); }}
                placeholder="e.g. Research, Drafts, 2026-Q2"
                autoComplete="off"
                spellCheck={false}
                autoFocus
                maxLength={120}
                disabled={creatingFolder}
              />
            </label>
            {folderError ? (
              <p className="agents-modal-feedback error" role="alert" aria-live="polite">{folderError}</p>
            ) : (
              <small className="project-album-folder-hint">Letters, numbers, spaces, dashes. No slashes.</small>
            )}
          </section>

          <footer className="agents-modal-foot">
            <button
              type="button"
              className="admin-button secondary"
              onClick={closeFolderModal}
              disabled={creatingFolder}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="admin-button"
              disabled={creatingFolder || !folderName.trim()}
            >
              {creatingFolder ? 'Creating…' : 'Create folder'}
            </button>
          </footer>
        </form>
      </AdminModal>

      <PrivacyPassphraseModal
        open={setupModalOpen}
        onClose={closeSetupModal}
        projectId={projectId}
        privacy={privacy}
      />
      <PrivacyUnlockModal
        open={unlockModalOpen}
        onClose={closeUnlockModal}
        projectId={projectId}
        privacy={privacy}
      />

      {shareOpen ? (
        <SharePanel
          item={{ source_type: 'project', id: projectId, name: projectName }}
          onClose={() => setShareOpen(false)}
        />
      ) : null}
    </>
  );
}

function LockIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="3" y="7" width="10" height="7" rx="1.5" />
      <path d="M5 7V5a3 3 0 0 1 6 0v2" />
    </svg>
  );
}

function UnlockIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="3" y="7" width="10" height="7" rx="1.5" />
      <path d="M5 7V5a3 3 0 0 1 6 0v0" />
    </svg>
  );
}
