'use client';

import type { ReportSynthesis, StaffMember, StaffLeaderboardResolved, StaffIndividual, StaffGroup } from '../types';
import type { ReportLocale } from '../i18n/useReportLocale';
import { useReportLocale } from '../i18n/useReportLocale';
import ReportPage from '../components/ReportPage';
import SectionHeader from '../components/SectionHeader';
import { paginateItems } from '../utils/paginate';

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

const RANK_COLORS: Record<number, { bg: string; color: string }> = {
  1: { bg: '#FEF3C7', color: '#92400E' },
  2: { bg: '#F1F5F9', color: '#475569' },
  3: { bg: '#FED7AA', color: '#9A3412' },
};

// First page has section header + callout -> fewer rows
const FIRST_PAGE_ROWS = 6;
const NEXT_PAGE_ROWS = 12;

function isResolvedStaff(staff: any): staff is StaffLeaderboardResolved {
  return staff && typeof staff === 'object' && !Array.isArray(staff) && 'individuals' in staff;
}

export default function StaffLeaderboard({ report, locale = 'en', startPage = 8, totalPages = 10, sectionNumber = 7 }: StaffLeaderboardProps) {
  const { t } = useReportLocale(locale);
  const staff = report.staff_leaderboard;

  if (!staff) return null;

  if (isResolvedStaff(staff)) {
    return (
      <ResolvedStaffLeaderboard
        resolved={staff}
        locale={locale}
        startPage={startPage}
        totalPages={totalPages}
        sectionNumber={sectionNumber}
        t={t}
      />
    );
  }

  // Legacy array format
  if (!Array.isArray(staff) || staff.length === 0) return null;
  return (
    <LegacyStaffLeaderboard
      staff={staff}
      locale={locale}
      startPage={startPage}
      totalPages={totalPages}
      sectionNumber={sectionNumber}
      t={t}
    />
  );
}

// ---------------------------------------------------------------------------
// Resolved (v2.1.0+) format
// ---------------------------------------------------------------------------

function ResolvedStaffLeaderboard({
  resolved,
  locale,
  startPage,
  totalPages,
  sectionNumber,
  t,
}: {
  resolved: StaffLeaderboardResolved;
  locale: string;
  startPage: number;
  totalPages: number;
  sectionNumber: number;
  t: (key: string) => string;
}) {
  const { individuals, groups } = resolved;

  if (individuals.length === 0 && groups.length === 0) return null;

  const topPerformer = individuals[0] || null;

  return (
    <ReportPage pageNumber={startPage} totalPages={totalPages} background="white">
      <SectionHeader
        number={sectionNumber}
        title={t('staff_leaderboard')}
        subtitle={t('staff_leaderboard_lead')}
      />

      {/* Top Performer Callout */}
      {topPerformer && topPerformer.positive_quotes.length > 0 && (
        <div className="insight-callout green" style={{ marginBottom: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span className="heading-md" style={{ color: 'var(--ui-success)' }}>
              {t('staff_top_performer')}: {topPerformer.canonical_name}
            </span>
          </div>
          <div className="evidence-quote green" style={{ margin: 0 }}>
            &ldquo;{topPerformer.positive_quotes[0]}&rdquo;
          </div>
        </div>
      )}

      {/* Individuals Table */}
      {individuals.length > 0 && (
        <>
          <h3 className="caption" style={{ marginBottom: 8 }}>{t('staff_individuals')}</h3>
          <ResolvedTable members={individuals} t={t} showRole />
        </>
      )}

      {/* Groups Table */}
      {groups.length > 0 && (
        <>
          <h3 className="caption" style={{ marginTop: 20, marginBottom: 8 }}>{t('staff_groups')}</h3>
          <ResolvedTable members={groups} t={t} showRole={false} />
        </>
      )}

      {/* Observations */}
      {resolved.observations && (
        <div className="insight-callout" style={{ marginTop: 16, background: '#F0F9FF', borderLeftColor: '#3B82F6' }}>
          <p className="body-sm" style={{ color: 'var(--text-secondary)', margin: 0 }}>
            {resolved.observations}
          </p>
        </div>
      )}

      {/* Disclaimer */}
      <div className="insight-callout" style={{ marginTop: 16, background: '#FFF7ED', borderLeftColor: '#F59E0B' }}>
        <p className="body-sm" style={{ color: 'var(--text-secondary)', margin: 0 }}>
          <strong style={{ color: '#92400E' }}>&#9888;</strong> {t('staff_disclaimer')}
        </p>
      </div>
    </ReportPage>
  );
}

function ResolvedTable({
  members,
  t,
  showRole,
}: {
  members: (StaffIndividual | StaffGroup)[];
  t: (key: string) => string;
  showRole: boolean;
}) {
  return (
    <table className="scoring-table">
      <thead>
        <tr>
          <th style={{ width: 60 }}>{t('staff_rank')}</th>
          <th>{t('staff_name')}</th>
          {showRole && <th style={{ width: 100 }}>{t('staff_role')}</th>}
          <th style={{ width: 90, textAlign: 'center' }}>{t('staff_mentions')}</th>
          <th style={{ width: 100, textAlign: 'center' }}>{t('staff_sentiment')}</th>
          <th style={{ width: 80, textAlign: 'center' }}>{t('staff_positive')}</th>
          <th style={{ width: 80, textAlign: 'center' }}>{t('staff_negative')}</th>
        </tr>
      </thead>
      <tbody>
        {members.map((member, i) => {
          const rank = i + 1;
          const rankStyle = RANK_COLORS[rank];
          const sentimentScore = member.sentiment_score ?? 0;
          const role = showRole && 'role_inferred' in member ? (member as StaffIndividual).role_inferred : null;

          return (
            <tr key={member.canonical_name}>
              <td style={{ textAlign: 'center' }}>
                {rankStyle ? (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    width: 28, height: 28, borderRadius: '50%',
                    background: rankStyle.bg, color: rankStyle.color,
                    fontWeight: 700, fontSize: 13,
                  }}>
                    {rank}
                  </span>
                ) : (
                  <span style={{ fontWeight: 600, color: 'var(--text-secondary)' }}>{rank}</span>
                )}
              </td>
              <td style={{ fontWeight: 600 }}>{member.canonical_name}</td>
              {showRole && <td style={{ color: 'var(--text-secondary)', fontSize: 12 }}>{role || '\u2014'}</td>}
              <td style={{ textAlign: 'center', fontWeight: 600 }}>{member.total_mentions}</td>
              <td style={{ textAlign: 'center' }}>
                <span className={`score-badge ${sentimentScore >= 70 ? 'green' : 'amber'}`}>
                  {sentimentScore}%
                </span>
              </td>
              <td style={{ textAlign: 'center', color: 'var(--ui-success)', fontWeight: 600 }}>
                {member.positive}
              </td>
              <td style={{ textAlign: 'center', color: 'var(--ui-error)', fontWeight: 600 }}>
                {member.negative}
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

// ---------------------------------------------------------------------------
// Legacy (v2.0.0) array format
// ---------------------------------------------------------------------------

function LegacyStaffLeaderboard({
  staff,
  locale,
  startPage,
  totalPages,
  sectionNumber,
  t,
}: {
  staff: StaffMember[];
  locale: string;
  startPage: number;
  totalPages: number;
  sectionNumber: number;
  t: (key: string) => string;
}) {
  const topPerformer = staff[0];
  const pages = paginateItems(staff, FIRST_PAGE_ROWS, NEXT_PAGE_ROWS);

  return (
    <>
      {pages.map((pageStaff, pageIdx) => {
        // Compute global offset for rank numbering
        let globalOffset = 0;
        for (let p = 0; p < pageIdx; p++) globalOffset += pages[p]!.length;
        const isLastPage = pageIdx === pages.length - 1;

        return (
          <ReportPage key={pageIdx} pageNumber={startPage + pageIdx} totalPages={totalPages} background="white">
            {pageIdx === 0 ? (
              <>
                <SectionHeader
                  number={sectionNumber}
                  title={t('staff_leaderboard')}
                  subtitle={t('staff_leaderboard_lead')}
                />

                {/* Top Performer Callout */}
                {topPerformer && topPerformer.positive_quotes && topPerformer.positive_quotes.length > 0 && (
                  <div className="insight-callout green" style={{ marginBottom: 20 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                      <span className="heading-md" style={{ color: 'var(--ui-success)' }}>
                        {t('staff_top_performer')}: {topPerformer.name}
                      </span>
                    </div>
                    <div className="evidence-quote green" style={{ margin: 0 }}>
                      &ldquo;{topPerformer.positive_quotes[0]}&rdquo;
                    </div>
                  </div>
                )}
              </>
            ) : (
              <div className="caption" style={{ marginBottom: 16, fontSize: 12 }}>
                {t('staff_leaderboard')} ({t('continued')})
              </div>
            )}

            {/* Staff Table */}
            <LegacyStaffTable staff={pageStaff} globalOffset={globalOffset} t={t} />

            {/* Evidence Quotes -- only on the last page */}
            {isLastPage && (
              <>
                <StaffEvidence staff={staff.slice(0, 3)} t={t} />
                <div className="insight-callout" style={{ marginTop: 16, background: '#FFF7ED', borderLeftColor: '#F59E0B' }}>
                  <p className="body-sm" style={{ color: 'var(--text-secondary)', margin: 0 }}>
                    <strong style={{ color: '#92400E' }}>&#9888;</strong> {t('staff_disclaimer')}
                  </p>
                </div>
              </>
            )}
          </ReportPage>
        );
      })}
    </>
  );
}

function LegacyStaffTable({ staff, globalOffset, t }: { staff: StaffMember[]; globalOffset: number; t: (key: string) => string }) {
  return (
    <table className="scoring-table">
      <thead>
        <tr>
          <th style={{ width: 60 }}>{t('staff_rank')}</th>
          <th>{t('staff_name')}</th>
          <th style={{ width: 90, textAlign: 'center' }}>{t('staff_mentions')}</th>
          <th style={{ width: 100, textAlign: 'center' }}>{t('staff_sentiment')}</th>
          <th style={{ width: 80, textAlign: 'center' }}>{t('staff_positive')}</th>
          <th style={{ width: 80, textAlign: 'center' }}>{t('staff_negative')}</th>
        </tr>
      </thead>
      <tbody>
        {staff.map((member, i) => {
          const rank = globalOffset + i + 1;
          const rankStyle = RANK_COLORS[rank];
          const sentimentScore = member.sentiment_score ?? 0;

          return (
            <tr key={member.name}>
              <td style={{ textAlign: 'center' }}>
                {rankStyle ? (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    width: 28, height: 28, borderRadius: '50%',
                    background: rankStyle.bg, color: rankStyle.color,
                    fontWeight: 700, fontSize: 13,
                  }}>
                    {rank}
                  </span>
                ) : (
                  <span style={{ fontWeight: 600, color: 'var(--text-secondary)' }}>{rank}</span>
                )}
              </td>
              <td style={{ fontWeight: 600 }}>{member.name}</td>
              <td style={{ textAlign: 'center', fontWeight: 600 }}>{member.total_mentions}</td>
              <td style={{ textAlign: 'center' }}>
                <span className={`score-badge ${sentimentScore >= 70 ? 'green' : 'amber'}`}>
                  {sentimentScore}%
                </span>
              </td>
              <td style={{ textAlign: 'center', color: 'var(--ui-success)', fontWeight: 600 }}>
                {member.positive}
              </td>
              <td style={{ textAlign: 'center', color: 'var(--ui-error)', fontWeight: 600 }}>
                {member.negative}
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function StaffEvidence({ staff, t }: { staff: StaffMember[]; t: (key: string) => string }) {
  const hasQuotes = staff.some(m => m.positive_quotes && m.positive_quotes.length > 0);
  if (!hasQuotes) return null;

  return (
    <div style={{ marginTop: 24 }}>
      <div className="caption" style={{ marginBottom: 12 }}>
        {t('evidence')}
      </div>
      {staff.map((member) => {
        const quotes = member.positive_quotes?.slice(0, 1) || [];
        if (quotes.length === 0) return null;
        return (
          <div key={member.name} style={{ marginBottom: 8 }}>
            <span className="body-sm" style={{ fontWeight: 600, color: 'var(--text-primary)', marginRight: 6 }}>
              {member.name}:
            </span>
            {quotes.map((q, qi) => (
              <div key={qi} className="evidence-quote green">
                &ldquo;{q}&rdquo;
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
}
