"use client"
import { useEffect, useState } from "react";

type Attendance = {
  id: string;
  userId: string;
  clockIn: string;
  clockOut: string | null;
  status: string;
  date: string;
};

export function AttendanceSummary() {
  const [attendances, setAttendances] = useState<Attendance[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  
  useEffect(() => {
    const fetchAttendance = async () => {
      const employeeId = localStorage.getItem("employeeId");
      if (!employeeId) {
        setError("Employee ID not found in local storage");
        setIsLoading(false);
        return;
      }

      try {
        const res = await fetch(`/api/attendance/summary?employeeId=${employeeId}`);
        const data = await res.json();
        if (res.ok) {
          setAttendances(data.attendances);
        } else {
          setError(data.error || "Failed to fetch attendance summary");
        }
      } catch (err: any) {
        setError(err.message);
      } finally {
        setIsLoading(false);
      }
    };
    fetchAttendance();
  }, []);

  // Group attendances by date
  const attendancesByDate = attendances.reduce<Record<string, Attendance[]>>((acc, attendance) => {
    const date = new Date(attendance.clockIn).toLocaleDateString();
    if (!acc[date]) {
      acc[date] = [];
    }
    acc[date].push(attendance);
    return acc;
  }, {});

  // Calculate work duration for an attendance record
  const calculateDuration = (clockIn: string, clockOut: string | null): string => {
    if (!clockOut) return "In progress";
    
    const start = new Date(clockIn).getTime();
    const end = new Date(clockOut).getTime();
    const durationMs = end - start;
    
    const hours = Math.floor(durationMs / (1000 * 60 * 60));
    const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));
    
    return `${hours}h ${minutes}m`;
  };

  if (isLoading) return <div className="p-4 text-center text-gray-500">Loading attendance records...</div>;
  if (error) return <div className="p-4 text-center text-red-500">Error: {error}</div>;

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-bold mb-4">Attendance Summary</h2>
      
      {Object.keys(attendancesByDate).length > 0 ? (
        Object.entries(attendancesByDate)
          .sort(([dateA], [dateB]) => new Date(dateB).getTime() - new Date(dateA).getTime())
          .map(([date, records]) => (
            <div key={date} className="border rounded-lg overflow-hidden shadow-sm">
              <div className="bg-gray-100 px-4 py-2 font-medium">{date}</div>
              <div className="divide-y">
                {records.map((att) => (
                  <div key={att.id} className="px-4 py-3 flex justify-between items-center">
                    <div>
                      <div className="flex items-center space-x-2">
                        <div className={`h-2 w-2 rounded-full ${
                          att.status === 'Present' ? 'bg-green-500' : 
                          att.status === 'Late' ? 'bg-yellow-500' : 'bg-red-500'
                        }`}></div>
                        <span className="font-medium">{att.status}</span>
                      </div>
                      <div className="text-sm text-gray-600 mt-1">
                        In: {new Date(att.clockIn).toLocaleTimeString()}
                        {att.clockOut && (
                          <span> • Out: {new Date(att.clockOut).toLocaleTimeString()}</span>
                        )}
                      </div>
                    </div>
                    <div className="text-sm font-medium">
                      {calculateDuration(att.clockIn, att.clockOut)}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))
      ) : (
        <div className="text-center p-8 bg-gray-50 rounded-lg border">
          <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <h3 className="mt-2 text-sm font-medium text-gray-900">No attendance records</h3>
          <p className="mt-1 text-sm text-gray-500">No attendance records have been found for your account.</p>
        </div>
      )}
    </div>
  );
}