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

type Module = {
  id: number;
  key: string;
  label: string;
  description: string | null;
  enabled: boolean;
};

type GradeItem = {
  id: number;
  label: string;
  number: number;
  enabled: boolean;
};

type School = {
  id: number;
  name: string;
  code: string;
  schoolType: string | null;
};

type Props = {
  school: School;
  modules: Module[];
  grades: GradeItem[];
};

const MODULE_ICONS: Record<string, string> = {
  attendance: 'bi-clipboard-check',
  grades: 'bi-patch-check',
  messages: 'bi-envelope',
  sms: 'bi-chat-dots',
  reports: 'bi-bar-chart',
  online_class: 'bi-camera-video',
  homework: 'bi-journal-check',
  exam: 'bi-pencil-square',
  voting: 'bi-check2-square',
  announcements: 'bi-megaphone',
  library: 'bi-book',
  finance: 'bi-cash-stack',
  transport: 'bi-bus-front',
  news: 'bi-newspaper',
  schedule: 'bi-calendar2-week',
  report_card: 'bi-file-earmark-bar-graph',
};

const SCHOOL_TYPE_LABELS: Record<string, string> = {
  ebtedaee: 'ابتدایی',
  motevasete_aval: 'متوسطه اول',
  motevasete_dovom: 'متوسطه دوم',
};

function getModuleIcon(key: string): string {
  for (const [k, icon] of Object.entries(MODULE_ICONS)) {
    if (key.includes(k)) return icon;
  }
  return 'bi-puzzle';
}

export default function SchoolModules({ school, modules, grades }: Props) {
  function handleModuleToggle(module: Module) {
    const action = module.enabled ? 'غیرفعال کردن' : 'فعال کردن';
    if (!confirm(`${action} ماژول «${module.label}» برای مدرسه «${school.name}»؟`)) return;
    router.patch(`/super-admin/schools/${school.id}/modules/${module.id}/toggle`, {}, { preserveScroll: true });
  }

  function handleGradeToggle(grade: GradeItem) {
    const action = grade.enabled ? 'حذف دسترسی' : 'فعال کردن';
    if (!confirm(`${action} «${grade.label}» برای مدرسه «${school.name}»؟`)) return;
    router.patch(`/super-admin/schools/${school.id}/grades/${grade.id}/toggle`, {}, { preserveScroll: true });
  }

  const enabledModules = modules.filter((m) => m.enabled);
  const disabledModules = modules.filter((m) => !m.enabled);

  return (
    <AppLayout title={`پلن مدرسه — ${school.name}`}>
      <div className="page-stack">

        {/* Header */}
        <section className="section-header">
          <div>
            <h2><i className="bi bi-sliders" /> پیکربندی پلن مدرسه «{school.name}»</h2>
            <p>
              کد: <strong>{school.code}</strong>
              {school.schoolType && (
                <> — مقطع: <span className="badge badge-primary" style={{ marginRight: 4 }}>{SCHOOL_TYPE_LABELS[school.schoolType] ?? school.schoolType}</span></>
              )}
            </p>
          </div>
          <a className="btn btn-ghost" href="/super-admin/schools"><i className="bi bi-arrow-right" /> بازگشت</a>
        </section>

        {/* Grade Levels Section */}
        <section className="panel-card">
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: '1rem' }}>
            <i className="bi bi-mortarboard-fill" style={{ fontSize: '1.25rem', color: 'var(--color-primary)' }} />
            <div>
              <h2 style={{ margin: 0 }}>پایه‌های تحصیلی مجاز</h2>
              <p style={{ margin: 0, color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
                پایه‌هایی که این مدرسه اجازه استفاده دارد. مدیر مدرسه نمی‌تواند خارج از این محدوده کلاس بسازد.
              </p>
            </div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.6rem' }}>
            {grades.map((grade) => (
              <button
                key={grade.id}
                type="button"
                onClick={() => handleGradeToggle(grade)}
                style={{
                  padding: '0.45rem 1rem',
                  borderRadius: 8,
                  border: `2px solid ${grade.enabled ? 'var(--color-primary)' : 'var(--color-border)'}`,
                  background: grade.enabled ? 'var(--color-primary)' : 'var(--color-surface)',
                  color: grade.enabled ? '#fff' : 'var(--color-text-muted)',
                  fontWeight: 700,
                  fontSize: '0.875rem',
                  cursor: 'pointer',
                  transition: 'all .15s',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 6,
                }}
              >
                <i className={grade.enabled ? 'bi bi-check-circle-fill' : 'bi bi-circle'} />
                {grade.label}
              </button>
            ))}
          </div>
          <p style={{ marginTop: '0.75rem', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
            <i className="bi bi-info-circle" /> {grades.filter((g) => g.enabled).length} از {grades.length} پایه فعال
          </p>
        </section>

        {/* Modules Section - Discord-like cards */}
        <section className="panel-card">
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: '1.25rem' }}>
            <i className="bi bi-grid-3x3-gap-fill" style={{ fontSize: '1.25rem', color: 'var(--color-primary)' }} />
            <div>
              <h2 style={{ margin: 0 }}>ماژول‌ها و قابلیت‌ها</h2>
              <p style={{ margin: 0, color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
                {enabledModules.length} فعال — {disabledModules.length} غیرفعال
              </p>
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
            gap: '0.75rem',
          }}>
            {modules.map((module) => (
              <div
                key={module.id}
                style={{
                  borderRadius: 10,
                  border: `2px solid ${module.enabled ? 'var(--color-primary)' : 'var(--color-border)'}`,
                  background: module.enabled
                    ? 'var(--color-bg-soft)'
                    : 'var(--color-surface)',
                  padding: '0.9rem 1rem',
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 8,
                  transition: 'border-color .15s, background .15s',
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 8,
                      background: module.enabled ? 'var(--color-primary)' : 'var(--color-border)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: module.enabled ? '#fff' : 'var(--color-text-muted)',
                      fontSize: '1rem',
                      flexShrink: 0,
                    }}>
                      <i className={`bi ${getModuleIcon(module.key)}`} />
                    </div>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: '0.875rem' }}>{module.label}</div>
                      <code style={{ fontSize: '0.7rem', color: 'var(--color-text-muted)' }}>{module.key}</code>
                    </div>
                  </div>

                  {/* Toggle switch */}
                  <button
                    type="button"
                    onClick={() => handleModuleToggle(module)}
                    aria-label={module.enabled ? 'غیرفعال کردن' : 'فعال کردن'}
                    style={{
                      width: 44, height: 24,
                      borderRadius: 12,
                      background: module.enabled ? 'var(--color-primary)' : 'var(--color-border)',
                      border: 'none',
                      cursor: 'pointer',
                      position: 'relative',
                      flexShrink: 0,
                      transition: 'background .2s',
                    }}
                  >
                    <span style={{
                      position: 'absolute',
                      top: 2,
                      left: module.enabled ? 22 : 2,
                      width: 20, height: 20,
                      borderRadius: '50%',
                      background: '#fff',
                      transition: 'left .2s',
                      boxShadow: '0 1px 3px rgba(0,0,0,.2)',
                    }} />
                  </button>
                </div>

                {module.description && (
                  <p style={{ margin: 0, fontSize: '0.78rem', color: 'var(--color-text-muted)', lineHeight: 1.4 }}>
                    {module.description}
                  </p>
                )}

                <div>
                  <span
                    className={`badge ${module.enabled ? 'badge-success' : 'badge-muted'}`}
                    style={{ fontSize: '0.7rem' }}
                  >
                    {module.enabled ? 'فعال' : 'غیرفعال'}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </section>

      </div>
    </AppLayout>
  );
}
