import React, { useEffect, useRef, useState } from 'react';

// The ticket proof stays in the POST body; object URLs are scoped to this component.
export default function PrivateAttachment({ item, messageID, endpoint, appState, txt }) {
  const [url, setUrl] = useState('');
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const active = useRef(null);
  const objectURL = useRef('');
  const { ticket_id, pin, rep } = appState;
  const contact_id = appState.contact_id || appState.contact?.id;

  useEffect(() => {
    setUrl('');
    setError(false);
    setLoading(false);
    return () => {
    if (active.current) active.current.abort();
    if (objectURL.current) URL.revokeObjectURL(objectURL.current);
    active.current = null;
    objectURL.current = '';
    };
  }, [ticket_id, contact_id, pin, rep, messageID, item.private_index, endpoint]);

  async function load() {
    if (loading) return;
    const controller = new AbortController();
    active.current = controller;
    setLoading(true);
    setError(false);
    const body = new FormData();
    Object.entries({ ticket_id, contact_id, pin: pin || '', rep: rep || '', message_id: messageID, index: item.private_index }).forEach(([key, value]) => body.append(key, value));
    try {
      const response = await fetch(endpoint, { method: 'POST', body, signal: controller.signal });
      if (!response.ok) throw new Error('Attachment unavailable');
      const blob = await response.blob();
      if (controller.signal.aborted) return;
      if (objectURL.current) URL.revokeObjectURL(objectURL.current);
      objectURL.current = URL.createObjectURL(blob);
      setUrl(objectURL.current);
    } catch (err) {
      if (!controller.signal.aborted) setError(true);
    } finally {
      if (!controller.signal.aborted) setLoading(false);
    }
  }

  return <div>
    {!url && <button type="button" className="ui tiny button" onClick={load} disabled={loading}>{loading ? txt('Loading attachment') : txt('Open attachment')}: {item.file_name}</button>}
    {error && <span role="status">{txt('Attachment could not be loaded.')}</span>}
    {url && item.kind === 'picture' && <img src={url} alt="" style={{maxWidth:'100%', maxHeight:'320px'}} />}
    {url && item.kind === 'video' && <video src={url} controls style={{maxWidth:'100%', maxHeight:'320px'}} aria-label={item.file_name} />}
    {url && item.kind === 'audio' && <audio src={url} controls aria-label={item.file_name} />}
    {url && <div><a className="ui tiny button" href={url} download={item.file_name}>{txt('Download')}: {item.file_name}</a></div>}
  </div>;
}
