
"use client";

import { useTransition, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import { handleCheckIn, handleCheckOut, handleAutomaticCheckIn } from "@/lib/actions";
import { CalendarCheck, Loader2, LogIn, LogOut } from "lucide-react";
import { type AttendanceRecord } from "@/lib/types";
import { format } from "date-fns";

type Translation = {
    title: string;
    completed: string;
    checkedIn: string;
    pending: string;
    completedDesc: string;
    checkedInDesc: string;
    pendingDesc: string;
    checkInButton: string;
    checkOutButton: string;
    recordedButton: string;
}

export default function AttendanceCard({ todaysAttendance, t }: { todaysAttendance: AttendanceRecord | undefined, t: Translation }) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const router = useRouter();
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // If the user is already checked in or has completed their day, do nothing.
    if (todaysAttendance) {
        // Also clear any existing interval, just in case.
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }
        return;
    }

    const autoCheckIn = async () => {
        // A background task shouldn't use the main transition spinner
        const result = await handleAutomaticCheckIn();

        if (result.success) {
            toast({
                title: "Automatic Check-in",
                description: result.message,
            });
            // Stop polling once checked in
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
            router.refresh();
        }
        // Don't show error toasts for background failures to avoid spamming the user.
    };

    // Run once on component mount
    autoCheckIn();

    // Set up the interval to run every 5 minutes (300,000 ms)
    intervalRef.current = setInterval(autoCheckIn, 300000);

    // Cleanup function to clear the interval when the component unmounts or dependencies change
    return () => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }
    };
}, [todaysAttendance, router, toast]);

  const onCheckIn = () => {
    startTransition(async () => {
      const result = await handleCheckIn();
      if (result.success) {
        toast({
          title: "Success",
          description: result.message,
        });
        router.refresh();
      } else {
        toast({
          title: "Check-in Failed",
          description: result.message,
          variant: "destructive",
        });
      }
    });
  };

  const onCheckOut = () => {
    startTransition(async () => {
      const result = await handleCheckOut();
      if (result.success) {
        toast({
          title: "Success",
          description: result.message,
        });
        router.refresh();
      } else {
        toast({
          title: "Check-out Failed",
          description: result.message,
          variant: "destructive",
        });
      }
    });
  };

  const checkInTime = todaysAttendance?.checkIn ? format(new Date(todaysAttendance.checkIn), 'p') : '';
  const checkOutTime = todaysAttendance?.checkOut ? format(new Date(todaysAttendance.checkOut), 'p') : '';

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{t.title}</CardTitle>
        <CalendarCheck className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">
            {checkOutTime ? t.completed : checkInTime ? t.checkedIn : t.pending}
        </div>
        <p className="text-xs text-muted-foreground">
          {checkOutTime
            ? t.completedDesc.replace('{checkInTime}', checkInTime).replace('{checkOutTime}', checkOutTime)
            : checkInTime
            ? t.checkedInDesc.replace('{checkInTime}', checkInTime)
            : t.pendingDesc}
        </p>

        {!todaysAttendance && (
            <Button className="mt-4 w-full" onClick={onCheckIn} disabled={isPending}>
                {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <LogIn className="me-2 h-4 w-4" />}
                {t.checkInButton}
            </Button>
        )}

        {todaysAttendance && !todaysAttendance.checkOut && (
            <Button className="mt-4 w-full" onClick={onCheckOut} disabled={isPending} variant="outline">
                {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <LogOut className="me-2 h-4 w-4" />}
                {t.checkOutButton}
            </Button>
        )}
        
        {todaysAttendance && todaysAttendance.checkOut && (
             <Button className="mt-4 w-full" disabled={true} variant="secondary">
                <CalendarCheck className="me-2 h-4 w-4" />
                {t.recordedButton}
            </Button>
        )}
      </CardContent>
    </Card>
  );
}
