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

const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const RECURRENCE_OPTIONS = [
  { value: 'once', label: 'One-time' },
  { value: 'weekly', label: 'Weekly' },
  { value: 'monthly', label: 'Monthly' }
];

/** Normalize API date (string or Date) to YYYY-MM-DD for consistent comparison. */
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 '';
}

function getDatesForScheduleInMonth(schedule, year, month) {
  const dates = [];
  const last = new Date(year, month + 1, 0);
  const scheduledDateStr = toYYYYMMDD(schedule.scheduled_date);
  const scheduled = new Date(scheduledDateStr + 'T12:00:00');
  if (isNaN(scheduled.getTime())) return dates;

  if (schedule.recurrence_type === 'once') {
    if (scheduled.getFullYear() === year && scheduled.getMonth() === month) {
      dates.push(scheduled.getDate());
    }
    return dates;
  }

  if (schedule.recurrence_type === 'weekly') {
    const dayOfWeek = schedule.recurrence_day_of_week != null ? Number(schedule.recurrence_day_of_week) : scheduled.getDay();
    for (let d = 1; d <= last.getDate(); d++) {
      const dte = new Date(year, month, d, 12, 0, 0);
      if (dte.getDay() === dayOfWeek && dte >= scheduled) dates.push(d);
    }
    return dates;
  }

  if (schedule.recurrence_type === 'monthly') {
    const dayOfMonth = schedule.recurrence_day_of_month != null ? Number(schedule.recurrence_day_of_month) : scheduled.getDate();
    const maxDay = last.getDate();
    if (dayOfMonth >= 1 && dayOfMonth <= maxDay) {
      const dte = new Date(year, month, dayOfMonth, 12, 0, 0);
      if (dte >= scheduled) dates.push(dayOfMonth);
    }
    return dates;
  }

  return dates;
}

function AuditScheduling() {
  const navigate = useNavigate();
  const currentUserId = getUserIdFromToken();
  const [schedules, setSchedules] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentMonth, setCurrentMonth] = useState(() => {
    const d = new Date();
    return { year: d.getFullYear(), month: d.getMonth() };
  });
  const [showForm, setShowForm] = useState(false);
  const [formData, setFormData] = useState({
    audit_name: '',
    assigned_to_user_id: currentUserId ? String(currentUserId) : '',
    scheduled_date: '',
    recurrence_type: 'once',
    recurrence_day_of_week: 3,
    recurrence_day_of_month: 5,
    reminder_days_before: 0
  });
  const [submitting, setSubmitting] = useState(false);
  const [sendingReminderId, setSendingReminderId] = useState(null);
  const [successMessage, setSuccessMessage] = useState(null);

  const fetchSchedules = async () => {
    try {
      const res = await axiosInstance.get(AUDIT_SCHEDULES_URL);
      setSchedules(res.data?.data || []);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load schedules');
    }
  };

  const fetchUsers = async () => {
    try {
      const res = await axiosInstance.get(USERS_URL);
      setUsers(res.data?.data || []);
    } catch (err) {
      console.warn('Failed to load users', err);
    }
  };

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      setError(null);
      await Promise.all([fetchSchedules(), fetchUsers()]);
      setLoading(false);
    };
    load();
  }, []);

  const calendarDays = useMemo(() => {
    const { year, month } = currentMonth;
    const first = new Date(year, month, 1);
    const last = new Date(year, month + 1, 0);
    const startPad = first.getDay();
    const daysInMonth = last.getDate();
    const days = [];
    for (let i = 0; i < startPad; i++) days.push({ day: null, date: null });
    for (let d = 1; d <= daysInMonth; d++) days.push({ day: d, date: new Date(year, month, d) });
    return days;
  }, [currentMonth]);

  const markedDates = useMemo(() => {
    const set = new Set();
    const { year, month } = currentMonth;
    schedules.forEach((s) => {
      getDatesForScheduleInMonth(s, year, month).forEach((d) => set.add(d));
    });
    return set;
  }, [schedules, currentMonth]);

  const prevMonth = () => {
    setCurrentMonth((m) => {
      if (m.month === 0) return { year: m.year - 1, month: 11 };
      return { year: m.year, month: m.month - 1 };
    });
  };

  const nextMonth = () => {
    setCurrentMonth((m) => {
      if (m.month === 11) return { year: m.year + 1, month: 0 };
      return { year: m.year, month: m.month + 1 };
    });
  };

  const monthLabel = `${new Date(currentMonth.year, currentMonth.month).toLocaleString('default', { month: 'long' })} ${currentMonth.year}`;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.audit_name || !formData.assigned_to_user_id || !formData.scheduled_date) {
      setError('Please fill audit name, assignee, and scheduled date.');
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      const payload = {
        audit_name: formData.audit_name,
        assigned_to_user_id: Number(formData.assigned_to_user_id),
        scheduled_date: formData.scheduled_date,
        recurrence_type: formData.recurrence_type,
        reminder_days_before: Number(formData.reminder_days_before) >= 0 ? Number(formData.reminder_days_before) : 0
      };
      if (formData.recurrence_type === 'weekly') {
        payload.recurrence_day_of_week = Number(formData.recurrence_day_of_week);
      }
      if (formData.recurrence_type === 'monthly') {
        payload.recurrence_day_of_month = Number(formData.recurrence_day_of_month);
      }
      await axiosInstance.post(AUDIT_SCHEDULES_URL, payload);
      await fetchSchedules();
      setFormData({ audit_name: '', assigned_to_user_id: currentUserId ? String(currentUserId) : '', scheduled_date: '', recurrence_type: 'once', recurrence_day_of_week: 3, recurrence_day_of_month: 5, reminder_days_before: 0 });
      setShowForm(false);
      setSuccessMessage('Schedule created successfully. The assignee will receive an email when SMTP is configured.');
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to create schedule');
    } finally {
      setSubmitting(false);
    }
  };

  const handleSendReminder = async (id) => {
    setSendingReminderId(id);
    try {
      const res = await axiosInstance.post(`${AUDIT_SCHEDULES_URL}/${id}/send-reminder`);
      setError(null);
      setSuccessMessage(res.data?.message || 'Reminder processed.');
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to send reminder');
    } finally {
      setSendingReminderId(null);
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this schedule?')) return;
    try {
      await axiosInstance.delete(`${AUDIT_SCHEDULES_URL}/${id}`);
      await fetchSchedules();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to delete');
    }
  };

  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">
        <h1>Audit Scheduling</h1>
        <p className="audit-scheduling-subtitle">Schedule audits and assign users. Assignment and reminder emails are sent when configured.</p>
        <button type="button" className="audit-scheduling-btn-primary" onClick={() => setShowForm(!showForm)}>
          {showForm ? 'Cancel' : 'Schedule an audit'}
        </button>
      </div>

      {successMessage && (
        <div className="audit-scheduling-success" role="status">
          {successMessage}
        </div>
      )}

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

      {showForm && (
        <form className="audit-scheduling-form" onSubmit={handleSubmit}>
          <h2>New scheduled audit</h2>
          <div className="audit-scheduling-form-row">
            <label>Audit name</label>
            <input
              type="text"
              value={formData.audit_name}
              onChange={(e) => setFormData((f) => ({ ...f, audit_name: e.target.value }))}
              placeholder="e.g. Weekly Safety Audit"
              required
            />
          </div>
          <div className="audit-scheduling-form-row">
            <label>Assign to</label>
            <select
              value={formData.assigned_to_user_id}
              onChange={(e) => setFormData((f) => ({ ...f, assigned_to_user_id: e.target.value }))}
              required
            >
              <option value="">Select user</option>
              {currentUserId && (
                <option value={currentUserId}>Myself ({getDisplayNameFromToken()})</option>
              )}
              {users
                .filter((u) => u.user_id !== currentUserId)
                .map((u) => (
                  <option key={u.user_id} value={u.user_id}>
                    {u.employee_name} ({u.email_id})
                  </option>
                ))}
            </select>
          </div>
          <div className="audit-scheduling-form-row">
            <label>Scheduled date (first occurrence)</label>
            <input
              type="date"
              value={formData.scheduled_date}
              onChange={(e) => setFormData((f) => ({ ...f, scheduled_date: e.target.value }))}
              required
            />
          </div>
          <div className="audit-scheduling-form-row">
            <label>Recurrence</label>
            <select
              value={formData.recurrence_type}
              onChange={(e) => setFormData((f) => ({ ...f, recurrence_type: e.target.value }))}
            >
              {RECURRENCE_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>{o.label}</option>
              ))}
            </select>
          </div>
          {formData.recurrence_type === 'weekly' && (
            <div className="audit-scheduling-form-row">
              <label>Day of week</label>
              <select
                value={formData.recurrence_day_of_week}
                onChange={(e) => setFormData((f) => ({ ...f, recurrence_day_of_week: Number(e.target.value) }))}
              >
                {WEEKDAYS.map((name, i) => (
                  <option key={i} value={i}>{name}</option>
                ))}
              </select>
            </div>
          )}
          {formData.recurrence_type === 'monthly' && (
            <div className="audit-scheduling-form-row">
              <label>Day of month (1–31)</label>
              <input
                type="number"
                min={1}
                max={31}
                value={formData.recurrence_day_of_month}
                onChange={(e) => setFormData((f) => ({ ...f, recurrence_day_of_month: Number(e.target.value) || 1 }))}
              />
            </div>
          )}
          <div className="audit-scheduling-form-row">
            <label>Reminder</label>
            <input
              type="number"
              min={0}
              value={formData.reminder_days_before}
              onChange={(e) => setFormData((f) => ({ ...f, reminder_days_before: Number(e.target.value) >= 0 ? Number(e.target.value) : 0 }))}
            />
            <span className="audit-scheduling-form-hint">0 = on the day of schedule, 1+ = days before</span>
          </div>
          <div className="audit-scheduling-form-actions">
            <button type="submit" className="audit-scheduling-btn-primary" disabled={submitting}>
              {submitting ? 'Saving…' : 'Create schedule'}
            </button>
          </div>
        </form>
      )}

      <div className="audit-scheduling-calendar-section">
        <h2>Calendar</h2>
        <div className="audit-scheduling-calendar-nav">
          <button type="button" onClick={prevMonth} aria-label="Previous month">&larr;</button>
          <span className="audit-scheduling-calendar-title">{monthLabel}</span>
          <button type="button" onClick={nextMonth} aria-label="Next month">&rarr;</button>
        </div>
        <div className="audit-scheduling-calendar">
          {WEEKDAYS.map((d) => (
            <div key={d} className="audit-scheduling-calendar-weekday">{d}</div>
          ))}
          {calendarDays.map((cell, i) => {
            const isScheduled = cell.day != null && markedDates.has(cell.day);
            const dateStr = cell.date
              ? `${currentMonth.year}-${String(currentMonth.month + 1).padStart(2, '0')}-${String(cell.day).padStart(2, '0')}`
              : null;
            return (
              <div
                key={i}
                role={isScheduled ? 'button' : undefined}
                tabIndex={isScheduled ? 0 : undefined}
                className={`audit-scheduling-calendar-day ${cell.day == null ? 'empty' : ''} ${isScheduled ? 'scheduled clickable' : ''}`}
                onClick={isScheduled ? () => navigate(`/audit-schedule/date/${dateStr}`) : undefined}
                onKeyDown={isScheduled ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); navigate(`/audit-schedule/date/${dateStr}`); } } : undefined}
              >
                {cell.day != null ? cell.day : ''}
              </div>
            );
          })}
        </div>
        <p className="audit-scheduling-legend">Dates with scheduled audits are highlighted.</p>
      </div>

      <div className="audit-scheduling-list-section">
        <h2>Scheduled audits</h2>
        {schedules.length === 0 ? (
          <p className="audit-scheduling-empty">No schedules yet. Create one above.</p>
        ) : (
          <ul className="audit-scheduling-list">
            {schedules.map((s) => (
              <li key={s.id} className="audit-scheduling-list-item">
                <div className="audit-scheduling-list-main">
                  <strong>{s.audit_name}</strong>
                  <span> → {s.assigned_to_name} ({s.assigned_to_email})</span>
                  <span className="audit-scheduling-recurrence">
                    {s.recurrence_type === 'once' && `One-time: ${s.scheduled_date}`}
                    {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}`}
                  </span>
                  <span> Reminder: {s.reminder_days_before === 0 ? 'On the day of schedule' : `${s.reminder_days_before} day(s) before`}</span>
                </div>
                <div className="audit-scheduling-list-actions">
                  <button
                    type="button"
                    className="audit-scheduling-btn-sm"
                    onClick={() => handleSendReminder(s.id)}
                    disabled={sendingReminderId === s.id}
                  >
                    {sendingReminderId === s.id ? 'Sending…' : 'Send reminder'}
                  </button>
                  <button type="button" className="audit-scheduling-btn-sm audit-scheduling-btn-danger" onClick={() => handleDelete(s.id)}>
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}

export default AuditScheduling;
