'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 RatingTrend from '../charts/RatingTrend';
import SentimentDonut from '../charts/SentimentDonut';
import { getScoreColor } from '../styles/report-theme';

function getRatingBarColor(star: number): string {
  if (star === 5) return '#22c55e';
  if (star === 4) return '#84cc16';
  if (star === 3) return '#f59e0b';
  if (star === 2) return '#f97316';
  return '#ef4444';
}

interface RatingDashboardProps {
  report: ReportSynthesis;
  locale?: ReportLocale;
  pageNumber?: number;
  totalPages?: number;
}

export default function RatingDashboard({ report, locale = 'en', pageNumber = 3, totalPages = 9 }: RatingDashboardProps) {
  const { t } = useReportLocale(locale);
  const dist = report.rating_distribution;
  const distEntries = Object.entries(dist)
    .map(([k, v]) => ({ star: parseInt(k), count: v }))
    .sort((a, b) => b.star - a.star);
  const totalReviews = distEntries.reduce((sum, d) => sum + d.count, 0);
  const maxCount = Math.max(...distEntries.map(d => d.count), 1);
  const scoreColor = getScoreColor(report.reputation_score);

  const sentimentData = report.charts?.sentiment_donut || [];
  const positive = sentimentData.find(d => d.label === 'Positive')?.value || 0;
  const negative = sentimentData.find(d => d.label === 'Negative')?.value || 0;
  const neutral = sentimentData.find(d => d.label === 'Neutral')?.value || 0;
  const mixed = sentimentData.find(d => d.label === 'Mixed')?.value || 0;

  return (
    <ReportPage pageNumber={pageNumber} totalPages={totalPages} background="gray">
      <SectionHeader number={2} title={t('rating_dashboard')} subtitle={t('rating_dashboard_lead')} />

      {/* Stats Row */}
      <div className="stats-row">
        <div className="stat-item">
          <div className="stat-value text-primary">{report.current_rating.toFixed(1)}</div>
          <div className="stat-label">{t('current_rating')}</div>
        </div>
        <div className="stat-item">
          <div className="stat-value" style={{ color: scoreColor }}>{report.potential_rating.toFixed(1)}</div>
          <div className="stat-label">{t('potential_rating')}</div>
        </div>
        <div className="stat-item">
          <div className="stat-value text-primary">{totalReviews.toLocaleString()}</div>
          <div className="stat-label">{t('reviews_analyzed')}</div>
        </div>
        <div className="stat-item">
          <div className="stat-value" style={{ color: scoreColor }}>{Math.round(report.reputation_score)}</div>
          <div className="stat-label">{t('reputation_score')}</div>
        </div>
      </div>

      {/* Rating Narrative */}
      {report.rating_narrative && (
        <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: '16px 20px', marginTop: 16 }}>
          <p className="body-sm" style={{ margin: 0, lineHeight: 1.6, color: 'var(--text-secondary)' }}>
            {report.rating_narrative}
          </p>
        </div>
      )}

      {/* Two-column layout: Distribution + Sentiment */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginTop: 20 }}>
        {/* Rating Distribution */}
        <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: 20 }}>
          <h3 className="caption" style={{ marginBottom: 14 }}>{t('distribution')}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {distEntries.map((item) => {
              const pct = totalReviews > 0 ? (item.count / totalReviews) * 100 : 0;
              return (
                <div key={item.star} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span className="body-sm" style={{ width: 28, fontWeight: 600 }}>{item.star}★</span>
                  <div style={{ flex: 1, height: 16, background: 'var(--surface-muted)', borderRadius: 8, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${(item.count / maxCount) * 100}%`, backgroundColor: getRatingBarColor(item.star), borderRadius: 8 }} />
                  </div>
                  <span className="body-sm" style={{ width: 40, textAlign: 'right', fontWeight: 500 }}>{pct.toFixed(0)}%</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Sentiment Donut */}
        {(positive + negative + neutral + mixed) > 0 && (
          <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: 20 }}>
            <h3 className="caption" style={{ marginBottom: 14 }}>{t('sentiment_distribution')}</h3>
            <SentimentDonut positive={positive} negative={negative} neutral={neutral} mixed={mixed} />
          </div>
        )}
      </div>

      {/* Rating Trend */}
      {report.charts?.rating_trend && report.charts.rating_trend.length > 0 && (
        <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-brand)', padding: 20, marginTop: 20 }}>
          <h3 className="caption" style={{ marginBottom: 14 }}>{t('rating_trend')}</h3>
          <RatingTrend data={report.charts.rating_trend} />
        </div>
      )}
    </ReportPage>
  );
}
