"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"
import { Button } from "./ui/button"
import { Calendar } from "./ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"
import { format } from "date-fns"
import { toSouthAfricaTime } from "../lib/timezone"
import { CalendarIcon } from "lucide-react"
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"
import { DateRange } from "react-date-range"
import "react-date-range/dist/styles.css"
import "react-date-range/dist/theme/default.css"

interface ExtendedRange {
  startDate: Date
  endDate: Date
  key: string
}

// Define types for our attendance data
type AttendanceRecord = {
  id: string
  employeeId: string
  employeeName: string
  profilePicture: string
  selfieImage?: string
  department: string
  date: string
  clockIn: string
  clockOut: string | null
  hoursWorked: string | null
  status: "On Time" | "Late" | "Active"
  location: string
}

export function AttendanceReport({ dateRange, setDateRange, attendanceData }: { dateRange: ExtendedRange[], setDateRange: React.Dispatch<React.SetStateAction<ExtendedRange[]>>, attendanceData: AttendanceRecord[] }) {
  const [department, setDepartment] = useState("all")
  const [selectedEmployee, setSelectedEmployee] = useState("all")
  const [employees, setEmployees] = useState<{id: string, name: string}[]>([])

  useEffect(() => {
    const uniqueEmployees = Array.from(
      new Map(attendanceData.map(r => [r.employeeId, {id: r.employeeId, name: r.employeeName}])).values()
    )
    setEmployees(uniqueEmployees)
  }, [attendanceData])

  // Filter attendance records based on department and employee
  const filteredData = attendanceData.filter((record) => {
    if (department !== "all" && record.department.toLowerCase() !== department.toLowerCase()) {
      return false
    }
    if (selectedEmployee !== "all" && record.employeeId !== selectedEmployee) {
      return false
    }
    return true
  })

  // Helper function to safely prepare data for Excel export
  const prepareDataForExport = (data: any[]) => {
    return data.map((item) => {
      const safeItem: any = {}
      for (const [key, value] of Object.entries(item)) {
        if (value === null || value === undefined) {
          safeItem[key] = ""
        } else if (typeof value === "object" && !(value instanceof Date)) {
          safeItem[key] = JSON.stringify(value)
        } else {
          safeItem[key] = value
        }
      }
      return safeItem
    })
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Attendance Report</CardTitle>
          <CardDescription>View and export attendance data by department and date</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            <div className="w-full sm:w-1/4">
              <label className="text-sm font-medium mb-1 block">Department</label>
              <Select value={department} onValueChange={setDepartment}>
                <SelectTrigger>
                  <SelectValue placeholder="Select department" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Departments</SelectItem>
                  <SelectItem value="Special Project">Special Project</SelectItem>
                  <SelectItem value="ICT">ICT</SelectItem>
                  <SelectItem value="Civil Infrastructure">Civil Infrastructure</SelectItem>
                  <SelectItem value="Admin">Admin</SelectItem>
                  <SelectItem value="HR">HR</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="w-full sm:w-1/4">
              <label className="text-sm font-medium mb-1 block">Employee</label>
              <Select value={selectedEmployee} onValueChange={setSelectedEmployee}>
                <SelectTrigger>
                  <SelectValue placeholder="Select employee" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Employees</SelectItem>
                  {employees.map(emp => (
                    <SelectItem key={emp.id} value={emp.id}>{emp.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          <div className="w-full sm:w-1/2">
            <label className="text-sm font-medium mb-1 block">Date Range</label>
            <Popover>
              <PopoverTrigger asChild>
                <Button variant="outline" className="w-full justify-start text-left font-normal">
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {(dateRange[0] as any).startDate && (dateRange[0] as any).endDate
                    ? `${format((dateRange[0] as any).startDate, "PPP")} - ${format((dateRange[0] as any).endDate, "PPP")}`
                    : "Select date range"}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0">
                <DateRange
                  editableDateInputs={true}
                  onChange={(item: any) => setDateRange([item.selection])}
                  moveRangeOnFirstSelection={false}
                  ranges={dateRange}
                  maxDate={new Date()}
                />
              </PopoverContent>
            </Popover>
          </div>
          </div>

          <div className="overflow-x-auto max-h-[calc(100vh-300px)] overflow-y-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b dark:border-slate-700">
                  <th className="text-left py-3 px-4 font-medium">Profile</th>
                  <th className="text-left py-3 px-4 font-medium">ID</th>
                  <th className="text-left py-3 px-4 font-medium">Name</th>
                  <th className="text-left py-3 px-4 font-medium">Department</th>
                  <th className="text-left py-3 px-4 font-medium">Clock In</th>
                  <th className="text-left py-3 px-4 font-medium">Clock Out</th>
                  <th className="text-left py-3 px-4 font-medium">Hours</th>
                  <th className="text-left py-3 px-4 font-medium">Location</th>
                  <th className="text-left py-3 px-4 font-medium">Selfie</th>
                  <th className="text-left py-3 px-4 font-medium">Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredData.length > 0 ? (
                  filteredData.map((record, index) => (
                    <tr key={index} className="border-b dark:border-slate-700">
                      <td className="py-3 px-4">
                        <img 
                          src={record.profilePicture} 
                          alt={record.employeeName}
                          className="w-10 h-10 rounded-full object-cover"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = '/placeholder-user.jpg'
                          }}
                        />
                      </td>
                      <td className="py-3 px-4">{record.employeeId}</td>
                      <td className="py-3 px-4">{record.employeeName}</td>
                      <td className="py-3 px-4">{record.department}</td>
                      <td className="py-3 px-4">{format(toSouthAfricaTime(new Date(record.clockIn)), "p")}</td>
                      <td className="py-3 px-4">{record.clockOut ? format(toSouthAfricaTime(new Date(record.clockOut)), "p") : "Active"}</td>
                      <td className="py-3 px-4">{record.hoursWorked || "In Progress"}</td>
                      <td className="py-3 px-4">{record.location}</td>
                      <td className="py-3 px-4">
                        <Avatar className="h-16 w-16">
                        {record.selfieImage ? (
                        <AvatarImage src={`data:image/jpeg;base64,${record.selfieImage}`} alt="Profile" />
                        ) : (
                        <AvatarImage src="/placeholder.svg?height=64&width=64" alt="Profile" />
                        )}
                        <AvatarFallback className="text-xl">
                        {record.employeeName.split(" ").map((n) => n[0]).join("")}
                        </AvatarFallback>
                      </Avatar>
                      </td>
                      <td className="py-3 px-4">
                        <span
                          className={`inline-block px-2 py-1 rounded-full text-xs ${
                            record.status === "On Time"
                              ? "bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400"
                              : record.status === "Active"
                              ? "bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400"
                              : "bg-amber-100 text-amber-800 dark:bg-amber-900/20 dark:text-amber-400"
                          }`}
                        >
                          {record.status}
                        </span>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={10} className="py-6 text-center text-slate-500 dark:text-slate-400">
                      No attendance records found for the selected filters
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
