'use client';

import api from '@/lib/api-client';
import { useEffect, useState } from 'react';

export function ReportEvidence({ entry }: { entry: { url: string; type: string } }) {
  const [state, setState] = useState({ source: '', url: '', failed: false });

  useEffect(() => {
    const controller = new AbortController();
    let objectUrl = '';
    const path = entry.url.replace('/api/backend/integration/field-reports/', '/admin/field-reports/');
    api.get(path, { responseType: 'blob', timeout: 60000, signal: controller.signal }).then(response => {
      if (controller.signal.aborted) return;
      objectUrl = URL.createObjectURL(response.data);
      setState({ source: entry.url, url: objectUrl, failed: false });
    }).catch(() => {
      if (!controller.signal.aborted) setState({ source: entry.url, url: '', failed: true });
    });
    return () => {
      controller.abort();
      if (objectUrl) URL.revokeObjectURL(objectUrl);
    };
  }, [entry.url]);

  if (state.source !== entry.url) return <p className="text-sm text-slate-500">Loading evidence...</p>;
  if (state.failed) return <p role="alert" className="text-sm text-rose-700">Evidence could not be loaded.</p>;
  if (entry.type === 'audio') return <audio src={state.url} controls className="w-full" />;
  if (entry.type === 'video') return <video src={state.url} controls className="max-h-96 w-full" />;
  return <img src={state.url} alt="Report evidence" className="max-h-96 w-full object-contain" />;
}
