import { ArrowLeft, Calendar, UserCheck, Users } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { Link, useParams } from 'react-router-dom';
import { useShellOutletContext } from '@/app/shellOutletContext';
import { useCampusAttendancePage } from '@/business/campus-attendance/hooks';
import { formatAttendanceDate } from '@/business/campus-attendance/selectors';
import { useStaffAttendanceRecords } from '@/business/staff-attendance/hooks';
import { CampusAttendanceLoadingState } from '@/components/campus-attendance/CampusAttendanceStatus';
import { percentageTextClass } from '@/components/campus-attendance/styles';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useScopeContext } from '@/contexts/scope-context';
import { APP_ROUTE_PATHS } from '@/shared/constants/routes';
import { getScopeChildren } from '@/shared/api/scope';
import type { StaffAttendanceStatus } from '@/shared/types/staffAttendance';
import type { TenantLevel } from '@/shared/types/scope';

function formatRoleName(role: string | null): string {
  if (!role) {
    return 'Staff';
  }

  return role
    .split('_')
    .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)
    .join(' ');
}

function statusClass(status: StaffAttendanceStatus): string {
  if (status === 'present') {
    return 'bg-emerald-500/10 text-emerald-300';
  }

  if (status === 'late') {
    return 'bg-amber-500/10 text-amber-300';
  }

  return 'bg-red-500/10 text-red-300';
}

export default function CampusAttendanceDetailsPage() {
  const { level, tenantId } = useParams<{ level: TenantLevel; tenantId: string }>();
  const { selectedTenant } = useScopeContext();
  const shell = useShellOutletContext();
  const attendancePage = useCampusAttendancePage({
    userRole: shell.userRole,
    userCampus: shell.userCampus,
    userName: shell.userName,
  });
  const { state } = attendancePage;
  const staffRecordsQuery = useStaffAttendanceRecords(
    { limit: 500 },
    state.roleAccess.canReadStaffReports,
  );
  const childCampusesQuery = useQuery({
    queryKey: ['attendance-details-child-campuses', level, tenantId],
    enabled: level === 'school' && Boolean(tenantId),
    queryFn: () => getScopeChildren('school', tenantId ?? '', { limit: 500 }),
  });

  if (state.loading || childCampusesQuery.isLoading) {
    return <CampusAttendanceLoadingState />;
  }

  const selectedChild = state.attendanceChildStats.find((child) => child.level === level && child.id === tenantId);
  const selectedCampus = level === 'campus'
    ? state.scopedCampusOptions.find((campus) => campus.tenantId === tenantId || campus.id === tenantId)
      ?? state.campusStats.find((campus) => campus.tenantId === tenantId || campus.id === tenantId)
    : null;
  const schoolCampusTenantIds = new Set(
    (childCampusesQuery.data?.rows ?? [])
      .filter((child) => child.level === 'campus')
      .map((child) => child.id),
  );
  const selectedCampusIds = level === 'school'
    ? new Set(state.scopedCampusOptions
        .filter((campus) => campus.tenantId ? schoolCampusTenantIds.has(campus.tenantId) : false)
        .map((campus) => campus.id))
    : new Set([selectedCampus?.id].filter((id): id is string => Boolean(id)));
  const selectedStaffCampusIds = level === 'school'
    ? new Set([
        ...selectedCampusIds,
        ...schoolCampusTenantIds,
      ])
    : new Set([
        selectedCampus?.id,
        selectedCampus?.tenantId,
      ].filter((id): id is string => Boolean(id)));
  const studentRecords = state.attendanceData.filter((record) => selectedCampusIds.has(record.campus_id));
  const staffRecords = (staffRecordsQuery.data ?? []).filter((record) => (
    record.campusId ? selectedStaffCampusIds.has(record.campusId) : false
  ));
  const displayName = selectedChild?.fullName ?? selectedCampus?.fullName ?? 'Attendance';
  const displayGradient = selectedChild?.bgGradient ?? selectedCampus?.bgGradient ?? 'from-slate-600 to-slate-500';
  const displayInitial = (selectedChild?.mascot ?? selectedCampus?.mascot ?? displayName).charAt(0);
  const scopeRouteState = { __scope: selectedTenant };

  if (!selectedChild && !selectedCampus) {
    return (
      <div className="space-y-6">
        <Link
          to={APP_ROUTE_PATHS.attendance}
          state={scopeRouteState}
          className="inline-flex items-center gap-2 text-sm font-medium text-slate-300 hover:text-white"
        >
          <ArrowLeft size={16} />
          Back to Attendance
        </Link>
        <div className="rounded-2xl border border-slate-700/40 bg-slate-800/60 p-10 text-center">
          <Users size={40} className="mx-auto mb-3 text-slate-600" />
          <p className="text-sm text-slate-400">Attendance details are not available for this child scope.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <Link
            to={APP_ROUTE_PATHS.attendance}
            state={scopeRouteState}
            className="inline-flex items-center gap-2 text-sm font-medium text-slate-300 hover:text-white"
          >
            <ArrowLeft size={16} />
            Back to Attendance
          </Link>
          <div className="mt-4 flex items-start gap-3">
            <div className={`flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br ${displayGradient}`}>
              <span className="text-lg font-bold text-white">{displayInitial}</span>
            </div>
            <div>
              <h2 className="text-2xl font-bold text-white">{displayName} Attendance Details</h2>
              <p className="mt-1 text-sm text-slate-400">
                Separate student and staff attendance records for this child scope.
              </p>
            </div>
          </div>
        </div>
      </div>

      <section className="rounded-2xl border border-slate-700/40 bg-slate-800/60">
        <div className="border-b border-slate-700/40 p-5">
          <h3 className="flex items-center gap-2 font-semibold text-white">
            <Users size={18} className="text-orange-400" />
            Student Attendance
          </h3>
        </div>
        {studentRecords.length > 0 ? (
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-700/30 hover:bg-slate-700/30">
                <TableHead className="h-auto p-3 text-xs text-slate-400">Date</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Enrolled</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</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Attendance %</TableHead>
                <TableHead className="h-auto p-3 text-xs text-slate-400">Notes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {studentRecords.map((record) => (
                <TableRow key={record.id} className="border-t border-slate-700/20 hover:bg-slate-700/20">
                  <TableCell className="p-3 font-medium text-slate-300">{formatAttendanceDate(record.date)}</TableCell>
                  <TableCell className="p-3 text-center text-slate-300">{record.total_enrolled}</TableCell>
                  <TableCell className="p-3 text-center text-emerald-300">{record.total_present}</TableCell>
                  <TableCell className="p-3 text-center text-red-300">{record.total_absent}</TableCell>
                  <TableCell className="p-3 text-center text-amber-300">{record.total_tardy}</TableCell>
                  <TableCell className={`p-3 text-center font-bold ${percentageTextClass(record.attendance_percentage)}`}>
                    {record.attendance_percentage.toFixed(1)}%
                  </TableCell>
                  <TableCell className="max-w-[260px] truncate p-3 text-xs text-slate-500">
                    {record.notes || '-'}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        ) : (
          <div className="p-10 text-center">
            <Calendar size={40} className="mx-auto mb-3 text-slate-600" />
            <p className="text-sm text-slate-400">No student attendance records are saved for this child scope.</p>
          </div>
        )}
      </section>

      <section className="rounded-2xl border border-slate-700/40 bg-slate-800/60">
        <div className="border-b border-slate-700/40 p-5">
          <h3 className="flex items-center gap-2 font-semibold text-white">
            <UserCheck size={18} className="text-sky-400" />
            Staff Attendance
          </h3>
        </div>
        {staffRecordsQuery.isLoading ? (
          <div className="p-6 text-sm text-slate-400">Loading staff attendance...</div>
        ) : staffRecords.length > 0 ? (
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-700/30 hover:bg-slate-700/30">
                <TableHead className="h-auto p-3 text-xs text-slate-400">Date</TableHead>
                <TableHead className="h-auto p-3 text-xs text-slate-400">Name</TableHead>
                <TableHead className="h-auto p-3 text-xs text-slate-400">Role</TableHead>
                <TableHead className="h-auto p-3 text-center text-xs text-slate-400">Status</TableHead>
                <TableHead className="h-auto p-3 text-xs text-slate-400">Notes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {staffRecords.map((record) => (
                <TableRow key={record.id} className="border-t border-slate-700/20 hover:bg-slate-700/20">
                  <TableCell className="p-3 font-medium text-slate-300">{formatAttendanceDate(record.date)}</TableCell>
                  <TableCell className="p-3 font-medium text-slate-100">{record.userName}</TableCell>
                  <TableCell className="p-3 text-slate-400">{formatRoleName(record.userRole)}</TableCell>
                  <TableCell className="p-3 text-center">
                    <span className={`rounded-lg px-2 py-0.5 text-xs font-semibold capitalize ${statusClass(record.status)}`}>
                      {record.status}
                    </span>
                  </TableCell>
                  <TableCell className="max-w-[260px] truncate p-3 text-xs text-slate-500">
                    {record.note || '-'}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        ) : (
          <div className="p-10 text-center">
            <UserCheck size={40} className="mx-auto mb-3 text-slate-600" />
            <p className="text-sm text-slate-400">No staff attendance records are saved for this child scope.</p>
          </div>
        )}
      </section>
    </div>
  );
}
