'use client';

import { useEffect, useState, useCallback } from 'react';
import ReportsView from '@/components/ReportsView';
import { listExecutions } from '@/lib/pipeline-api';
import type { ExecutionStatus } from '@/lib/pipeline-types';
import type { JobStatus } from '@/components/ScraperTest';

export default function ReportsPage() {
  const [executions, setExecutions] = useState<ExecutionStatus[]>([]);
  const [jobsMap, setJobsMap] = useState<Map<string, JobStatus>>(new Map());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      // Fetch executions and jobs in parallel
      const [executionsData, jobsResponse] = await Promise.all([
        listExecutions('reviewiq', { limit: 100 }),
        fetch('/api/jobs?limit=100').then(r => r.json())
      ]);

      setExecutions(executionsData);

      // Create a map of job_id -> job for quick lookup
      const map = new Map<string, JobStatus>();
      const jobsList = jobsResponse?.jobs || jobsResponse;
      if (Array.isArray(jobsList)) {
        jobsList.forEach((job: JobStatus) => {
          map.set(job.job_id, job);
        });
      }
      setJobsMap(map);
    } catch (err) {
      console.error('Failed to fetch data:', err);
      setError(err instanceof Error ? err.message : 'Failed to load reports');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  if (loading) {
    return (
      <div className="h-full overflow-y-auto p-6">
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-gray-900">Reports</h1>
          <p className="text-gray-500 mt-1">AI-generated business intelligence reports from ReviewIQ pipeline</p>
        </div>
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="flex flex-col items-center gap-3">
            <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
            <span className="text-gray-500">Loading reports...</span>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="h-full overflow-y-auto p-6">
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-gray-900">Reports</h1>
          <p className="text-gray-500 mt-1">AI-generated business intelligence reports from ReviewIQ pipeline</p>
        </div>
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
          <div className="flex items-center gap-2">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span className="font-medium">Error loading reports</span>
          </div>
          <p className="mt-1 text-sm">{error}</p>
          <button
            onClick={fetchData}
            className="mt-3 px-4 py-2 bg-red-100 hover:bg-red-200 text-red-800 text-sm font-medium rounded-lg transition-colors"
          >
            Try again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full overflow-y-auto p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Reports</h1>
        <p className="text-gray-500 mt-1">AI-generated business intelligence reports from ReviewIQ pipeline</p>
      </div>
      <ReportsView executions={executions} jobsMap={jobsMap} onRefresh={fetchData} />
    </div>
  );
}
