'use client';

import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import ShareAccessLog from './share-access-log.jsx';
import ShareLinkList from './share-link-list.jsx';
import ShareScopeSelector from './share-scope-selector.jsx';
import ProjectShareControls from './project-share-controls.jsx';
import { useProjectAlbum } from './project-album-context.jsx';

export default function SharePanel({ item, onClose }) {
  const [acl, setAcl] = useState(null);
  const [links, setLinks] = useState([]);
  const [auditRows, setAuditRows] = useState([]);
  const [scope, setScope] = useState('private');
  const [expiryDays, setExpiryDays] = useState(7);
  const [loading, setLoading] = useState(false);
  const [linkLoading, setLinkLoading] = useState(false);
  const [error, setError] = useState('');
  const [saveStatus, setSaveStatus] = useState('');
  const { shareData } = useProjectAlbum();
  const artifactId = item?.source_type === 'artifact' ? item?.id : null;
  const projectId = item?.source_type === 'project' ? item?.id : null;

  const loadData = useCallback(async ({ force = false } = {}) => {
    if (!artifactId) return;
    setLoading(true);
    setError('');
    try {
      const data = await shareData.readArtifactShareData(artifactId, { force });
      setAcl(data?.acl || null);
      setScope(data?.acl?.scope || 'private');
      setLinks(Array.isArray(data?.links) ? data.links : []);
      setAuditRows(Array.isArray(data?.auditRows) ? data.auditRows : []);
    } catch {
      setError('Failed to load sharing settings.');
    } finally {
      setLoading(false);
    }
  }, [artifactId, shareData]);

  useEffect(() => { if (item) loadData(); }, [item, loadData]);
  useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose?.(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  async function handleSaveScope() {
    if (!artifactId) return;
    setSaveStatus('saving');
    setError('');
    try {
      const res = await fetch(`/api/artifacts/${artifactId}/acl`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ scope }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        setError(d.error || 'Failed to save.');
        setSaveStatus('');
        return;
      }
      setSaveStatus('saved');
      setTimeout(() => setSaveStatus(''), 2000);
      shareData.invalidateArtifactShareData(artifactId);
      await loadData({ force: true });
    } catch {
      setError('Network error.');
      setSaveStatus('');
    }
  }

  async function handleCreateLink() {
    if (!artifactId) return;
    setLinkLoading(true);
    setError('');
    try {
      const res = await fetch(`/api/artifacts/${artifactId}/share-link`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ expires_in_days: expiryDays }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        setError(d.error || 'Failed to create link.');
        return;
      }
      shareData.invalidateArtifactShareData(artifactId);
      await loadData({ force: true });
    } catch {
      setError('Network error.');
    } finally {
      setLinkLoading(false);
    }
  }

  async function handleRevokeLink(linkId) {
    if (!artifactId) return;
    try {
      const res = await fetch(`/api/artifacts/${artifactId}/share-link/${linkId}`, { method: 'DELETE' });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        setError(d.error || 'Failed to revoke link.');
        return;
      }
      shareData.invalidateArtifactShareData(artifactId);
      await loadData({ force: true });
    } catch {
      setError('Network error.');
    }
  }

  if (!item || typeof document === 'undefined') return null;
  const activeLinks = links.filter((l) => !l.revoked);
  const showLinks = scope === 'link' || activeLinks.length > 0;
  const kindLabel = projectId ? 'Project' : 'Artifact';

  return createPortal(
    <div role="dialog" aria-modal="true" aria-label={`Share ${kindLabel.toLowerCase()}`} className="share-panel-root">
      <div onClick={onClose} className="share-panel-backdrop" aria-hidden="true" />
      <div className="share-panel-shell">
        <header className="share-panel-header">
          <div>
            <p>Share {kindLabel}</p>
            <h2>{item.title || item.name || kindLabel}</h2>
          </div>
          <button type="button" onClick={onClose} aria-label="Close share panel" className="share-panel-close">×</button>
        </header>
        <div className="share-panel-body">
          {projectId ? (
            <ProjectShareControls projectId={projectId} projectName={item.name || item.title} />
          ) : (
            <>
              {loading ? <p className="share-panel-muted">Loading...</p> : null}
              {error ? <div className="share-panel-error">{error}</div> : null}
              {!loading && artifactId ? (
                <>
                  <ShareScopeSelector scope={scope} aclScope={acl?.scope} saveStatus={saveStatus} onScopeChange={setScope} onSave={handleSaveScope} />
                  {showLinks ? <ShareLinkList links={links} expiryDays={expiryDays} setExpiryDays={setExpiryDays} linkLoading={linkLoading} onCreateLink={handleCreateLink} onRevokeLink={handleRevokeLink} /> : null}
                  <ShareAccessLog rows={auditRows} />
                </>
              ) : null}
              {!artifactId && !loading ? <p className="share-panel-empty">Share controls are available for artifacts. Select an artifact from the album to manage its sharing settings.</p> : null}
            </>
          )}
        </div>
      </div>
    </div>,
    document.body,
  );
}
