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

import { 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,
    myTodayPct,
    myWeekAvg,
    myCampusData,
    myCampusConfig,
    roleAccess,
    campusInfo,
  } = state;
  const todayRecord = myCampusData.find((record) => record.date === today);

  return (
    <>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <AttendanceSummaryCard
          label="Today's Attendance"
          value={myTodayPct !== null ? `${myTodayPct}%` : 'N/A'}
          helper={formatAttendanceDate(today)}
          icon={Calendar}
          percentage={myTodayPct}
        />
        <AttendanceSummaryCard
          label="Weekly Average"
          value={myWeekAvg !== null ? `${myWeekAvg}%` : 'N/A'}
          helper={`Week of ${formatAttendanceDate(weekStart)}`}
          icon={BarChart3}
          percentage={myWeekAvg}
        />
        {todayRecord && (
          <>
            <AttendanceSummaryCard
              label="Enrolled"
              value={todayRecord.total_enrolled}
              helper={`${todayRecord.total_present} present`}
              icon={Users}
              color="blue"
            />
            <AttendanceSummaryCard
              label="Absent Today"
              value={todayRecord.total_absent}
              helper={`${todayRecord.total_tardy} tardy`}
              icon={UserX}
              color="red"
            />
          </>
        )}
      </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 - {campusInfo?.fullName}
          </h3>
        </div>
        {myCampusData.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-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-left text-xs text-slate-400">Notes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
                {myCampusData.slice(0, 15).map((record) => (
                  <TableRow key={record.id} className="border-t border-slate-700/20 hover:bg-slate-700/20">
                    <TableCell className="p-3 text-slate-300 font-medium">{formatAttendanceDate(record.date)}</TableCell>
                    <TableCell className="p-3 text-center text-slate-300">{record.total_enrolled}</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.total_present}</span>
                    </TableCell>
                    <TableCell className="p-3 text-center">
                      <span className={`px-2 py-0.5 rounded-lg text-xs font-semibold ${record.total_absent > 3 ? 'bg-red-500/10 text-red-400' : 'bg-slate-700/30 text-slate-400'}`}>{record.total_absent}</span>
                    </TableCell>
                    <TableCell className="p-3 text-center">
                      <span className={`px-2 py-0.5 rounded-lg text-xs font-semibold ${record.total_tardy > 2 ? 'bg-amber-500/10 text-amber-400' : 'bg-slate-700/30 text-slate-400'}`}>{record.total_tardy}</span>
                    </TableCell>
                    <TableCell className="p-3 text-center">
                      <span className={`font-bold ${percentageTextClass(record.attendance_percentage)}`}>
                        {record.attendance_percentage.toFixed(1)}%
                      </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">No attendance data recorded yet for this campus.</p>
            {roleAccess.isOfficeManager && (
              <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>
    </>
  );
}
