'use client';

import type { ReportSynthesis } from '../types';
import type { ReportLocale } from '../i18n/useReportLocale';
import { useReportLocale } from '../i18n/useReportLocale';
import ReportPage from '../components/ReportPage';
import SectionHeader from '../components/SectionHeader';
import QuarterlyRatingChart from '../charts/QuarterlyRatingChart';
import DomainSentimentTrend from '../charts/DomainSentimentTrend';
import SeasonalPatternChart from '../charts/SeasonalPatternChart';
import { paginateItems } from '../utils/paginate';

interface TrendsTimelineProps {
  report: ReportSynthesis;
  locale?: ReportLocale;
  startPage?: number;
  totalPages?: number;
  sectionNumber?: number;
}

interface ChartEntry {
  key: string;
  render: () => React.ReactNode;
}

export default function TrendsTimeline({
  report,
  locale = 'en',
  startPage = 6,
  totalPages = 9,
  sectionNumber = 5,
}: TrendsTimelineProps) {
  const { t } = useReportLocale(locale);
  const quarterlyRating = report.charts?.quarterly_rating ?? [];
  const domainSentiment = report.charts?.quarterly_domain_sentiment ?? [];
  const seasonal = report.charts?.seasonal_pattern ?? [];

  // Only render if we have meaningful data
  if (quarterlyRating.length < 2 && domainSentiment.length < 2) return null;

  // Build ordered list of available charts
  const charts: ChartEntry[] = [];

  if (quarterlyRating.length > 1) {
    charts.push({
      key: 'quarterly_rating',
      render: () => (
        <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: 20, marginBottom: 24 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)', marginBottom: 12 }}>
            {t('quarterly_rating_evolution')}
          </h3>
          <QuarterlyRatingChart data={quarterlyRating} />
          {report.rating_evolution_narrative && (
            <p className="body-sm" style={{ margin: '8px 0 0', lineHeight: 1.5, color: 'var(--text-secondary)', fontSize: 12 }}>
              {report.rating_evolution_narrative}
            </p>
          )}
        </div>
      ),
    });
  }

  if (domainSentiment.length > 1) {
    charts.push({
      key: 'domain_sentiment',
      render: () => (
        <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: 20, marginBottom: 24 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)', marginBottom: 12 }}>
            {t('domain_sentiment_trend')}
          </h3>
          <DomainSentimentTrend data={domainSentiment} />
          {report.domain_sentiment_narrative && (
            <p className="body-sm" style={{ margin: '8px 0 0', lineHeight: 1.5, color: 'var(--text-secondary)', fontSize: 12 }}>
              {report.domain_sentiment_narrative}
            </p>
          )}
        </div>
      ),
    });
  }

  if (seasonal.length > 1) {
    charts.push({
      key: 'seasonal',
      render: () => (
        <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: 20, marginBottom: 24 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)', marginBottom: 12 }}>
            {t('seasonal_pattern')}
          </h3>
          <SeasonalPatternChart data={seasonal} />
          {report.seasonal_narrative && (
            <p className="body-sm" style={{ margin: '8px 0 0', lineHeight: 1.5, color: 'var(--text-secondary)', fontSize: 12 }}>
              {report.seasonal_narrative}
            </p>
          )}
        </div>
      ),
    });
  }

  // With narrative: 1 chart on first page (header + narrative + chart), 2 on continuation
  // Without narrative: 2 charts on first page (header + 2 charts), 3 on continuation
  const hasNarrative = !!report.trends_narrative;
  const pages = paginateItems(charts, hasNarrative ? 1 : 2, hasNarrative ? 2 : 3);

  return (
    <>
      {pages.map((pageCharts, pageIdx) => (
        <ReportPage key={pageIdx} pageNumber={startPage + pageIdx} totalPages={totalPages} background="gray">
          {pageIdx === 0 ? (
            <>
              <SectionHeader
                number={sectionNumber}
                title={t('trends_timeline')}
                subtitle={t('trends_timeline_lead')}
              />
              {report.trends_narrative && (
                <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: '16px 20px', marginBottom: 20 }}>
                  <p className="body-sm" style={{ margin: 0, lineHeight: 1.6, color: 'var(--text-secondary)' }}>
                    {report.trends_narrative}
                  </p>
                </div>
              )}
            </>
          ) : (
            <div className="caption" style={{ marginBottom: 16, fontSize: 12 }}>
              {t('trends_timeline')} ({t('continued')})
            </div>
          )}

          {pageCharts.map((chart) => (
            <div key={chart.key}>{chart.render()}</div>
          ))}
        </ReportPage>
      ))}
    </>
  );
}
