import { BarChart3, Calendar, ClipboardList, ExternalLink, FileText, Globe, Link2, Users } from 'lucide-react';

import {
  buildCombinedAttendanceHistoryRows,
  formatAttendanceDate,
} from '@/business/campus-attendance/selectors';
import { AttendanceSummaryCard } from '@/components/campus-attendance/AttendanceSummaryCard';
import { percentageTextClass } from '@/components/campus-attendance/styles';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type {
  CampusAttendancePageActions,
  CampusAttendancePageState,
} from '@/components/campus-attendance/types';

type IndividualCampusAttendanceViewProps = {
  state: CampusAttendancePageState;
  actions: CampusAttendancePageActions;
};

export function IndividualCampusAttendanceView({ state, actions }: IndividualCampusAttendanceViewProps) {
  const {
    today,
    weekStart,
    weekEnd,
    myWeekAvg,
    myCampusData,
    myStaffData,
    myCampusConfig,
    roleAccess,
    campusInfo,
    scopeModel,
  } = state;
  const todayRecord = myCampusData.find((record) => record.date === today);
  const todayStaffRecord = myStaffData.find((record) => record.date === today);
  const historyTitle = campusInfo?.fullName || scopeModel.tenantName || 'Current Campus';
  const combinedHistoryRows = buildCombinedAttendanceHistoryRows(myCampusData, myStaffData);
  const todayStudentTotal = todayRecord?.total_enrolled ?? 0;
  const todayStaffTotal = todayStaffRecord?.total_staff ?? 0;
  const todayStudentPresent = todayRecord?.total_present ?? 0;
  const todayStaffPresent = todayStaffRecord?.total_present ?? 0;
  const combinedTodayTotal = todayStudentTotal + todayStaffTotal;
  const combinedTodayPresent = todayStudentPresent + todayStaffPresent;
  const combinedTodayPct = combinedTodayTotal > 0
    ? Number(((combinedTodayPresent / combinedTodayTotal) * 100).toFixed(2))
    : null;
  const weekStudentDates = new Set(myCampusData.map((record) => record.date));
  const weekStaffDates = new Set(myStaffData.map((record) => record.date));
  const weekDates = Array.from(new Set([...weekStudentDates, ...weekStaffDates]))
    .filter((date) => date >= weekStart && date <= weekEnd);
  const combinedWeekPct = weekDates.length > 0
    ? Number((weekDates.reduce((sum, date) => {
        const studentRecord = myCampusData.find((record) => record.date === date) ?? null;
        const staffRecord = myStaffData.find((record) => record.date === date) ?? null;
        const total = (studentRecord?.total_enrolled ?? 0) + (staffRecord?.total_staff ?? 0);
        const present = (studentRecord?.total_present ?? 0) + (staffRecord?.total_present ?? 0);
        return sum + (total > 0 ? (present / total) * 100 : 0);
      }, 0) / weekDates.length).toFixed(2))
    : null;
  const studentTodayLabel = todayRecord ? `${todayRecord.total_present}/${todayRecord.total_enrolled} students` : 'No student data';
  const staffTodayLabel = todayStaffRecord ? `${todayStaffRecord.total_present}/${todayStaffRecord.total_staff} staff` : 'No staff data';
  const weekStudentLabel = myWeekAvg !== null ? `Students ${myWeekAvg}%` : 'Students N/A';
  const weekStaffRecords = myStaffData.filter((record) => record.date >= weekStart && record.date <= weekEnd);
  const weekStaffAvg = weekStaffRecords.length > 0
    ? Number((weekStaffRecords.reduce((sum, record) => sum + record.attendance_percentage, 0) / weekStaffRecords.length).toFixed(2))
    : null;
  const weekStaffLabel = weekStaffAvg !== null ? `Staff ${weekStaffAvg}%` : 'Staff N/A';

  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <AttendanceSummaryCard
          label="Today's Attendance"
          value={combinedTodayPct !== null ? `${combinedTodayPct}%` : 'N/A'}
          helper={`${studentTodayLabel} · ${staffTodayLabel}`}
          icon={Calendar}
          percentage={combinedTodayPct}
        />
        <AttendanceSummaryCard
          label="Weekly Average"
          value={combinedWeekPct !== null ? `${combinedWeekPct}%` : 'N/A'}
          helper={`${weekStudentLabel} · ${weekStaffLabel}`}
          icon={BarChart3}
          percentage={combinedWeekPct}
        />
        <AttendanceSummaryCard
          label="People"
          value={combinedTodayTotal || 'N/A'}
          helper={`${todayStudentTotal} students · ${todayStaffTotal} staff`}
          icon={Users}
          color="blue"
        />
      </div>

      {myCampusConfig?.attendance_link && !roleAccess.isOfficeManager && (
        <div className="bg-slate-800/60 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-5">
          <h3 className="font-semibold text-white flex items-center gap-2 mb-3">
            <Link2 size={16} className="text-orange-400" />
            Campus Attendance System
          </h3>
          <a
            href={myCampusConfig.attendance_link}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-2 px-4 py-3 bg-orange-500/10 border border-orange-500/20 rounded-xl text-sm text-orange-400 hover:bg-orange-500/20 transition-all"
          >
            <Globe size={16} />
            <span className="truncate">{myCampusConfig.attendance_link}</span>
            <ExternalLink size={14} className="ml-auto flex-shrink-0" />
          </a>
        </div>
      )}

      <div className="bg-slate-800/60 backdrop-blur-sm rounded-2xl border border-slate-700/40 overflow-hidden">
        <div className="p-5 border-b border-slate-700/40">
          <h3 className="font-semibold text-white flex items-center gap-2">
            <FileText size={16} className="text-slate-400" />
            Recent Attendance History - {historyTitle}
          </h3>
        </div>
        {combinedHistoryRows.length > 0 ? (
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-700/30 hover:bg-slate-700/30">
                <TableHead className="h-auto p-3 text-left text-xs text-slate-400">Date</TableHead>
                <TableHead className="h-auto p-3 text-left text-xs text-slate-400">Group</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Total</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Present</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Absent</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Tardy / Late</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Attendance %</TableHead>
                <TableHead className="h-auto p-3 text-left text-xs text-slate-400">Notes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {combinedHistoryRows
                .filter((record) => record.date === today || record.group === 'total')
                .slice(0, 45)
                .map((record) => {
                  const shouldShowDate = record.date !== today || record.group === 'students';

                  return (
                    <TableRow
                      key={record.id}
                      className={`border-t border-slate-700/20 hover:bg-slate-700/20 ${
                        record.group === 'total' ? 'bg-slate-900/30' : ''
                      }`}
                    >
                      <TableCell className="p-3 text-slate-300 font-medium">
                        {shouldShowDate ? formatAttendanceDate(record.date) : ''}
                      </TableCell>
                      <TableCell className={`p-3 ${record.group === 'total' ? 'text-white font-semibold' : 'text-slate-300'}`}>
                        {record.label}
                      </TableCell>
                      <TableCell className="p-3 text-center text-slate-300">{record.total}</TableCell>
                      <TableCell className="p-3 text-center">
                        <span className="px-2 py-0.5 rounded-lg text-xs font-semibold bg-emerald-500/10 text-emerald-400">{record.present}</span>
                      </TableCell>
                      <TableCell className="p-3 text-center">
                        <span className={`px-2 py-0.5 rounded-lg text-xs font-semibold ${record.absent > 0 ? 'bg-red-500/10 text-red-400' : 'bg-slate-700/30 text-slate-400'}`}>{record.absent}</span>
                      </TableCell>
                      <TableCell className="p-3 text-center">
                        <span className={`px-2 py-0.5 rounded-lg text-xs font-semibold ${record.late > 0 ? 'bg-amber-500/10 text-amber-400' : 'bg-slate-700/30 text-slate-400'}`}>{record.late}</span>
                      </TableCell>
                      <TableCell className="p-3 text-center">
                        <span className={`font-bold ${percentageTextClass(record.attendancePercentage)}`}>
                          {record.attendancePercentage !== null ? `${record.attendancePercentage.toFixed(1)}%` : 'N/A'}
                        </span>
                      </TableCell>
                      <TableCell className="p-3 text-xs text-slate-500 max-w-[200px] truncate">{record.notes || '-'}</TableCell>
                    </TableRow>
                  );
                })}
            </TableBody>
          </Table>
        ) : (
          <div className="p-10 text-center">
            <ClipboardList size={40} className="text-slate-600 mx-auto mb-3" />
            <p className="text-slate-400 text-sm">{scopeModel.emptyHistoryMessage}</p>
            {roleAccess.canEnterData && (
              <button
                type="button"
                onClick={() => actions.setShowEntryForm(true)}
                className="mt-3 text-orange-400 hover:text-orange-300 text-sm font-medium transition-colors"
              >
                Enter today&apos;s attendance
              </button>
            )}
          </div>
        )}
      </div>
    </>
  );
}
