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

type TodayClass = {
  time: string;
  classroom: string;
  subject: string;
};

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

type Stats = {
  totalStudents: number;
  activeClasses: number;
  pendingGrades: number;
  openHomeworks: number;
};

type Props = {
  stats: Stats;
  todaySchedule: TodayClass[];
  nextClass: NextClass | null;
  news: DashboardNewsFeedItem[];
};

export default function MyClasses({ stats, todaySchedule, nextClass, news }: Props) {
  const { props } = usePage<{ modules?: ModuleKey[] }>();
  const gradesEnabled = (props.modules ?? []).includes('grades');
  const homeworkEnabled = (props.modules ?? []).includes('homework');

  const quickLinks = [
    { href: '/teacher/students', icon: 'bi-people', label: 'لیست دانش‌آموزان', show: true },
    { href: '/teacher/grade-sheet', icon: 'bi-table', label: 'کارنامه گروهی', show: gradesEnabled },
    { href: '/teacher/class-stats', icon: 'bi-bar-chart-line', label: 'آمار نمرات', show: gradesEnabled },
    { href: '/teacher/grades', icon: 'bi-pencil-square', label: 'ثبت نمره', show: gradesEnabled },
    { href: '/teacher/homeworks', icon: 'bi-journal-check', label: 'تکالیف', show: homeworkEnabled },
  ].filter((link) => link.show);

  return (
    <AppLayout title="داشبورد معلم">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>داشبورد معلم</h2>
            <p>خلاصه وضعیت کلاس‌ها و فعالیت‌های شما</p>
          </div>
        </section>

        <DashboardFeed news={news} />

        <section className="dashboard-grid dashboard-grid--animated" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))' }}>
          <StatCard
            icon="bi-people"
            label="کل دانش‌آموزان"
            value={stats.totalStudents}
            tone="primary"
            href="/teacher/students"
          />
          <StatCard
            icon="bi-door-open"
            label="کلاس‌های فعال"
            value={stats.activeClasses}
            tone="info"
          />
          {gradesEnabled && (
            <StatCard
              icon="bi-pencil-square"
              label="نمرات در انتظار تایید"
              value={stats.pendingGrades === 0 ? ('همه تایید شده‌اند' as any) : stats.pendingGrades}
              tone={stats.pendingGrades === 0 ? 'primary' : 'warning'}
              href={stats.pendingGrades > 0 ? '/teacher/grades' : undefined}
            />
          )}
          {homeworkEnabled && (
            <StatCard
              icon="bi-journal-check"
              label="تکالیف باز"
              value={stats.openHomeworks === 0 ? ('تکلیف باز ندارید' as any) : stats.openHomeworks}
              tone={stats.openHomeworks === 0 ? 'primary' : 'violet'}
              href={stats.openHomeworks > 0 ? '/teacher/homeworks' : undefined}
            />
          )}
        </section>

        {/* Next Class Banner */}
        {nextClass && (
          <section 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 1.25rem',
            display: 'flex',
            alignItems: 'center',
            gap: '1rem',
            flexWrap: 'wrap',
          }}>
            <i className="bi bi-alarm" style={{ fontSize: '1.5rem', color: 'var(--color-primary)' }} />
            <div>
              <div style={{ fontWeight: 700, fontSize: '0.9rem' }}>
                {nextClass.isToday ? 'کلاس بعدی امروز' : `کلاس بعدی — ${nextClass.dayName}`}
              </div>
              <div style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
                {nextClass.subject} · {nextClass.classroom} · ساعت {formatPersianTime(nextClass.time)}
              </div>
            </div>
          </section>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: todaySchedule.length > 0 ? '1fr 1fr' : '1fr', gap: '1rem' }}>
          {/* Today's schedule */}
          {todaySchedule.length > 0 && (
            <section className="panel-card">
              <h3 style={{ marginBottom: '0.75rem' }}>
                <i className="bi bi-calendar-day" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
                کلاس‌های امروز
              </h3>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {todaySchedule.map((s, i) => (
                  <li key={i} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--color-border)', 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-muted)' }}>{s.classroom}</span>
                    </div>
                    <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>{formatPersianTimeRange(s.time)}</span>
                  </li>
                ))}
              </ul>
            </section>
          )}

          {/* Quick links */}
          <section className="panel-card">
            <h3 style={{ marginBottom: '0.25rem' }}>
              <i className="bi bi-grid-3x3-gap" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
              دسترسی سریع
            </h3>
            <p style={{ margin: '0 0 1rem', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
              پرکاربردترین بخش‌ها، یک کلیک فاصله
            </p>
            <div className="quick-access-grid">
              {quickLinks.map((link) => (
                <Link key={link.href} className="quick-access-tile" href={link.href}>
                  <span className="quick-access-icon">
                    <i className={`bi ${link.icon}`} />
                  </span>
                  <span className="quick-access-label">{link.label}</span>
                  <i className="bi bi-chevron-left quick-access-chevron" />
                </Link>
              ))}
            </div>
          </section>
        </div>
      </div>
    </AppLayout>
  );
}
