import { Link, usePage } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { DashboardFeed } from '@/Components/Dashboard/DashboardFeed';
import { formatCount } from '@/lib/formatters';
import { formatPersianTime, formatPersianTimeRange } from '@/lib/persianDate';
import type { ModuleKey } from '@/types';

type OnlineClass = {
  id: number;
  title: string;
  subject: string;
  meetingUrl: string | null;
  startsAt: string;
};

type NewsItem = {
  id: number;
  title: string;
  body: string;
  imagePath: string | null;
  isImportant: boolean;
  template: string;
  accentColor: string;
  read: boolean;
  createdAt: string;
};

type GradeStat = {
  subject: string;
  avgPct: number;
  count: number;
};

type ScheduleEntry = {
  scheduleId: number;
  time: string;
  subject: string;
  teacher: string;
};

type NextClass = {
  time: string;
  subject: string;
  teacher: string;
  dayName: string;
  isToday: boolean;
};

type Props = {
  metrics: {
    todayClasses: number;
    activeExams: number;
    openHomeworks: number;
    monthAbsences: number;
  };
  onlineClasses: OnlineClass[];
  activeVotingCount: number;
  approvedGradeCount: number;
  news: NewsItem[];
  todaySchedule: ScheduleEntry[];
  nextClass: NextClass | null;
  gradeStats: GradeStat[];
};

// ── Grade performance bars ──────────────────────────────────────────────────
function GradeChart({ stats }: { stats: GradeStat[] }) {
  if (stats.length === 0) return null;

  const overallAvg = Math.round(stats.reduce((s, g) => s + g.avgPct, 0) / stats.length);
  const avgColor = overallAvg >= 70 ? '#0EA678' : overallAvg >= 50 ? '#F59E0B' : '#EF4444';

  return (
    <section className="panel-card">
      <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.9rem' }}>
        <i className="bi bi-bar-chart-line-fill" style={{ color: 'var(--color-primary)', fontSize: '1rem' }} />
        <h2 style={{ margin: 0, flex: 1, fontSize: '0.97rem', fontWeight: 700 }}>عملکرد تحصیلی</h2>
        <span style={{
          fontSize: '1.15rem',
          fontWeight: 800,
          color: avgColor,
          fontVariantNumeric: 'tabular-nums',
        }}>
          {overallAvg}٪
        </span>
        <span style={{ fontSize: '0.72rem', color: 'var(--color-text-muted)' }}>میانگین کل</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.55rem' }}>
        {stats.map((s) => {
          const pct = Math.round(s.avgPct);
          const color = pct >= 70 ? '#0EA678' : pct >= 50 ? '#F59E0B' : '#EF4444';
          return (
            <div key={s.subject}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '0.18rem' }}>
                <span style={{ fontSize: '0.82rem', color: 'var(--color-text)' }}>{s.subject}</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                  <span style={{ fontSize: '0.68rem', color: 'var(--color-text-muted)' }}>{s.count} نمره</span>
                  <span style={{ fontSize: '0.8rem', fontWeight: 700, color, minWidth: 36, textAlign: 'left', fontVariantNumeric: 'tabular-nums' }}>
                    {pct}٪
                  </span>
                </div>
              </div>
              <div style={{ background: 'var(--color-border, #e2e8f0)', borderRadius: 99, height: 7, overflow: 'hidden' }}>
                <div
                  style={{
                    width: `${pct}%`,
                    height: '100%',
                    background: `linear-gradient(90deg, ${color}99, ${color})`,
                    borderRadius: 99,
                    transition: 'width 0.7s cubic-bezier(.4,0,.2,1)',
                  }}
                />
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ marginTop: '0.85rem', textAlign: 'center' }}>
        <Link href="/student/grades" style={{ fontSize: '0.8rem', color: 'var(--color-primary)', textDecoration: 'none', fontWeight: 600 }}>
          مشاهده همه نمرات <i className="bi bi-arrow-left" />
        </Link>
      </div>
    </section>
  );
}

// ── Main page ───────────────────────────────────────────────────────────────
export default function StudentHome({
  metrics,
  onlineClasses,
  activeVotingCount,
  approvedGradeCount,
  news,
  todaySchedule,
  nextClass,
  gradeStats,
}: Props) {
  const { props } = usePage<{ modules?: ModuleKey[] }>();
  const attendanceEnabled = (props.modules ?? []).includes('attendance');

  return (
    <AppLayout title="پنل دانش‌آموز">
      <div className="page-stack">
        <DashboardFeed news={news} />

        {/* Metric cards */}
        <section className="dashboard-grid dashboard-grid--animated">
          <article className="metric-card"><span>کلاس‌های امروز</span><strong>{formatCount(metrics.todayClasses)}</strong></article>
          <Link href="/student/exams" className="metric-card" style={{ textDecoration: 'none' }}>
            <span>امتحان فعال</span>
            <strong>{formatCount(metrics.activeExams)}</strong>
          </Link>
          <Link href="/student/homeworks" className="metric-card" style={{ textDecoration: 'none' }}>
            <span>تکلیف باز</span>
            <strong>{formatCount(metrics.openHomeworks)}</strong>
          </Link>
          {attendanceEnabled && (
            <Link href="/student/attendance" className="metric-card" style={{ textDecoration: 'none' }}>
              <span>غیبت ماه</span>
              <strong>{formatCount(metrics.monthAbsences)}</strong>
            </Link>
          )}
          {approvedGradeCount > 0 && (
            <Link href="/student/grades" className="metric-card" style={{ textDecoration: 'none' }}>
              <span><i className="bi bi-patch-check" style={{ marginLeft: '0.3rem' }} />نمرات ثبت‌شده</span>
              <strong>{formatCount(approvedGradeCount)}</strong>
            </Link>
          )}
          {activeVotingCount > 0 && (
            <Link href="/student/voting" className="metric-card" style={{ textDecoration: 'none', borderColor: 'var(--color-primary)', background: 'var(--color-primary-soft)' }}>
              <span><i className="bi bi-ballot" style={{ marginLeft: '0.3rem', color: 'var(--color-primary)' }} />رأی‌گیری فعال</span>
              <strong style={{ color: 'var(--color-primary-active)' }}>{formatCount(activeVotingCount)}</strong>
            </Link>
          )}
        </section>

        {/* Grade performance chart */}
        <GradeChart stats={gradeStats} />

        <section className="split-panel">
          <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            {/* کلاس بعدی */}
            {nextClass && (
              <div style={{
                background: nextClass.isToday ? 'var(--color-primary-soft)' : 'var(--color-bg-soft)',
                border: `1.5px solid ${nextClass.isToday ? 'var(--color-primary)' : 'var(--color-border)'}`,
                borderRadius: 'var(--radius-md)',
                padding: '0.75rem 1rem',
                display: 'flex',
                alignItems: 'center',
                gap: '0.75rem',
              }}>
                <i className="bi bi-alarm" style={{ fontSize: '1.4rem', color: 'var(--color-primary)', flexShrink: 0 }} />
                <div>
                  <div style={{ fontWeight: 700, fontSize: '0.875rem' }}>
                    {nextClass.isToday ? 'کلاس بعدی امروز' : `کلاس بعدی — ${nextClass.dayName}`}
                  </div>
                  <div style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)' }}>
                    {nextClass.subject} · {nextClass.teacher} · ساعت {formatPersianTime(nextClass.time)}
                  </div>
                </div>
              </div>
            )}

            {/* برنامه امروز */}
            {todaySchedule.length > 0 && (
              <article className="panel-card">
                <h2 style={{ marginBottom: '0.75rem' }}><i className="bi bi-calendar-day" style={{ marginLeft: '0.4rem' }} />کلاس‌های امروز</h2>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                  {todaySchedule.map((s) => (
                    <li key={s.scheduleId} style={{ borderBottom: '1px solid var(--color-border)', padding: '0.6rem 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div>
                        <strong style={{ display: 'block', fontSize: '0.9rem' }}>{s.subject}</strong>
                        <span style={{ fontSize: '0.8rem', color: 'var(--color-text-soft)' }}>{s.teacher} · {formatPersianTimeRange(s.time)}</span>
                      </div>
                    </li>
                  ))}
                </ul>
              </article>
            )}
          </div>

          <article className="panel-card">
            <h2><i className="bi bi-camera-video" style={{ marginLeft: '0.4rem' }} />کلاس‌های آنلاین</h2>
            {onlineClasses.length === 0 ? (
              <p style={{ color: 'var(--color-text-muted)' }}>کلاس آنلاین برنامه‌ریزی‌شده‌ای وجود ندارد.</p>
            ) : (
              <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {onlineClasses.map((c) => (
                  <li key={c.id} style={{ borderBottom: '1px solid var(--color-border)', padding: '0.75rem 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <strong style={{ display: 'block' }}>{c.title}</strong>
                      <span style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>{c.subject} — {c.startsAt}</span>
                    </div>
                    <a href={`/student/online-classes/${c.id}/join`} target="_blank" rel="noreferrer" className="btn btn-primary btn-sm">
                      <i className="bi bi-box-arrow-up-left" /> ورود
                    </a>
                  </li>
                ))}
              </ul>
            )}
          </article>
        </section>
      </div>
    </AppLayout>
  );
}
