'use client';

import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import { format } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  Play,
  Pause,
  Square,
  Coffee,
  Clock,
  CheckCircle2,
  AlertCircle,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import {
  useTimeTrackingStatus,
  useClockIn,
  useClockOut,
  useStartBreak,
  useEndBreak,
} from '@/hooks/hr/use-time-tracking';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import type { TimeEntryStatus } from '@/types/hr';

interface TimeClockProps {
  locale: string;
}

/**
 * Web-based time clock for clocking in/out and breaks
 * Features a prominent clock display with action buttons
 */
export function TimeClock({ locale }: TimeClockProps) {
  const t = useTranslations('hr.timeTracking');
  const tCommon = useTranslations('common');
  const { toast } = useToast();

  const [currentTime, setCurrentTime] = useState(new Date());

  // Queries and mutations
  const { data: status, isLoading, error } = useTimeTrackingStatus();
  const clockIn = useClockIn();
  const clockOut = useClockOut();
  const startBreak = useStartBreak();
  const endBreak = useEndBreak();

  // Update clock every second
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  const dateLocale = locale === 'de' ? de : enUS;

  // Calculate work duration
  const getWorkDuration = () => {
    if (!status?.clockInTime) return '00:00:00';

    const startTime = new Date(status.clockInTime);
    const diff = currentTime.getTime() - startTime.getTime();
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  };

  // Handle clock in
  const handleClockIn = async () => {
    try {
      await clockIn.mutateAsync();
      toast({
        title: t('clockedIn'),
        description: t('clockedInDesc'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorClockIn'),
        variant: 'destructive',
      });
    }
  };

  // Handle clock out
  const handleClockOut = async () => {
    try {
      await clockOut.mutateAsync();
      toast({
        title: t('clockedOut'),
        description: t('clockedOutDesc'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorClockOut'),
        variant: 'destructive',
      });
    }
  };

  // Handle break start
  const handleStartBreak = async () => {
    try {
      await startBreak.mutateAsync();
      toast({
        title: t('breakStarted'),
        description: t('breakStartedDesc'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorBreakStart'),
        variant: 'destructive',
      });
    }
  };

  // Handle break end
  const handleEndBreak = async () => {
    try {
      await endBreak.mutateAsync();
      toast({
        title: t('breakEnded'),
        description: t('breakEndedDesc'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorBreakEnd'),
        variant: 'destructive',
      });
    }
  };

  // Get status badge
  const getStatusBadge = (currentStatus: TimeEntryStatus) => {
    switch (currentStatus) {
      case 'CLOCKED_IN':
        return (
          <Badge className="bg-green-100 text-green-700 hover:bg-green-100">
            <CheckCircle2 className="mr-1 h-3 w-3" />
            {t('working')}
          </Badge>
        );
      case 'ON_BREAK':
        return (
          <Badge className="bg-yellow-100 text-yellow-700 hover:bg-yellow-100">
            <Coffee className="mr-1 h-3 w-3" />
            {t('onBreak')}
          </Badge>
        );
      case 'CLOCKED_OUT':
        return (
          <Badge variant="secondary">
            <Square className="mr-1 h-3 w-3" />
            {t('notWorking')}
          </Badge>
        );
    }
  };

  if (isLoading) {
    return (
      <Card className="col-span-full md:col-span-1">
        <CardHeader className="pb-3">
          <Skeleton className="h-6 w-32" />
        </CardHeader>
        <CardContent className="space-y-6">
          <Skeleton className="h-24 w-full" />
          <Skeleton className="h-12 w-full" />
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="col-span-full md:col-span-1">
        <CardContent className="flex flex-col items-center justify-center py-12">
          <AlertCircle className="h-12 w-12 text-destructive" />
          <p className="mt-4 text-muted-foreground">{t('errorLoading')}</p>
        </CardContent>
      </Card>
    );
  }

  const currentStatus = status?.status || 'CLOCKED_OUT';
  const isClockedIn = currentStatus === 'CLOCKED_IN' || currentStatus === 'ON_BREAK';
  const isOnBreak = currentStatus === 'ON_BREAK';
  const isProcessing =
    clockIn.isPending ||
    clockOut.isPending ||
    startBreak.isPending ||
    endBreak.isPending;

  return (
    <Card className="col-span-full md:col-span-1">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <Clock className="h-5 w-5" />
            {t('title')}
          </CardTitle>
          {getStatusBadge(currentStatus)}
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Current time display */}
        <div className="text-center">
          <motion.div
            key={currentTime.toISOString()}
            initial={{ opacity: 0.5 }}
            animate={{ opacity: 1 }}
            className="text-5xl font-mono font-bold tabular-nums"
          >
            {format(currentTime, 'HH:mm:ss')}
          </motion.div>
          <p className="text-sm text-muted-foreground mt-1">
            {format(currentTime, 'EEEE, d. MMMM yyyy', { locale: dateLocale })}
          </p>
        </div>

        {/* Work duration (when clocked in) */}
        <AnimatePresence>
          {isClockedIn && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="rounded-lg bg-muted p-4 text-center"
            >
              <p className="text-sm text-muted-foreground">{t('workDuration')}</p>
              <p className="text-2xl font-mono font-semibold tabular-nums">
                {getWorkDuration()}
              </p>
              {status?.clockInTime && (
                <p className="text-xs text-muted-foreground mt-1">
                  {t('since')} {format(new Date(status.clockInTime), 'HH:mm')}
                </p>
              )}
            </motion.div>
          )}
        </AnimatePresence>

        {/* Action buttons */}
        <div className="space-y-3">
          {!isClockedIn ? (
            <Button
              size="lg"
              className="w-full h-14 text-lg gap-2"
              onClick={handleClockIn}
              disabled={isProcessing}
            >
              <Play className="h-5 w-5" />
              {t('clockIn')}
            </Button>
          ) : (
            <>
              {!isOnBreak ? (
                <Button
                  variant="secondary"
                  size="lg"
                  className="w-full h-12 gap-2"
                  onClick={handleStartBreak}
                  disabled={isProcessing}
                >
                  <Coffee className="h-4 w-4" />
                  {t('startBreak')}
                </Button>
              ) : (
                <Button
                  variant="secondary"
                  size="lg"
                  className="w-full h-12 gap-2 bg-yellow-100 hover:bg-yellow-200 text-yellow-800"
                  onClick={handleEndBreak}
                  disabled={isProcessing}
                >
                  <Play className="h-4 w-4" />
                  {t('endBreak')}
                </Button>
              )}
              <Button
                variant="destructive"
                size="lg"
                className="w-full h-14 text-lg gap-2"
                onClick={handleClockOut}
                disabled={isProcessing || isOnBreak}
              >
                <Square className="h-5 w-5" />
                {t('clockOut')}
              </Button>
            </>
          )}
        </div>

        {/* Today's summary */}
        {status && (
          <div className="grid grid-cols-2 gap-4 pt-4 border-t">
            <div className="text-center">
              <p className="text-2xl font-semibold tabular-nums">
                {Math.floor((status.todayWorkMinutes || 0) / 60)}h{' '}
                {(status.todayWorkMinutes || 0) % 60}m
              </p>
              <p className="text-xs text-muted-foreground">{t('todayWorked')}</p>
            </div>
            <div className="text-center">
              <p className="text-2xl font-semibold tabular-nums">
                {status.todayBreakMinutes || 0}m
              </p>
              <p className="text-xs text-muted-foreground">{t('todayBreak')}</p>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
