"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Textarea } from "@/components/ui/textarea"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { CalendarIcon, Search, Pencil, Trash2, CircleX } from "lucide-react"
import { format } from "date-fns"
import { fr } from "date-fns/locale"
import { cn } from "@/lib/utils"
import type { AttendanceWithDetails } from "@/lib/types"
import { getAuthToken } from "@/lib/auth"
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"
import { Alert, AlertDescription } from "@/components/ui/alert"

interface Class {
  id: number
  name: string
}

export default function AttendancePage() {
  const [date, setDate] = useState<Date>(new Date())
  const [hour, setHour] = useState("all")
  const [searchQuery, setSearchQuery] = useState("")
  const [filterClasse, setFilterClasse] = useState("all")
  const [filterStatus, setFilterStatus] = useState("all")
  const [editDialogOpen, setEditDialogOpen] = useState(false)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [selectedRecord, setSelectedRecord] = useState<AttendanceWithDetails | null>(null)
  const [justification, setJustification] = useState("")
  const [hoursAbsent, setHoursAbsent] = useState("")
  const [attendanceRecords, setAttendanceRecords] = useState<AttendanceWithDetails[]>([])
  const [classes, setClasses] = useState<Class[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()

  // Fetch classes
  useEffect(() => {
    const fetchClasses = async () => {
      try {
        const token = getAuthToken()
        if (!token) {
          router.push("/login")
          return
        }
        const response = await fetch("/api/classes", {
          headers: { Authorization: `Bearer ${token}` },
        })
        if (response.ok) {
          const data = await response.json()
          setClasses(data)
        } else {
          console.error("Failed to fetch classes")
        }
      } catch (err) {
        console.error("Error fetching classes:", err)
      }
    }
    fetchClasses()
  }, [router])

  // Fetch attendance for the selected day/hour
  const fetchAttendance = async () => {
    try {
      setLoading(true)
      const token = getAuthToken()
      if (!token) {
        router.push("/login")
        return
      }

      let startDate = format(date, "yyyy-MM-dd") + " 00:00:00"
      let endDate = format(date, "yyyy-MM-dd") + " 23:59:59"

      if (hour !== "all") {
        startDate = format(date, "yyyy-MM-dd") + ` ${hour}:00:00`
        endDate = format(date, "yyyy-MM-dd") + ` ${hour}:59:59`
      }

      const url = new URL("/api/attendance", window.location.origin)
      url.searchParams.append("startDate", startDate)
      url.searchParams.append("endDate", endDate)
      if (filterClasse !== "all") url.searchParams.append("class", filterClasse)
      if (filterStatus !== "all") url.searchParams.append("status", filterStatus)
      if (searchQuery) url.searchParams.append("search", searchQuery)

      const response = await fetch(url.toString(), {
        headers: { Authorization: `Bearer ${token}` },
      })

      if (!response.ok) {
        const errorText = await response.text()
        if (response.status === 401) {
          router.push("/login")
          return
        }
        throw new Error(`Échec de la récupération des présences: ${response.status} ${errorText}`)
      }

      const data = await response.json()
      setAttendanceRecords(data)
      setError(null)
    } catch (err: any) {
      setError(`Erreur lors de la récupération des présences`)
      // console.error("Erreur de récupération des présences:", err)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchAttendance()
  }, [date, hour, filterClasse, filterStatus, searchQuery])

  const handleEditRecord = (record: AttendanceWithDetails) => {
    setSelectedRecord(record)
    setJustification(record.justification || "")
    setHoursAbsent(record.hours_absent?.toString() || "")
    setEditDialogOpen(true)
  }

  const handleSaveEdit = async () => {
    if (!selectedRecord) return

    try {
      const token = getAuthToken()
      if (!token) {
        router.push("/login")
        return
      }

      const response = await fetch(`/api/attendance/${selectedRecord.id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          justification,
          hoursAbsent: parseFloat(hoursAbsent) || null,
        }),
      })

      if (!response.ok) {
        throw new Error("Failed to update attendance")
      }

      await fetchAttendance()
      setEditDialogOpen(false)
    } catch (err) {
      setError("Erreur lors de la mise à jour de la présence")
    }
  }

  const handleDeleteRecord = (record: AttendanceWithDetails) => {
    setSelectedRecord(record)
    setDeleteDialogOpen(true)
  }

  const confirmDelete = async () => {
    if (!selectedRecord) return

    try {
      const token = getAuthToken()
      if (!token) {
        router.push("/login")
        return
      }

      const response = await fetch(`/api/attendance/${selectedRecord.id}`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${token}` },
      })

      if (!response.ok) {
        throw new Error("Failed to delete attendance")
      }

      await fetchAttendance()
      setDeleteDialogOpen(false)
    } catch (err) {
      setError("Erreur lors de la suppression de la présence")
    }
  }

  return (
    <AuthGuard allowedRoles={["admin"]}>
      <DashboardLayout>
        <div className="space-y-6">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between">
            <div className="hidden md:block">
              <h1 className="text-2xl sm:text-3xl font-semibold tracking-tight">Présences</h1>
              <p className="text-muted-foreground text-sm sm:text-base">
                Visualiser, modifier ou supprimer les enregistrements de présence
              </p>
            </div>
          </div>
          {error && (
            <Alert variant="destructive">
              <CircleX className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <div className="grid bg-card border rounded-lg p-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="space-y-2">
              <Label>Date</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full justify-start text-left font-normal bg-background",
                      !date && "text-muted-foreground"
                    )}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {date ? format(date, "PPP", { locale: fr }) : <span>Choisir une date</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0 bg-background">
                  <Calendar mode="single" selected={date} onSelect={setDate} initialFocus />
                </PopoverContent>
              </Popover>
            </div>

            <div className="space-y-2">
              <Label>Heure</Label>
              <Select value={hour} onValueChange={setHour}>
                <SelectTrigger className="bg-background">
                  <SelectValue placeholder="Filtrer par heure" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Toute la journée</SelectItem>
                  <SelectItem value="08">08:00-10:00</SelectItem>
                  <SelectItem value="10">10:00-12:00</SelectItem>
                  <SelectItem value="12">12:00-14:00</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Classe</Label>
              <Select value={filterClasse} onValueChange={setFilterClasse}>
                <SelectTrigger className="bg-background">
                  <SelectValue placeholder="Filtrer par classe" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Toutes les classes</SelectItem>
                  {classes.map((cls) => (
                    <SelectItem key={cls.id} value={cls.name}>
                      {cls.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Statut</Label>
              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="bg-background">
                  <SelectValue placeholder="Filtrer par statut" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Tous les statuts</SelectItem>
                  <SelectItem value="present">Présent</SelectItem>
                  <SelectItem value="absent">Absent</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Rechercher par nom d'étudiant ou classe..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 bg-background"
            />
          </div>

          <div className="rounded-lg border border-border bg-card">
            <ScrollArea className="w-96 md:w-auto lg:w-full">
              <Table>
                <TableHeader>
                  <TableRow className="hover:bg-transparent border-border">
                    <TableHead>Étudiant</TableHead>
                    <TableHead>Classe</TableHead>
                    <TableHead>Date/Heure</TableHead>
                    <TableHead>Statut</TableHead>
                    <TableHead>Heures absentes</TableHead>
                    <TableHead>Justification</TableHead>
                    <TableHead>Surveillant</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center text-muted-foreground">
                        Chargement...
                      </TableCell>
                    </TableRow>
                  ) : attendanceRecords.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center text-muted-foreground">
                        Aucune présence trouvée
                      </TableCell>
                    </TableRow>
                  ) : (
                    attendanceRecords.map((record) => (
                      <TableRow key={record.id} className="border-border">
                        <TableCell className="font-medium">{record.student_name}</TableCell>
                        <TableCell>{record.classe}</TableCell>
                        <TableCell>{format(new Date(record.date), "PPP HH:mm", { locale: fr })}</TableCell>
                        <TableCell>
                          <span
                            className={`rounded-full px-3 py-1 text-xs font-medium ${
                              record.status === "present"
                                ? "bg-green-500/10 text-green-500"
                                : "bg-red-500/10 text-red-500"
                            }`}
                          >
                            {record.status === "present" ? "Présent" : "Absent"}
                          </span>
                        </TableCell>
                        <TableCell>{record.hours_absent ? `${record.hours_absent}h` : "-"}</TableCell>
                        <TableCell className="max-w-[200px] truncate">
                          {record.justification || (
                            <span className="text-muted-foreground italic">Aucune</span>
                          )}
                        </TableCell>
                        <TableCell>{record.observer_name}</TableCell>
                        <TableCell className="text-right">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleEditRecord(record)}
                          >
                            <Pencil className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="text-red-500 hover:text-red-700"
                            onClick={() => handleDeleteRecord(record)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
              <ScrollBar orientation="horizontal" />
            </ScrollArea>
          </div>
        </div>

        {/* Edit Dialog */}
        {selectedRecord && (
          <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
            <DialogContent className="w-[90vw] max-w-lg bg-card">
              <DialogHeader>
                <DialogTitle>Modifier l'enregistrement de présence</DialogTitle>
                <DialogDescription>
                  Modifier la présence pour {selectedRecord.student_name} le {format(date, "PPP HH:mm", { locale: fr })}
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="hours">Heures d'absence</Label>
                  <Input
                    id="hours"
                    type="number"
                    step="0.5"
                    min="0"
                    value={hoursAbsent}
                    onChange={(e) => setHoursAbsent(e.target.value)}
                    className="bg-background text-sm sm:text-base"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="justification">Justification</Label>
                  <Textarea
                    id="justification"
                    placeholder="Entrez la justification de l'absence..."
                    value={justification}
                    onChange={(e) => setJustification(e.target.value)}
                    rows={4}
                    className="bg-background resize-none text-sm sm:text-base"
                  />
                </div>

                <div className="flex justify-end gap-2">
                  <Button variant="outline" onClick={() => setEditDialogOpen(false)}>
                    Annuler
                  </Button>
                  <Button onClick={handleSaveEdit}>Enregistrer les modifications</Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        )}

        {/* Delete Dialog */}
        {selectedRecord && (
          <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
            <DialogContent className="w-[90vw] max-w-md bg-card">
              <DialogHeader>
                <DialogTitle>Supprimer l'enregistrement de présence</DialogTitle>
                <DialogDescription>
                  Êtes-vous sûr de vouloir supprimer l'enregistrement de présence pour{" "}
                  <strong>{selectedRecord.student_name}</strong> ? Cette action est irréversible.
                </DialogDescription>
              </DialogHeader>
              <div className="flex justify-end gap-2 mt-4">
                <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
                  Annuler
                </Button>
                <Button variant="destructive" onClick={confirmDelete}>
                  Supprimer
                </Button>
              </div>
            </DialogContent>
          </Dialog>
        )}
      </DashboardLayout>
    </AuthGuard>
  )
}