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

type AttendanceRecord = {
  id: number;
  date: string;
  dateJalali: string;
  status: string;
  type: string;
  classroom: string;
  note: string | null;
  excuseRequest: { status: string; reason: string | null; createdAt: string | null } | null;
};

type MonthGroup = {
  month: string;
  present: number;
  absent: number;
  late: number;
  excused: number;
  records: AttendanceRecord[];
};

type Summary = { present: number; absent: number; late: number; excused: number };

type Props = {
  records: AttendanceRecord[];
  summary: Summary;
  monthGroups: MonthGroup[];
};

const statusConfig: Record<string, { label: string; color: string; bg: string; icon: string }> = {
  present: { label: 'حاضر', color: '#0EA678', bg: '#0EA67815', icon: 'bi-check-circle-fill' },
  absent: { label: 'غایب', color: '#ef4444', bg: '#ef444415', icon: 'bi-x-circle-fill' },
  late: { label: 'دیر', color: '#f59e0b', bg: '#f59e0b15', icon: 'bi-clock-fill' },
  excused: { label: 'موجه', color: '#6366f1', bg: '#6366f115', icon: 'bi-shield-check' },
};

const typeLabel: Record<string, string> = { in_person: 'حضوری', online: 'آنلاین' };

// Convert YYYY-MM to Persian month name roughly (just show year-month cleanly)
function monthLabel(ym: string): string {
  const [year, month] = ym.split('-').map(Number);
  const persianMonths = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
  // approximate Jalali month: Gregorian month 3–12 → Jalali month 1–12 (rough)
  // Just show Gregorian for reliability
  return `${year}/${String(month).padStart(2, '0')}`;
}

export default function StudentAttendance({ summary, monthGroups }: Props) {
  const [openMonths, setOpenMonths] = useState<Record<string, boolean>>({
    [monthGroups[0]?.month ?? '']: true,
  });
  const [view, setView] = useState<'monthly' | 'all'>('monthly');

  const total = Object.values(summary).reduce((a, b) => a + b, 0);
  const attendancePct = total > 0 ? Math.round((summary.present / total) * 100) : 100;

  function toggleMonth(m: string) {
    setOpenMonths((prev) => ({ ...prev, [m]: !prev[m] }));
  }

  const allRecords = monthGroups.flatMap((g) => g.records);

  return (
    <AppLayout title="حضور و غیاب">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-clipboard-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />حضور و غیاب</h2>
            <p>سابقه حضور و غیاب شما در {total} جلسه</p>
          </div>
        </section>

        {/* Summary stat cards */}
        <section className="dashboard-grid">
          {Object.entries(statusConfig).map(([key, cfg]) => (
            <article key={key} className="metric-card" style={{ borderColor: cfg.color + '40', background: cfg.bg }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', color: cfg.color }}>
                <i className={`bi ${cfg.icon}`} />{cfg.label}
              </span>
              <strong style={{ color: cfg.color }}>{summary[key as keyof Summary]}</strong>
            </article>
          ))}
        </section>

        {/* Attendance rate bar */}
        <section className="panel-card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
            <span style={{ fontWeight: 600 }}>درصد حضور</span>
            <strong style={{ color: attendancePct >= 80 ? '#0EA678' : attendancePct >= 60 ? '#f59e0b' : '#ef4444' }}>{attendancePct}٪</strong>
          </div>
          <div style={{ height: 10, background: 'var(--color-border)', borderRadius: 99, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${attendancePct}%`, background: attendancePct >= 80 ? '#0EA678' : attendancePct >= 60 ? '#f59e0b' : '#ef4444', borderRadius: 99, transition: 'width 0.5s' }} />
          </div>
        </section>

        {/* View toggle */}
        {monthGroups.length > 0 && (
          <div style={{ display: 'flex', gap: '0.4rem' }}>
            {(['monthly', 'all'] as const).map((v) => (
              <button
                key={v}
                type="button"
                onClick={() => setView(v)}
                style={{ padding: '0.3rem 0.85rem', borderRadius: 'var(--radius-sm)', border: '1px solid var(--color-border)', background: view === v ? 'var(--color-primary)' : 'var(--color-surface)', color: view === v ? 'white' : 'var(--color-text)', fontSize: '0.82rem', cursor: 'pointer', fontWeight: view === v ? 600 : 400 }}
              >
                {v === 'monthly' ? 'ماهانه' : 'همه'}
              </button>
            ))}
          </div>
        )}

        {monthGroups.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
              <div className="icon-badge" style={{ width: 56, height: 56, fontSize: '1.5rem', margin: '0 auto 1rem' }}><i className="bi bi-clipboard-check" /></div>
              <h2>سابقه‌ای ثبت نشده</h2>
              <p>هنوز هیچ جلسه حضور و غیابی برای شما ثبت نشده است.</p>
            </div>
          </section>
        ) : view === 'monthly' ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
            {monthGroups.map((mg) => (
              <div key={mg.month} className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
                {/* Month header */}
                <button
                  type="button"
                  onClick={() => toggleMonth(mg.month)}
                  style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0.75rem 1rem', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'right' }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <span style={{ fontWeight: 700, fontSize: '0.9rem' }}>{monthLabel(mg.month)}</span>
                    <MiniPill color="#ef4444" count={mg.absent} label="غیبت" />
                    <MiniPill color="#6366f1" count={mg.excused} label="موجه" />
                    <MiniPill color="#f59e0b" count={mg.late} label="تاخیر" />
                  </div>
                  <i className={`bi bi-chevron-${openMonths[mg.month] ? 'up' : 'down'}`} style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }} />
                </button>

                {openMonths[mg.month] && (
                  <div style={{ borderTop: '1px solid var(--color-border)', overflowX: 'auto' }}>
                    <RecordsTable records={mg.records} />
                  </div>
                )}
              </div>
            ))}
          </div>
        ) : (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ overflowX: 'auto' }}>
              <RecordsTable records={allRecords} />
            </div>
          </section>
        )}
      </div>
    </AppLayout>
  );
}

function MiniPill({ color, count, label }: { color: string; count: number; label: string }) {
  if (count === 0) return null;
  return (
    <span style={{ background: color + '18', color, border: `1px solid ${color}30`, borderRadius: 'var(--radius-sm)', padding: '0.1rem 0.45rem', fontSize: '0.72rem', fontWeight: 600 }}>
      {label}: {count}
    </span>
  );
}

function RecordsTable({ records }: { records: AttendanceRecord[] }) {
  const [openId, setOpenId] = useState<number | null>(null);
  const [reason, setReason] = useState('');

  function requestExcuse(recordId: number) {
    router.post(`/student/attendance/${recordId}/excuse-request`, { reason }, {
      preserveScroll: true,
      onSuccess: () => {
        setOpenId(null);
        setReason('');
      },
    });
  }

  return (
    <table className="data-table" style={{ width: '100%' }}>
      <thead>
        <tr>
          <th>تاریخ</th>
          <th>کلاس</th>
          <th>نوع</th>
          <th>وضعیت</th>
          <th>یادداشت</th>
          <th>درخواست موجه</th>
        </tr>
      </thead>
      <tbody>
        {records.map((r, i) => {
          const cfg = statusConfig[r.status] ?? { label: r.status, color: 'var(--color-text)', bg: 'transparent', icon: 'bi-dash' };
          const req = r.excuseRequest;
          const canRequest = r.status === 'absent' && req?.status !== 'pending' && req?.status !== 'approved';
          return (
            <tr key={r.id || i}>
              <td style={{ whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums', fontSize: '0.85rem' }}>{r.dateJalali}</td>
              <td>{r.classroom}</td>
              <td><span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>{typeLabel[r.type] ?? r.type}</span></td>
              <td>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.3rem', background: cfg.bg, color: cfg.color, border: `1px solid ${cfg.color}40`, borderRadius: 'var(--radius-sm)', padding: '0.15rem 0.5rem', fontSize: '0.8rem', fontWeight: 600 }}>
                  <i className={`bi ${cfg.icon}`} />{cfg.label}
                </span>
              </td>
              <td style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>{r.note ?? '—'}</td>
              <td style={{ minWidth: 220 }}>
                {req ? (
                  <span className={`badge ${req.status === 'approved' ? 'badge-success' : req.status === 'rejected' ? 'badge-danger' : 'badge-warning'}`}>
                    {req.status === 'approved' ? 'تایید شد' : req.status === 'rejected' ? 'رد شد' : 'در انتظار بررسی'}
                  </span>
                ) : canRequest ? (
                  <button className="btn btn-ghost btn-sm" type="button" onClick={() => setOpenId(openId === r.id ? null : r.id)}>
                    <i className="bi bi-shield-plus" /> درخواست
                  </button>
                ) : (
                  <span style={{ color: 'var(--color-text-soft)', fontSize: '0.8rem' }}>—</span>
                )}
                {openId === r.id && (
                  <div style={{ marginTop: '0.5rem', display: 'grid', gap: '0.4rem' }}>
                    <textarea
                      className="form-input"
                      rows={2}
                      value={reason}
                      onChange={(e) => setReason(e.target.value)}
                      placeholder="دلیل موجه بودن غیبت..."
                    />
                    <button className="btn btn-primary btn-sm" type="button" disabled={reason.trim().length < 3} onClick={() => requestExcuse(r.id)}>
                      ارسال درخواست
                    </button>
                  </div>
                )}
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
