/**
 * AttendanceHistoryView.tsx
 *
 * Shared per-student attendance history view, used by both the teacher
 * and parent pages. Single page, 4 tabs (class / hostel / transport /
 * club). Student picker, date range, table, summary, and CSV export.
 *
 * `studentOptions` controls where the student list comes from — for
 * the teacher/admin page it's every student in the school, for the
 * parent page it's only their linked children (loaded via
 * /api/users/children, which is what parent/Attendance.tsx already uses).
 *
 * The "class" tab reuses /api/attendance (the existing class
 * attendance controller). The other three tabs use the new
 * /{hostel,transport,club}-attendance/history endpoints. All four
 * return the same shape: { student_id, summary, records } — except
 * /api/attendance returns the records list directly, so the view
 * derives the summary client-side for that tab.
 */

import { useEffect, useMemo, useState } from 'react';
import {
  History as HistoryIcon, Calendar, User, BookOpen, Home, Bus, Trophy,
  Search, Download, AlertCircle, CheckCircle2, XCircle, Clock,
  TrendingUp, ChevronDown, RefreshCw
} from 'lucide-react';
import api from '../store/api';
import { exportToCsv, CsvColumn } from '../utils/csv';
import {
  useAttendanceStore, AttendanceContext, AttendanceStatus, AttendanceRecord, AttendanceSummary,
} from '../store/attendance';

const STATUS_STYLES: Record<string, { label: string; bg: string; text: string; border: string }> = {
  present: { label: 'Present', bg: 'bg-emerald-500/10', text: 'text-emerald-600', border: 'border-emerald-500/30' },
  absent:  { label: 'Absent',  bg: 'bg-rose-500/10',    text: 'text-rose-600',    border: 'border-rose-500/30' },
  excused: { label: 'Excused', bg: 'bg-amber-500/10',   text: 'text-amber-600',   border: 'border-amber-500/30' },
  late:    { label: 'Late',    bg: 'bg-orange-500/10',  text: 'text-orange-600',  border: 'border-orange-500/30' },
  'half-day': { label: 'Half-day', bg: 'bg-blue-500/10',    text: 'text-blue-600',    border: 'border-blue-500/30' },
};

export interface StudentOption {
  id: number;
  first_name?: string;
  last_name?: string;
  full_name?: string;
  class_name?: string;
  role?: string;
}

interface Props {
  /** Source of student options — usually pre-loaded by the parent page */
  studentOptions: StudentOption[];
  /** If true, hides the student picker (parent page uses a single fixed child) */
  hideStudentPicker?: boolean;
  /** Optional default student id to load on mount */
  defaultStudentId?: number;
  /** Optional default tab (defaults to 'class') */
  defaultTab?: AttendanceContext;
  /** Restrict the available tabs to a subset (parent page keeps all 4) */
  tabs?: AttendanceContext[];
}

const TABS: { id: AttendanceContext; label: string; icon: any }[] = [
  { id: 'class', label: 'Class', icon: BookOpen },
  { id: 'hostel', label: 'Hostel', icon: Home },
  { id: 'transport', label: 'Transport', icon: Bus },
  { id: 'club', label: 'Extra-curricular', icon: Trophy },
  { id: 'staff', label: 'Staff', icon: User },
];

const todayIso = () => new Date().toISOString().split('T')[0];
const monthAgoIso = () => {
  const d = new Date();
  d.setDate(d.getDate() - 30);
  return d.toISOString().split('T')[0];
};

const emptySummary = (): AttendanceSummary => ({ total: 0, present: 0, absent: 0, excused: 0, late: 0, halfDay: 0 });

const buildSummary = (records: AttendanceRecord[]): AttendanceSummary => {
  const s = emptySummary();
  records.forEach(r => {
    s.total += 1;
    if (r.status === 'present') s.present += 1;
    else if (r.status === 'absent') s.absent += 1;
    else if (r.status === 'excused') s.excused += 1;
    else if (r.status === 'late') (s as any).late += 1;
    else if (r.status === 'half-day') (s as any).halfDay += 1;
  });
  return s;
};

export default function AttendanceHistoryView({
  studentOptions,
  hideStudentPicker,
  defaultStudentId,
  defaultTab = 'class',
  tabs = ['class', 'hostel', 'transport', 'club'],
}: Props) {
  const { fetchHistory, fetchList, loading, error } = useAttendanceStore();

  const [context, setContext] = useState<AttendanceContext>(defaultTab);
  const [studentId, setStudentId] = useState<number | null>(defaultStudentId ?? null);
  const [studentSearch, setStudentSearch] = useState('');
  const [studentPickerOpen, setStudentPickerOpen] = useState(false);
  const [from, setFrom] = useState(monthAgoIso());
  const [to, setTo] = useState(todayIso());
  const [records, setRecords] = useState<AttendanceRecord[]>([]);
  const [summary, setSummary] = useState<AttendanceSummary>(emptySummary());
  const [loadErr, setLoadErr] = useState<string | null>(null);

  const visibleTabs = useMemo(() => TABS.filter(t => tabs.includes(t.id)), [tabs]);

  const contextStudents = useMemo(() => {
    if (context === 'staff') {
      return studentOptions.filter(s => s.role && s.role !== 'student' && s.role !== 'parent');
    } else {
      const hasRolesDefined = studentOptions.some(s => s.role);
      if (hasRolesDefined) {
        return studentOptions.filter(s => s.role === 'student');
      }
      return studentOptions;
    }
  }, [studentOptions, context]);

  const filteredStudents = useMemo(() => {
    const q = studentSearch.toLowerCase().trim();
    if (!q) return contextStudents;
    return contextStudents.filter(s => {
      const name = s.full_name || `${s.first_name || ''} ${s.last_name || ''}`;
      return name.toLowerCase().includes(q) || (s.class_name || '').toLowerCase().includes(q);
    });
  }, [contextStudents, studentSearch]);

  const selectedStudent = useMemo(
    () => studentOptions.find(s => s.id === studentId) || null,
    [studentOptions, studentId]
  );

  // Initialise and adjust studentId from context-aware options when they change
  useEffect(() => {
    if (contextStudents.length > 0) {
      const isValid = contextStudents.some(s => s.id === studentId);
      if (!isValid) {
        setStudentId(contextStudents[0].id);
      }
    } else {
      setStudentId(null);
    }
  }, [contextStudents, studentId]);

  // Load history when filters change, and set up auto-refresh
  useEffect(() => {
    let cancelled = false;
    const load = async (isBackground = false) => {
      if (!studentId) {
        setRecords([]);
        setSummary(emptySummary());
        return;
      }
      if (!isBackground) setLoadErr(null);
      try {
        if (context === 'class') {
          // The class /api/attendance list endpoint returns a flat array
          const params: Record<string, string> = { student_id: String(studentId) };
          if (from) params.from = from;
          if (to) params.to = to;
          const list = await fetchList('class', params);
          if (!cancelled) {
            setRecords(list);
            setSummary(buildSummary(list));
          }
        } else {
          // For staff, context is 'staff' which maps to /staff-attendance
          const res = await fetchHistory(context, studentId, { from, to });
          if (!cancelled) {
            setRecords(res.records || []);
            setSummary(res.summary || buildSummary(res.records || []));
          }
        }
      } catch (err: any) {
        if (!cancelled && !isBackground) {
          setLoadErr(err?.message || 'Failed to load history');
          setRecords([]);
          setSummary(emptySummary());
        }
      }
    };
    
    // Initial load
    load();

    // Polling for real-time data
    const interval = setInterval(() => {
      load(true);
    }, 10000); // 10 seconds

    return () => { 
      cancelled = true; 
      clearInterval(interval);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [context, studentId, from, to]);

  const handleRefresh = async () => {
    if (!studentId) return;
    setLoadErr(null);
    try {
      if (context === 'class') {
        const params: Record<string, string> = { student_id: String(studentId) };
        if (from) params.from = from;
        if (to) params.to = to;
        const list = await fetchList('class', params);
        setRecords(list);
        setSummary(buildSummary(list));
      } else {
        const res = await fetchHistory(context, studentId, { from, to });
        setRecords(res.records || []);
        setSummary(res.summary || buildSummary(res.records || []));
      }
    } catch (err: any) {
      setLoadErr(err?.message || 'Failed to refresh history');
    }
  };

  const attendanceRate = summary.total > 0
    ? Math.round((summary.present / summary.total) * 100)
    : 0;

  const handleExport = () => {
    if (records.length === 0) return;
    const studentName = selectedStudent
      ? (selectedStudent.full_name || `${selectedStudent.first_name || ''} ${selectedStudent.last_name || ''}`.trim())
      : `student-${studentId}`;
    const cols: CsvColumn<AttendanceRecord>[] = [
      { key: 'date',   label: 'Date' },
      { key: 'status', label: 'Status', format: r => STATUS_STYLES[r.status]?.label || r.status },
      { key: 'context_label', label: 'Context' },
    ];
    const contextLabel = context === 'club' ? 'Extra-curricular' : context.charAt(0).toUpperCase() + context.slice(1);
    const decorated = records.map(r => ({ ...r, context_label: contextLabel }));
    const safeName = studentName.replace(/\s+/g, '-').toLowerCase();
    const fileContext = context === 'club' ? 'extra-curricular' : context;
    exportToCsv(`attendance-${safeName}-${fileContext}-${from}_to_${to}.csv`, decorated, cols);
  };

  return (
    <div className="p-8 space-y-8 animate-in fade-in duration-500">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight uppercase flex items-center gap-2.5">
            <HistoryIcon className="text-primary" size={28} />
            Attendance History
          </h1>
          <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-[2px] mt-0.5">
            Per-student and staff attendance records and analytics
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          {studentId && (
            <button
              onClick={handleRefresh}
              className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text hover:bg-muted rounded-xl font-bold text-xs uppercase tracking-wider transition-all"
            >
              <RefreshCw size={14} className={loading ? "animate-spin" : ""} /> Refresh
            </button>
          )}
          {records.length > 0 && (
            <button
              onClick={handleExport}
              className="flex items-center gap-2 px-5 py-2.5 bg-primary text-white hover:opacity-90 rounded-xl font-bold text-xs uppercase tracking-widest transition-all shadow-lg active:scale-95"
            >
              <Download size={14} /> Export CSV
            </button>
          )}
        </div>
      </div>

      {loadErr && (
        <div className="px-6 py-3.5 bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20 rounded-2xl text-sm font-semibold flex items-center gap-2.5 animate-in fade-in">
          <AlertCircle size={18} /> {loadErr}
        </div>
      )}
      {error && (
        <div className="px-6 py-3.5 bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20 rounded-2xl text-sm font-semibold flex items-center gap-2.5 animate-in fade-in">
          <AlertCircle size={18} /> {error}
        </div>
      )}

      {/* Main card */}
      <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
        <div className="flex flex-wrap items-center border-b border-border bg-muted/20 p-1">
          {visibleTabs.map(t => {
            const Icon = t.icon;
            const active = context === t.id;
            return (
              <button
                key={t.id}
                onClick={() => setContext(t.id)}
                className={`flex items-center gap-2.5 px-6 py-3 rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all ${
                  active
                    ? 'bg-card text-primary shadow-sm ring-1 ring-border'
                    : 'text-text-muted hover:text-text'
                }`}
              >
                <Icon size={14} />
                {t.label}
              </button>
            );
          })}
        </div>

        {/* Filter bar */}
        <div className="p-6 flex flex-wrap items-center gap-4 bg-muted/20 border-b border-border">
          {!hideStudentPicker && (
            <div className="relative min-w-[280px] flex-1">
              <label className="block text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1.5">
                {context === 'staff' ? 'Staff Member' : 'Student'}
              </label>
              <button
                onClick={() => setStudentPickerOpen(o => !o)}
                className={`w-full flex items-center justify-between gap-2 px-4 py-2.5 bg-background border rounded-xl text-sm font-semibold text-text transition-all duration-150 focus:outline-none focus:ring-4 focus:ring-primary/5 ${
                  studentPickerOpen ? 'border-primary ring-4 ring-primary/5 shadow-sm' : 'border-border'
                }`}
              >
                <span className="flex items-center gap-2.5">
                  <User size={16} className="text-text-muted" />
                  {selectedStudent
                    ? (selectedStudent.full_name || `${selectedStudent.first_name || ''} ${selectedStudent.last_name || ''}`.trim() || `${context === 'staff' ? 'Staff' : 'Student'} ${selectedStudent.id}`)
                    : `— select a ${context === 'staff' ? 'staff member' : 'student'} —`}
                </span>
                <ChevronDown size={14} className={`text-text-muted transition-transform duration-200 ${studentPickerOpen ? 'rotate-180' : ''}`} />
              </button>
              {studentPickerOpen && (
                <div className="absolute top-full mt-1 left-0 right-0 max-h-80 overflow-y-auto custom-scrollbar bg-card border border-border rounded-2xl shadow-2xl z-[120] p-2 animate-in fade-in zoom-in-95 duration-150">
                  <div className="p-1.5">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={14} />
                      <input
                        autoFocus
                        type="text"
                        value={studentSearch}
                        onChange={e => setStudentSearch(e.target.value)}
                        placeholder={`Search by name or ${context === 'staff' ? 'role' : 'class'}…`}
                        className="w-full pl-9 pr-4 py-2 bg-background border border-border rounded-xl text-xs font-semibold text-text focus:outline-none focus:border-primary focus:ring-4 focus:ring-primary/5 transition-all"
                      />
                    </div>
                  </div>
                  {filteredStudents.length === 0 ? (
                    <p className="px-3 py-2.5 text-xs text-text-muted font-bold italic">No records match.</p>
                  ) : (
                    filteredStudents.map(s => {
                      const name = s.full_name || `${s.first_name || ''} ${s.last_name || ''}`.trim() || `Student ${s.id}`;
                      const isSel = s.id === studentId;
                      return (
                        <button
                          key={s.id}
                          onClick={() => { setStudentId(s.id); setStudentPickerOpen(false); setStudentSearch(''); }}
                          className={`w-full flex items-center gap-2.5 p-2 rounded-xl text-left text-xs ${isSel ? 'bg-primary/10 text-primary font-bold' : 'hover:bg-background-alt text-text'}`}
                        >
                          <div className="w-8 h-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center font-black text-sm uppercase">
                            {name[0] || '?'}
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="font-bold truncate text-text">{name}</p>
                            {s.class_name ? (
                                <p className="text-[0.6rem] text-text-muted uppercase font-black tracking-wider">{s.class_name}</p>
                            ) : (
                                s.role && <p className="text-[0.6rem] text-text-muted uppercase font-black tracking-wider">{s.role.replace('_', ' ')}</p>
                            )}
                          </div>
                        </button>
                      );
                    })
                  )}
                </div>
              )}
            </div>
          )}
          <div className="flex items-center gap-2">
            <div className="flex flex-col">
              <label className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1.5">From Date</label>
              <input
                type="date"
                value={from}
                max={to}
                onChange={e => setFrom(e.target.value)}
                className="px-4 py-2.5 bg-background border border-border rounded-xl text-sm font-semibold text-text focus:outline-none focus:border-primary focus:ring-4 focus:ring-primary/5 transition-all"
              />
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="flex flex-col">
              <label className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-1.5">To Date</label>
              <input
                type="date"
                value={to}
                min={from}
                max={todayIso()}
                onChange={e => setTo(e.target.value)}
                className="px-4 py-2.5 bg-background border border-border rounded-xl text-sm font-semibold text-text focus:outline-none focus:border-primary focus:ring-4 focus:ring-primary/5 transition-all"
              />
            </div>
          </div>
        </div>

        {/* Summary tiles */}
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 p-6 border-b border-border bg-muted/10">
          <div className="p-4 bg-background rounded-2xl border border-border shadow-sm">
            <div className="flex items-center gap-2 text-[0.6rem] text-text-muted uppercase tracking-widest font-black">
              <TrendingUp size={12} className="text-primary" /> Attendance Rate
            </div>
            <p className="text-3xl font-black text-text mt-1.5">{attendanceRate}<span className="text-lg text-text-muted font-bold">%</span></p>
          </div>
          <div className="p-4 bg-emerald-500/5 rounded-2xl border border-emerald-500/20 shadow-sm">
            <div className="flex items-center gap-2 text-[0.6rem] text-emerald-600 dark:text-emerald-400 uppercase tracking-widest font-black">
              <CheckCircle2 size={12} /> Present
            </div>
            <p className="text-3xl font-black text-emerald-600 dark:text-emerald-400 mt-1.5">{summary.present}</p>
          </div>
          <div className="p-4 bg-rose-500/5 rounded-2xl border border-rose-500/20 shadow-sm">
            <div className="flex items-center gap-2 text-[0.6rem] text-rose-600 dark:text-rose-400 uppercase tracking-widest font-black">
              <XCircle size={12} /> Absent
            </div>
            <p className="text-3xl font-black text-rose-600 dark:text-rose-400 mt-1.5">{summary.absent}</p>
          </div>
          {context === 'staff' ? (
              <>
                <div className="p-4 bg-orange-500/5 rounded-2xl border border-orange-500/20 shadow-sm">
                    <div className="flex items-center gap-2 text-[0.6rem] text-orange-600 dark:text-orange-400 uppercase tracking-widest font-black">
                    <Clock size={12} /> Late
                    </div>
                    <p className="text-3xl font-black text-orange-600 dark:text-orange-400 mt-1.5">{summary.late}</p>
                </div>
                <div className="p-4 bg-blue-500/5 rounded-2xl border border-blue-500/20 shadow-sm">
                    <div className="flex items-center gap-2 text-[0.6rem] text-blue-600 dark:text-blue-400 uppercase tracking-widest font-black">
                    <Clock size={12} /> Half-day
                    </div>
                    <p className="text-3xl font-black text-blue-600 dark:text-blue-400 mt-1.5">{summary.halfDay}</p>
                </div>
              </>
          ) : (
            <div className="p-4 bg-amber-500/5 rounded-2xl border border-amber-500/20 shadow-sm">
                <div className="flex items-center gap-2 text-[0.6rem] text-amber-600 dark:text-amber-400 uppercase tracking-widest font-black">
                <Clock size={12} /> Excused
                </div>
                <p className="text-3xl font-black text-amber-600 dark:text-amber-400 mt-1.5">{summary.excused}</p>
            </div>
          )}
        </div>

        {/* Records table */}
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-muted/50 border-b border-border">
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest w-1/3">Date</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest w-1/4">Status</th>
                <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Detail</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {loading ? (
                <tr>
                  <td colSpan={3} className="px-8 py-16 text-center text-text-muted font-bold uppercase tracking-widest text-xs italic">
                    <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                    Loading history…
                  </td>
                </tr>
              ) : !studentId ? (
                <tr>
                  <td colSpan={3} className="px-8 py-16 text-center text-text-muted font-bold uppercase tracking-widest text-xs italic">
                    <User size={36} className="mx-auto mb-3 opacity-20 text-primary" />
                    Pick a student to view their attendance history.
                  </td>
                </tr>
              ) : records.length === 0 ? (
                <tr>
                  <td colSpan={3} className="px-8 py-16 text-center text-text-muted font-bold uppercase tracking-widest text-xs italic">
                    <Calendar size={36} className="mx-auto mb-3 opacity-20 text-primary" />
                    No attendance records in the selected date range.
                  </td>
                </tr>
              ) : (
                records.map(r => {
                  const styles = STATUS_STYLES[r.status] || STATUS_STYLES.present;
                  return (
                    <tr key={r.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-8 py-5 text-text font-bold text-sm">
                        {new Date(r.date).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}
                      </td>
                      <td className="px-8 py-5">
                        <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-[0.65rem] font-black uppercase ${styles.bg} ${styles.text} border ${styles.border}`}>
                          {styles.label}
                        </span>
                      </td>
                      <td className="px-8 py-5 text-xs text-text-muted font-semibold">
                        {r.hostel_name || r.route_name || r.club_name || r.subject || r.remarks || '—'}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
