import { useState } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type Subject = {
  subjectId: number;
  subjectName: string;
  teacher: string;
};

type Classroom = {
  id: number;
  name: string;
  grade: string | null;
  subjects: Subject[];
};

type Homework = {
  id: number;
  title: string;
  description: string | null;
  dueDate: string | null;
  subjectName: string;
  classroom: string;
};
type TeacherRow = {
  teacherUserId: number | null;
  teacherName: string;
  subjectName: string;
  classroomName: string;
};
type AcademicProfile = {
  name: string;
  studentCode: string;
  nationalCode: string;
  grade: string;
  classroom: string;
  enrolledAt: string;
  awards: { title: string; description: string | null; color: string; awardedAt: string }[];
};

type Props = {
  classrooms: Classroom[];
  homeworks: Homework[];
  teachers: TeacherRow[];
  profile: AcademicProfile | null;
};

export default function StudentClasses({ classrooms, homeworks, teachers, profile }: Props) {
  const [tab, setTab] = useState<'profile' | 'classes' | 'teachers' | 'homeworks'>('profile');

  // Group homeworks by subject
  const hwBySubject: Record<string, Homework[]> = {};
  for (const hw of homeworks) {
    const key = hw.subjectName;
    if (!hwBySubject[key]) hwBySubject[key] = [];
    hwBySubject[key].push(hw);
  }
  const subjectNames = Object.keys(hwBySubject).sort((a, b) => a.localeCompare(b, 'fa'));

  return (
    <AppLayout title="کلاس‌های من">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-door-open" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />کلاس‌های من</h2>
            <p>درس‌ها، معلمان و تکالیف شما</p>
          </div>
        </section>

        <div className="tab-bar">
          <button className={`tab-btn${tab === 'profile' ? ' active' : ''}`} type="button" onClick={() => setTab('profile')}>
            <i className="bi bi-person-badge" style={{ marginLeft: '0.3rem' }} />
            پروفایل تحصیلی
          </button>
          <button className={`tab-btn${tab === 'classes' ? ' active' : ''}`} type="button" onClick={() => setTab('classes')}>
            <i className="bi bi-grid" style={{ marginLeft: '0.3rem' }} />
            کلاس‌ها و درس‌ها
          </button>
          <button className={`tab-btn${tab === 'teachers' ? ' active' : ''}`} type="button" onClick={() => setTab('teachers')}>
            <i className="bi bi-person-workspace" style={{ marginLeft: '0.3rem' }} />
            معلمان من
          </button>
          <button className={`tab-btn${tab === 'homeworks' ? ' active' : ''}`} type="button" onClick={() => setTab('homeworks')}>
            <i className="bi bi-journal-check" style={{ marginLeft: '0.3rem' }} />
            تکالیف
            {homeworks.length > 0 && (
              <span className="badge badge-warning" style={{ marginRight: '0.4rem', fontSize: '0.75rem' }}>{homeworks.length}</span>
            )}
          </button>
        </div>

        {tab === 'profile' && (
          <section className="panel-card">
            {profile ? (
              <>
                <h3 style={{ marginTop: 0 }}>{profile.name}</h3>
                <div className="dashboard-grid">
                  <article className="metric-card"><span>کد دانش‌آموزی</span><strong>{profile.studentCode}</strong></article>
                  <article className="metric-card"><span>کد ملی</span><strong>{profile.nationalCode}</strong></article>
                  <article className="metric-card"><span>پایه</span><strong>{profile.grade}</strong></article>
                  <article className="metric-card"><span>کلاس فعال</span><strong>{profile.classroom}</strong></article>
                  <article className="metric-card"><span>تاریخ ثبت‌نام</span><strong>{profile.enrolledAt}</strong></article>
                </div>
                {profile.awards.length > 0 && (
                  <div style={{ marginTop: 20 }}>
                    <h3>نشان‌ها و تقدیرنامه‌ها</h3>
                    <div className="action-row" style={{ flexWrap: 'wrap' }}>
                      {profile.awards.map((award, index) => (
                        <span key={`${award.title}-${index}`} className="badge" style={{ background: award.color, color: '#fff', padding: '0.55rem 0.8rem' }} title={award.description || award.awardedAt}>
                          <i className="bi bi-award" style={{ marginLeft: 6 }} />{award.title}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </>
            ) : (
              <p style={{ color: 'var(--color-text-muted)' }}>پرونده تحصیلی پیدا نشد.</p>
            )}
          </section>
        )}

        {tab === 'classes' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            {classrooms.length === 0 ? (
              <section className="panel-card">
                <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
                  <i className="bi bi-door-open" style={{ fontSize: '2rem', color: 'var(--color-text-muted)', display: 'block', marginBottom: '1rem' }} />
                  <h2>هنوز در هیچ کلاسی ثبت‌نام نشده‌اید</h2>
                </div>
              </section>
            ) : (
              classrooms.map((cls) => (
                <section key={cls.id} className="panel-card">
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1rem' }}>
                    <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--color-primary-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <i className="bi bi-door-open" style={{ color: 'var(--color-primary)', fontSize: '1.1rem' }} />
                    </div>
                    <div>
                      <h3 style={{ margin: 0, fontSize: '1rem' }}>{cls.name}</h3>
                      {cls.grade && <small style={{ color: 'var(--color-text-muted)' }}>{cls.grade}</small>}
                    </div>
                    <span className="badge badge-muted" style={{ marginRight: 'auto' }}>
                      {cls.subjects.length} درس
                    </span>
                  </div>

                  {cls.subjects.length === 0 ? (
                    <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>درسی تعریف نشده</p>
                  ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
                      {cls.subjects.map((subj) => (
                        <div
                          key={subj.subjectId}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            padding: '0.55rem 0.85rem',
                            background: 'var(--color-bg-muted)',
                            borderRadius: 'var(--radius-sm)',
                            border: '1px solid var(--color-border)',
                          }}
                        >
                          <span style={{ fontWeight: 600, fontSize: '0.9rem' }}>
                            <i className="bi bi-book" style={{ marginLeft: '0.4rem', color: 'var(--color-primary)' }} />
                            {subj.subjectName}
                          </span>
                          <span style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)' }}>
                            <i className="bi bi-person-workspace" style={{ marginLeft: '0.25rem' }} />
                            {subj.teacher}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </section>
              ))
            )}
          </div>
        )}

        {tab === 'teachers' && (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            {teachers.length === 0 ? (
              <p style={{ padding: '2rem', textAlign: 'center', color: 'var(--color-text-muted)' }}>هنوز معلمی برای کلاس‌های شما ثبت نشده است.</p>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table className="data-table" style={{ width: '100%' }}>
                  <thead>
                    <tr>
                      <th>معلم</th>
                      <th>درس</th>
                      <th>کلاس</th>
                      <th>ارتباط</th>
                    </tr>
                  </thead>
                  <tbody>
                    {teachers.map((teacher, i) => (
                      <tr key={`${teacher.teacherUserId}-${teacher.subjectName}-${i}`}>
                        <td style={{ fontWeight: 700 }}>{teacher.teacherName}</td>
                        <td>{teacher.subjectName}</td>
                        <td>{teacher.classroomName}</td>
                        <td>
                          <a className="btn btn-ghost btn-sm" href={teacher.teacherUserId ? `/student/messages?to=${teacher.teacherUserId}` : '/student/messages'}>
                            <i className="bi bi-envelope" /> پیام
                          </a>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        )}

        {tab === 'homeworks' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            {homeworks.length === 0 ? (
              <section className="panel-card">
                <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
                  <i className="bi bi-journal-check" style={{ fontSize: '2rem', color: 'var(--color-text-muted)', display: 'block', marginBottom: '1rem' }} />
                  <h2>تکلیفی ثبت نشده</h2>
                  <p>هنوز هیچ تکلیف فعالی وجود ندارد.</p>
                </div>
              </section>
            ) : (
              subjectNames.map((subjectName) => (
                <section key={subjectName} className="panel-card">
                  <h3 style={{ margin: '0 0 0.75rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <i className="bi bi-book" style={{ color: 'var(--color-primary)' }} />
                    {subjectName}
                    <span className="badge badge-muted" style={{ fontSize: '0.72rem' }}>{hwBySubject[subjectName].length} تکلیف</span>
                  </h3>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                    {hwBySubject[subjectName].map((hw) => (
                      <div
                        key={hw.id}
                        style={{
                          padding: '0.65rem 0.9rem',
                          background: 'var(--color-bg-muted)',
                          borderRadius: 'var(--radius-sm)',
                          border: '1px solid var(--color-border)',
                        }}
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '0.5rem' }}>
                          <strong style={{ fontSize: '0.9rem' }}>{hw.title}</strong>
                          <div style={{ flexShrink: 0, textAlign: 'left' }}>
                            {hw.dueDate && (
                              <span style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)' }}>
                                <i className="bi bi-clock" style={{ marginLeft: '0.2rem' }} />
                                {hw.dueDate}
                              </span>
                            )}
                          </div>
                        </div>
                        {hw.description && (
                          <p style={{ margin: '0.35rem 0 0', fontSize: '0.82rem', color: 'var(--color-text-muted)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
                            {hw.description}
                          </p>
                        )}
                        <span style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)', display: 'inline-block', marginTop: '0.3rem' }}>
                          <i className="bi bi-door-open" style={{ marginLeft: '0.2rem' }} />
                          {hw.classroom}
                        </span>
                      </div>
                    ))}
                  </div>
                </section>
              ))
            )}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
