import {
  BarChart3,
  Calendar,
  ChevronDown,
  ChevronUp,
  ExternalLink,
  Globe,
  Link2,
  UserCheck,
  Users,
} from 'lucide-react';

import { formatAttendanceDate } from '@/business/campus-attendance/selectors';
import { AttendanceSummaryCard } from '@/components/campus-attendance/AttendanceSummaryCard';
import {
  percentageBackgroundClass,
  percentageBorderClass,
  percentageTextClass,
} from '@/components/campus-attendance/styles';
import type {
  CampusAttendancePageActions,
  CampusAttendancePageState,
} from '@/components/campus-attendance/types';

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

export function SuperintendentAttendanceView({ state, actions }: SuperintendentAttendanceViewProps) {
  const { today, weekStart, overallStats, campusStats, expandedCampus } = state;

  return (
    <>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <AttendanceSummaryCard
          label="Today's Overall Attendance"
          value={overallStats.todayPct !== null ? `${overallStats.todayPct}%` : 'N/A'}
          helper={formatAttendanceDate(today)}
          icon={Calendar}
          percentage={overallStats.todayPct}
        />
        <AttendanceSummaryCard
          label="Weekly Average"
          value={overallStats.weekPct !== null ? `${overallStats.weekPct}%` : 'N/A'}
          helper={`Week of ${formatAttendanceDate(weekStart)}`}
          icon={BarChart3}
          percentage={overallStats.weekPct}
        />
        <AttendanceSummaryCard
          label="Total Enrolled Today"
          value={overallStats.todayEnrolled || 'N/A'}
          helper="Across all campuses"
          icon={Users}
          color="blue"
        />
        <AttendanceSummaryCard
          label="Present Today"
          value={overallStats.todayPresent || 'N/A'}
          helper="Across all campuses"
          icon={UserCheck}
          color="violet"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {campusStats.map((campus) => (
          <div key={campus.id} className="bg-slate-800/60 backdrop-blur-sm rounded-2xl border border-slate-700/40 overflow-hidden hover:border-slate-600/50 transition-all">
            <div className={`bg-gradient-to-r ${campus.bgGradient} p-4`}>
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-bold text-white text-lg">{campus.mascot}</h3>
                  <p className="text-white/70 text-xs">{campus.fullName}</p>
                </div>
                {campus.isOnline && (
                  <span className="px-2 py-0.5 bg-white/20 text-white text-[10px] rounded-full font-medium">Online</span>
                )}
              </div>
            </div>
            <div className="p-4 space-y-3">
              <div className="grid grid-cols-2 gap-3">
                <div className={`rounded-xl p-3 text-center ${percentageBackgroundClass(campus.todayPct)} border ${percentageBorderClass(campus.todayPct)}`}>
                  <p className="text-[10px] text-slate-400 mb-1">Today</p>
                  <p className={`text-xl font-bold ${percentageTextClass(campus.todayPct)}`}>
                    {campus.todayPct !== null ? `${campus.todayPct}%` : 'N/A'}
                  </p>
                </div>
                <div className={`rounded-xl p-3 text-center ${percentageBackgroundClass(campus.weekAvg)} border ${percentageBorderClass(campus.weekAvg)}`}>
                  <p className="text-[10px] text-slate-400 mb-1">Week Avg</p>
                  <p className={`text-xl font-bold ${percentageTextClass(campus.weekAvg)}`}>
                    {campus.weekAvg !== null ? `${campus.weekAvg}%` : 'N/A'}
                  </p>
                </div>
              </div>
              {campus.todayRecord && (
                <div className="grid grid-cols-3 gap-2 text-center">
                  <div className="bg-slate-700/30 rounded-lg p-2">
                    <p className="text-xs text-slate-400">Enrolled</p>
                    <p className="text-sm font-bold text-white">{campus.todayRecord.total_enrolled}</p>
                  </div>
                  <div className="bg-slate-700/30 rounded-lg p-2">
                    <p className="text-xs text-slate-400">Present</p>
                    <p className="text-sm font-bold text-emerald-400">{campus.todayRecord.total_present}</p>
                  </div>
                  <div className="bg-slate-700/30 rounded-lg p-2">
                    <p className="text-xs text-slate-400">Absent</p>
                    <p className="text-sm font-bold text-red-400">{campus.todayRecord.total_absent}</p>
                  </div>
                </div>
              )}
              {campus.config?.attendance_link ? (
                <a
                  href={campus.config.attendance_link}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-3 py-2 bg-slate-700/30 rounded-lg text-xs text-orange-400 hover:text-orange-300 hover:bg-slate-700/50 transition-all truncate"
                >
                  <Link2 size={12} className="flex-shrink-0" />
                  <span className="truncate">{campus.config.attendance_link}</span>
                  <ExternalLink size={10} className="flex-shrink-0 ml-auto" />
                </a>
              ) : (
                <div className="flex items-center gap-2 px-3 py-2 bg-slate-700/20 rounded-lg text-xs text-slate-500 italic">
                  <Link2 size={12} /> No link configured
                </div>
              )}
              <button
                type="button"
                onClick={() => actions.setExpandedCampus(expandedCampus === campus.id ? null : campus.id)}
                className="w-full flex items-center justify-center gap-1 text-xs text-slate-400 hover:text-white py-1 transition-colors"
              >
                {expandedCampus === campus.id ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
                {expandedCampus === campus.id ? 'Hide History' : 'View History'}
              </button>
              {expandedCampus === campus.id && campus.recentData.length > 0 && (
                <div className="space-y-1.5 max-h-48 overflow-y-auto">
                  {campus.recentData.map((record) => (
                    <div key={record.id} className="flex items-center justify-between px-3 py-2 bg-slate-700/20 rounded-lg text-xs">
                      <span className="text-slate-400">{formatAttendanceDate(record.date)}</span>
                      <div className="flex items-center gap-3">
                        <span className="text-slate-500">{record.total_present}/{record.total_enrolled}</span>
                        <span className={`font-bold ${percentageTextClass(record.attendance_percentage)}`}>
                          {record.attendance_percentage.toFixed(1)}%
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      <div className="bg-slate-800/60 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-6">
        <h3 className="font-semibold text-white flex items-center gap-2 mb-4">
          <Link2 size={18} className="text-orange-400" />
          Campus Attendance System Links
        </h3>
        <div className="space-y-2">
          {campusStats.map((campus) => (
            <div key={campus.id} className="flex items-center justify-between p-3 bg-slate-700/20 rounded-xl">
              <div className="flex items-center gap-3">
                <div className={`w-8 h-8 rounded-lg bg-gradient-to-br ${campus.bgGradient} flex items-center justify-center`}>
                  <span className="text-white text-xs font-bold">{campus.mascot[0]}</span>
                </div>
                <div>
                  <p className="text-sm font-medium text-white">{campus.fullName}</p>
                  {campus.config?.updated_by && (
                    <p className="text-[10px] text-slate-500">Updated by {campus.config.updated_by}</p>
                  )}
                </div>
              </div>
              {campus.config?.attendance_link ? (
                <a
                  href={campus.config.attendance_link}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-3 py-1.5 bg-orange-500/10 text-orange-400 border border-orange-500/20 rounded-lg text-xs hover:bg-orange-500/20 transition-all"
                >
                  <Globe size={12} />
                  Open Link
                  <ExternalLink size={10} />
                </a>
              ) : (
                <span className="text-xs text-slate-500 italic px-3 py-1.5">Not configured</span>
              )}
            </div>
          ))}
        </div>
      </div>
    </>
  );
}
