import React, { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { AUDIT_SCHEDULES_URL } from '../../../utils/config';
import './styles/AuditScheduling.css';

const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/** Normalize API date (string or Date) to YYYY-MM-DD so comparisons work. */
function toYYYYMMDD(val) {
  if (val == null) return '';
  if (typeof val === 'string') return val.slice(0, 10);
  if (typeof val === 'object' && typeof val.getFullYear === 'function') {
    const y = val.getFullYear();
    const m = String(val.getMonth() + 1).padStart(2, '0');
    const d = String(val.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
  return '';
}

/**
 * Returns true if the schedule has an occurrence on the given date (YYYY-MM-DD).
 */
function scheduleOccursOnDate(schedule, dateStr) {
  const d = new Date(dateStr + 'T12:00:00');
  const scheduledDateStr = toYYYYMMDD(schedule.scheduled_date);
  const scheduled = new Date(scheduledDateStr + 'T12:00:00');
  if (isNaN(d.getTime()) || isNaN(scheduled.getTime())) return false;

  if (schedule.recurrence_type === 'once') {
    return scheduledDateStr === dateStr;
  }
  if (schedule.recurrence_type === 'weekly') {
    const dayOfWeek = schedule.recurrence_day_of_week != null
      ? Number(schedule.recurrence_day_of_week)
      : scheduled.getDay();
    return d.getDay() === dayOfWeek && d >= scheduled;
  }
  if (schedule.recurrence_type === 'monthly') {
    const dayOfMonth = schedule.recurrence_day_of_month != null
      ? Number(schedule.recurrence_day_of_month)
      : scheduled.getDate();
    const last = new Date(d.getFullYear(), d.getMonth() + 1, 0);
    return d.getDate() === dayOfMonth && dayOfMonth <= last.getDate() && d >= scheduled;
  }
  return false;
}

function AuditScheduleDateDetail() {
  const { dateStr } = useParams();
  const navigate = useNavigate();
  const [schedules, setSchedules] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const schedulesOnDate = useMemo(() => {
    if (!dateStr) return [];
    return schedules.filter((s) => scheduleOccursOnDate(s, dateStr));
  }, [schedules, dateStr]);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await axiosInstance.get(AUDIT_SCHEDULES_URL);
        const raw = res.data?.data;
        if (!cancelled) setSchedules(Array.isArray(raw) ? raw : []);
      } catch (err) {
        if (!cancelled) setError(err.response?.data?.message || 'Failed to load schedules');
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    load();
    return () => { cancelled = true; };
  }, []);

  const displayDate = dateStr
    ? new Date(dateStr + 'T12:00:00').toLocaleDateString(undefined, {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      })
    : '';

  if (loading) {
    return (
      <div className="audit-scheduling-page">
        <div className="audit-scheduling-loading">Loading…</div>
      </div>
    );
  }

  return (
    <div className="audit-scheduling-page">
      <div className="audit-scheduling-header">
        <button
          type="button"
          className="audit-scheduling-back"
          onClick={() => navigate('/audit-schedule')}
        >
          ← Back to calendar
        </button>
        <h1>Scheduled audits on {displayDate}</h1>
        <p className="audit-scheduling-subtitle">
          Audit details, who created each schedule, who is assigned, and related information.
        </p>
      </div>

      {error && (
        <div className="audit-scheduling-error" role="alert">
          {error}
        </div>
      )}

      <div className="audit-scheduling-list-section audit-scheduling-date-detail-list">
        {schedulesOnDate.length === 0 ? (
          <p className="audit-scheduling-empty">
            No audits scheduled for this date.
          </p>
        ) : (
          <ul className="audit-scheduling-list audit-scheduling-detail-cards" role="list">
            {schedulesOnDate.map((s, index) => (
              <li key={s.id != null ? `schedule-${s.id}-${index}` : `schedule-idx-${index}`} className="audit-scheduling-detail-card">
                <h3 className="audit-scheduling-detail-card-title">{s.audit_name}</h3>
                <dl className="audit-scheduling-detail-card-dl">
                  <div className="audit-scheduling-detail-row">
                    <dt>Created by</dt>
                    <dd>{s.created_by_name || '—'}</dd>
                  </div>
                  <div className="audit-scheduling-detail-row">
                    <dt>Assigned to</dt>
                    <dd>
                      <span className="audit-scheduling-detail-name">{s.assigned_to_name || '—'}</span>
                      {s.assigned_to_email && (
                        <span className="audit-scheduling-detail-email"> ({s.assigned_to_email})</span>
                      )}
                    </dd>
                  </div>
                  <div className="audit-scheduling-detail-row">
                    <dt>First scheduled date</dt>
                    <dd>{toYYYYMMDD(s.scheduled_date) ? new Date(toYYYYMMDD(s.scheduled_date) + 'T12:00:00').toLocaleDateString() : '—'}</dd>
                  </div>
                  <div className="audit-scheduling-detail-row">
                    <dt>Recurrence</dt>
                    <dd>
                      {s.recurrence_type === 'once' && 'One-time'}
                      {s.recurrence_type === 'weekly' && `Weekly on ${WEEKDAYS[Number(s.recurrence_day_of_week)] || '?'}`}
                      {s.recurrence_type === 'monthly' && `Monthly on day ${s.recurrence_day_of_month}`}
                    </dd>
                  </div>
                  <div className="audit-scheduling-detail-row">
                    <dt>Reminder</dt>
                    <dd>{s.reminder_days_before != null ? (s.reminder_days_before === 0 ? 'On the day of schedule' : `${s.reminder_days_before} day(s) before`) : '—'}</dd>
                  </div>
                  {s.assignment_mail_sent_at != null && (
                    <div className="audit-scheduling-detail-row">
                      <dt>Assignment email sent</dt>
                      <dd>{new Date(s.assignment_mail_sent_at).toLocaleString()}</dd>
                    </div>
                  )}
                  <div className="audit-scheduling-detail-row">
                    <dt>Schedule created</dt>
                    <dd>{s.created_at ? new Date(s.created_at).toLocaleString() : '—'}</dd>
                  </div>
                </dl>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}

export default AuditScheduleDateDetail;
