import { Link } from '@inertiajs/react';
import { useMemo } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { PageHeader } from '@/Components/UI/PageHeader';
import { StatCard } from '@/Components/UI/StatCard';
import { EmptyState } from '@/Components/UI/EmptyState';
import { BarsChart, TrendAreaChart } from '@/Components/Charts/PanelCharts';
import { formatCount } from '@/lib/formatters';
import { formatJalali } from '@/lib/persianDate';

type Score = {
  id: number;
  subject: string;
  score: number;
  maxScore: number;
  statusKey: string;
  status: string;
  description: string | null;
  createdAt: string;
};

type Props = {
  student: { id: number; name: string; code: string };
  scores: Score[];
  scopeAll: boolean;
};

const statusBadge: Record<string, string> = {
  draft: 'badge-muted',
  submitted: 'badge-warning',
  approved: 'badge-success',
  rejected: 'badge-danger',
};

function percent(score: Score): number {
  return score.maxScore > 0 ? (score.score / score.maxScore) * 100 : 0;
}

export default function StudentScores({ student, scores, scopeAll }: Props) {
  const stats = useMemo(() => {
    if (scores.length === 0) return null;
    const percents = scores.map(percent);
    const avg = percents.reduce((a, b) => a + b, 0) / percents.length;
    const best = scores[percents.indexOf(Math.max(...percents))];
    const worst = scores[percents.indexOf(Math.min(...percents))];
    return { avg, best, worst };
  }, [scores]);

  const trendData = useMemo(
    () => scores.map((score) => ({
      label: formatJalali(score.createdAt),
      value: Math.round(percent(score)),
    })),
    [scores],
  );

  const subjectData = useMemo(() => {
    const map = new Map<string, { sum: number; count: number }>();
    for (const score of scores) {
      const entry = map.get(score.subject) ?? { sum: 0, count: 0 };
      entry.sum += percent(score);
      entry.count += 1;
      map.set(score.subject, entry);
    }
    return Array.from(map.entries()).map(([label, { sum, count }]) => ({
      label,
      value: Math.round(sum / count),
    }));
  }, [scores]);

  return (
    <AppLayout title={`کارنامه ${student.name}`}>
      <div className="page-stack">
        <PageHeader
          title={`کارنامه ${student.name}`}
          icon="bi-mortarboard"
          description={`${scopeAll ? 'همه نمرات ثبت‌شده این دانش‌آموز.' : 'نمرات درس‌هایی که شما برای این دانش‌آموز ثبت کرده‌اید.'} درصدها نسبت به «نمره از» هر آزمون محاسبه می‌شوند.`}
        >
          <Link href="/teacher/grades" className="btn btn-ghost">
            <i className="bi bi-arrow-right" /> بازگشت به نمره‌دهی
          </Link>
        </PageHeader>

        {scores.length === 0 ? (
          <div className="panel-card">
            <EmptyState
              icon="bi-journal-x"
              title="نمره‌ای ثبت نشده"
              description="هنوز برای این دانش‌آموز نمره‌ای ثبت نکرده‌اید. بعد از ثبت نمره، روند پیشرفت اینجا نمایش داده می‌شود."
            >
              <Link href="/teacher/grades" className="btn btn-primary">
                <i className="bi bi-plus-lg" /> ثبت نمره جدید
              </Link>
            </EmptyState>
          </div>
        ) : (
          <>
            <section className="dashboard-grid">
              <StatCard icon="bi-collection" label="تعداد نمرات" value={scores.length} tone="info" />
              {stats && (
                <>
                  <StatCard
                    icon="bi-graph-up-arrow"
                    label="میانگین کل"
                    value={`${formatCount(Math.round(stats.avg))}٪`}
                    tone={stats.avg >= 70 ? 'primary' : stats.avg >= 50 ? 'warning' : 'danger'}
                  />
                  <StatCard
                    icon="bi-trophy"
                    label="بهترین نمره"
                    value={`${formatCount(stats.best.score)} از ${formatCount(stats.best.maxScore)}`}
                    hint={stats.best.subject}
                    tone="primary"
                  />
                  <StatCard
                    icon="bi-arrow-down-right-circle"
                    label="ضعیف‌ترین نمره"
                    value={`${formatCount(stats.worst.score)} از ${formatCount(stats.worst.maxScore)}`}
                    hint={stats.worst.subject}
                    tone="danger"
                  />
                </>
              )}
            </section>

            <div className="card-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))' }}>
              <article className="panel-card">
                <h3 style={{ marginBottom: '1rem', fontSize: '0.95rem' }}>
                  <i className="bi bi-graph-up" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
                  روند نمرات (درصد)
                </h3>
                <TrendAreaChart data={trendData} />
              </article>
              <article className="panel-card">
                <h3 style={{ marginBottom: '1rem', fontSize: '0.95rem' }}>
                  <i className="bi bi-bar-chart" style={{ marginLeft: '0.4rem', color: 'var(--color-accent-hover)' }} />
                  میانگین هر درس (درصد)
                </h3>
                <BarsChart data={subjectData} color="#0EA5E9" />
              </article>
            </div>

            <div className="table-wrap">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>درس</th>
                    <th>نمره</th>
                    <th>درصد</th>
                    <th>وضعیت</th>
                    <th>تاریخ ثبت</th>
                    <th>توضیح</th>
                  </tr>
                </thead>
                <tbody>
                  {scores.map((score) => (
                    <tr key={score.id}>
                      <td>{score.subject}</td>
                      <td>{formatCount(score.score)} از {formatCount(score.maxScore)}</td>
                      <td>
                        <span className={`badge ${percent(score) >= 70 ? 'badge-success' : percent(score) >= 50 ? 'badge-warning' : 'badge-danger'}`}>
                          {formatCount(Math.round(percent(score)))}٪
                        </span>
                      </td>
                      <td>
                        <span className={`badge ${statusBadge[score.statusKey] || 'badge-muted'}`}>{score.status}</span>
                      </td>
                      <td style={{ whiteSpace: 'nowrap' }}>{formatJalali(score.createdAt)}</td>
                      <td style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>{score.description ?? '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}
      </div>
    </AppLayout>
  );
}
