'use client';

import { useEffect, useState } from 'react';
import { useParams, useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Loader2, FileText, BarChart3 } from 'lucide-react';
import { DynamicDashboard } from '@/components/dashboard/DynamicDashboard';
import { ReviewIQDashboard } from '@/components/reviewiq';
import { getDashboardConfig } from '@/lib/pipeline-api';
import type { DashboardConfig } from '@/lib/pipeline-types';

// Lazy load Report tab
import dynamic from 'next/dynamic';
const ReportTab = dynamic(() => import('@/components/reviewiq/ReportTab').then(m => m.ReportTab), {
  loading: () => <div className="flex items-center justify-center min-h-[400px]"><Loader2 className="w-8 h-8 animate-spin text-blue-600" /></div>
});

type ReviewIQTab = 'report' | 'dashboard';

export default function PipelineAnalyticsPage() {
  const params = useParams();
  const searchParams = useSearchParams();

  const pipelineId = params.pipelineId as string;
  const jobId = searchParams.get('job_id') || undefined;
  const businessId = searchParams.get('business_id') || undefined;

  const [config, setConfig] = useState<DashboardConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Use the handcrafted ReviewIQ dashboard for the reviewiq pipeline
  const useReviewIQDashboard = pipelineId === 'reviewiq';

  // Tab state for ReviewIQ
  const router = useRouter();
  const viewParam = searchParams.get('view') as ReviewIQTab | null;
  const [activeTab, setActiveTab] = useState<ReviewIQTab>(viewParam || 'report');

  // Update URL when tab changes
  const handleTabChange = (tab: ReviewIQTab) => {
    setActiveTab(tab);
    const params = new URLSearchParams(searchParams.toString());
    if (tab === 'report') {
      params.delete('view');
    } else {
      params.set('view', tab);
    }
    router.push(`/pipelines/${pipelineId}/analytics?${params.toString()}`, { scroll: false });
  };

  useEffect(() => {
    // Skip config fetch for ReviewIQ - it uses its own optimized endpoint
    if (useReviewIQDashboard) {
      setLoading(false);
      return;
    }

    async function fetchConfig() {
      try {
        setLoading(true);
        const dashboardConfig = await getDashboardConfig(pipelineId);
        setConfig(dashboardConfig);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load dashboard config');
      } finally {
        setLoading(false);
      }
    }

    fetchConfig();
  }, [pipelineId, useReviewIQDashboard]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  // Use handcrafted ReviewIQ Dashboard with tabs
  if (useReviewIQDashboard) {
    const tabs = [
      { id: 'report' as const, label: 'Report', icon: FileText },
      { id: 'dashboard' as const, label: 'Dashboard', icon: BarChart3 },
    ];

    return (
      <div className="h-full overflow-y-auto p-6">
        {/* Navigation breadcrumb */}
        <div className="mb-4">
          <Link
            href={`/pipelines/${pipelineId}`}
            className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="w-4 h-4 mr-1" />
            Back to ReviewIQ Pipeline
          </Link>
        </div>

        {/* Job context indicator */}
        {jobId && (
          <div className="mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-700">
            Showing results for job: <code className="bg-blue-100 px-1 rounded">{jobId}</code>
          </div>
        )}

        {/* Tab Navigation */}
        <div className="mb-6 border-b border-gray-200">
          <nav className="flex gap-2" aria-label="Tabs">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => handleTabChange(tab.id)}
                  className={`
                    relative px-4 py-2.5 flex items-center gap-2 text-sm font-medium transition-colors
                    ${isActive
                      ? 'text-blue-600'
                      : 'text-gray-500 hover:text-gray-700'
                    }
                  `}
                >
                  <Icon className={`w-4 h-4 ${isActive ? 'text-blue-600' : 'text-gray-400'}`} />
                  <span>{tab.label}</span>
                  {/* Active indicator bar */}
                  <span
                    className={`absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600 transition-opacity ${isActive ? 'opacity-100' : 'opacity-0'}`}
                  />
                </button>
              );
            })}
          </nav>
        </div>

        {/* Tab Content */}
        {activeTab === 'report' && (
          <ReportTab jobId={jobId} businessId={businessId} />
        )}
        {activeTab === 'dashboard' && (
          <ReviewIQDashboard jobId={jobId} businessId={businessId} />
        )}
      </div>
    );
  }

  // Fallback for other pipelines using dynamic dashboard
  if (error || !config) {
    return (
      <div className="p-6">
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
          {error || 'Failed to load dashboard configuration'}
        </div>
      </div>
    );
  }

  return (
    <div className="h-full overflow-y-auto p-6">
      {/* Navigation breadcrumb */}
      <div className="mb-4">
        <Link
          href={`/pipelines/${pipelineId}`}
          className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900"
        >
          <ArrowLeft className="w-4 h-4 mr-1" />
          Back to {pipelineId} Pipeline
        </Link>
      </div>

      {/* Job context indicator */}
      {jobId && (
        <div className="mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-700">
          Showing results for job: <code className="bg-blue-100 px-1 rounded">{jobId}</code>
        </div>
      )}

      {/* Dynamic Dashboard for other pipelines */}
      <DynamicDashboard
        pipelineId={pipelineId}
        config={config}
        businessId={businessId}
        jobId={jobId}
      />
    </div>
  );
}
