import { Clock, Database, Shield, TrendingDown, TrendingUp } from 'lucide-react';

import { useStaffAttendanceRecords } from '@/business/staff-attendance/hooks';
import {
  buildStaffAttendanceRollups,
  countStaffAttendanceStatus,
  recentStaffAttendanceRecords,
} from '@/business/staff-attendance/selectors';
import { StatePanel } from '@/components/ui/state-panel';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { STAFF_ATTENDANCE_STATUS_COLORS } from '@/shared/constants/staffAttendance';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import type { UserRole } from '@/shared/types/app';

interface AttendanceModuleProps {
  readonly userRole: UserRole;
}

export function AttendanceModule({ userRole }: AttendanceModuleProps) {
  const isDirector = userRole === 'director';
  const recordsQuery = useStaffAttendanceRecords();
  const records = recordsQuery.data ?? [];
  const errorMessage = getOptionalErrorMessage(recordsQuery.error);
  const personalRecords = recentStaffAttendanceRecords(records, 8);
  const presentCount = countStaffAttendanceStatus(personalRecords, 'present');
  const lateCount = countStaffAttendanceStatus(personalRecords, 'late');
  const absentCount = countStaffAttendanceStatus(personalRecords, 'absent');
  const staffAttendance = buildStaffAttendanceRollups(records);

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-orange-400 to-orange-600 flex items-center justify-center"><Clock size={20} className="text-white" /></div>
          Attendance
        </h2>
        <p className="text-sm text-gray-500 mt-1">{isDirector ? 'Campus-level attendance dashboard with trends' : 'Your personal attendance snapshot'}</p>
      </div>
      <div className="bg-orange-50 rounded-2xl border border-orange-200 p-4 flex items-center gap-3">
        <Shield size={18} className="text-orange-600 flex-shrink-0" />
        <p className="text-sm text-orange-700">
          Attendance data synced securely via ADP integration.
          {records.length > 0 && <span className="ml-1 inline-flex items-center gap-1 text-emerald-600"><Database size={10} /> {records.length} records loaded</span>}
        </p>
      </div>
      {recordsQuery.isLoading ? (
        <StatePanel tone="orange" alignment="center" loading>
          Loading attendance records...
        </StatePanel>
      ) : errorMessage ? (
        <StatePanel tone="red" role="alert">{errorMessage}</StatePanel>
      ) : !isDirector ? (
        <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Recent Attendance</h3>
          <div className="space-y-2">
            {personalRecords.map((day) => (
              <div key={day.id} className="flex items-center justify-between p-3 rounded-xl bg-gray-50">
                <span className="text-sm text-gray-700 font-medium">{day.date}</span>
                <div className="flex items-center gap-2">
                  {day.note && <span className="text-[10px] text-gray-400">{day.note}</span>}
                  <span className={`px-2.5 py-1 rounded-lg text-xs font-semibold ${STAFF_ATTENDANCE_STATUS_COLORS[day.status]}`}>{day.status.charAt(0).toUpperCase() + day.status.slice(1)}</span>
                </div>
              </div>
            ))}
          </div>
          <div className="mt-4 pt-4 border-t border-gray-100 grid grid-cols-3 gap-3 text-center">
            <div className="bg-emerald-50 rounded-xl p-3"><p className="text-2xl font-bold text-emerald-600">{presentCount}</p><p className="text-[10px] text-gray-500">Present</p></div>
            <div className="bg-amber-50 rounded-xl p-3"><p className="text-2xl font-bold text-amber-600">{lateCount}</p><p className="text-[10px] text-gray-500">Late</p></div>
            <div className="bg-red-50 rounded-xl p-3"><p className="text-2xl font-bold text-red-600">{absentCount}</p><p className="text-[10px] text-gray-500">Absent</p></div>
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="grid grid-cols-4 gap-4">
            {[
              { label: 'Total Records', value: records.length.toString(), color: 'bg-blue-50 text-blue-600' },
              { label: 'Present', value: countStaffAttendanceStatus(records, 'present').toString(), color: 'bg-emerald-50 text-emerald-600' },
              { label: 'Late', value: countStaffAttendanceStatus(records, 'late').toString(), color: 'bg-amber-50 text-amber-600' },
              { label: 'Absent', value: countStaffAttendanceStatus(records, 'absent').toString(), color: 'bg-red-50 text-red-600' },
            ].map((stat) => (
              <div key={stat.label} className={`${stat.color} rounded-2xl p-4 text-center`}><p className="text-2xl font-bold">{stat.value}</p><p className="text-xs mt-1 opacity-70">{stat.label}</p></div>
            ))}
          </div>
          {staffAttendance.length > 0 && (
            <div className="bg-white rounded-2xl border border-violet-100 shadow-sm overflow-hidden">
              <div className="p-4 border-b border-gray-100"><h3 className="font-semibold text-gray-800">Staff Attendance</h3></div>
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-50 hover:bg-gray-50">
                    <TableHead className="h-auto p-3 text-left text-gray-500">Staff</TableHead>
                    <TableHead className="h-auto p-3 text-center text-gray-500">Present</TableHead>
                    <TableHead className="h-auto p-3 text-center text-gray-500">Late</TableHead>
                    <TableHead className="h-auto p-3 text-center text-gray-500">Absent</TableHead>
                    <TableHead className="h-auto p-3 text-center text-gray-500">Trend</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {staffAttendance.map((staff) => (
                    <TableRow key={staff.name} className="border-t border-gray-50 hover:bg-violet-50/30">
                      <TableCell className="p-3 font-medium text-gray-700">{staff.name}</TableCell>
                      <TableCell className="p-3 text-center"><span className="bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-lg text-xs font-semibold">{staff.present}</span></TableCell>
                      <TableCell className="p-3 text-center"><span className={`px-2 py-0.5 rounded-lg text-xs font-semibold ${staff.late > 2 ? 'bg-amber-100 text-amber-700' : 'bg-gray-100 text-gray-500'}`}>{staff.late}</span></TableCell>
                      <TableCell className="p-3 text-center"><span className={`px-2 py-0.5 rounded-lg text-xs font-semibold ${staff.absent > 2 ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-500'}`}>{staff.absent}</span></TableCell>
                      <TableCell className="p-3 text-center">{staff.trend === 'up' ? <TrendingUp size={16} className="text-emerald-500 mx-auto" /> : <TrendingDown size={16} className="text-red-500 mx-auto" />}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
