'use client';

import { useTranslations } from 'next-intl';
import { format } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  Clock,
  TrendingUp,
  TrendingDown,
  Calendar,
  AlertCircle,
  Target,
  Minus,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import { useTimeSummary } from '@/hooks/hr/use-time-tracking';
import { cn } from '@/lib/utils';

interface TimeSummaryProps {
  locale: string;
  employeeId: string;
  year?: number;
  month?: number;
}

/**
 * Monthly time summary with progress towards target hours
 */
export function TimeSummary({
  locale,
  employeeId,
  year = new Date().getFullYear(),
  month = new Date().getMonth() + 1,
}: TimeSummaryProps) {
  const t = useTranslations('hr.timeTracking');
  const dateLocale = locale === 'de' ? de : enUS;

  const { data: summary, isLoading, error } = useTimeSummary(employeeId, year, month);

  // Format hours
  const formatHours = (hours: number) => {
    const h = Math.floor(hours);
    const m = Math.round((hours - h) * 60);
    return `${h}h ${m}m`;
  };

  // Get month name
  const monthName = format(new Date(year, month - 1, 1), 'MMMM yyyy', {
    locale: dateLocale,
  });

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-32" />
          <Skeleton className="h-4 w-48" />
        </CardHeader>
        <CardContent className="space-y-6">
          <Skeleton className="h-4 w-full" />
          <div className="grid grid-cols-2 gap-4">
            <Skeleton className="h-20 w-full" />
            <Skeleton className="h-20 w-full" />
            <Skeleton className="h-20 w-full" />
            <Skeleton className="h-20 w-full" />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error || !summary) {
    return (
      <Card>
        <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('errorLoadingSummary')}</p>
        </CardContent>
      </Card>
    );
  }

  const progressPercent = Math.min(
    100,
    Math.round((summary.totalWorkHours / summary.targetWorkHours) * 100)
  );

  const isOvertime = summary.balanceHours > 0;
  const isUndertime = summary.balanceHours < 0;

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5" />
              {t('monthlySummary')}
            </CardTitle>
            <CardDescription>{monthName}</CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Progress towards target */}
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span>{t('progress')}</span>
            <span className="font-medium">{progressPercent}%</span>
          </div>
          <Progress value={progressPercent} className="h-3" />
          <div className="flex justify-between text-xs text-muted-foreground">
            <span>
              {formatHours(summary.totalWorkHours)} {t('worked')}
            </span>
            <span>
              {formatHours(summary.targetWorkHours)} {t('target')}
            </span>
          </div>
        </div>

        {/* Stats grid */}
        <div className="grid grid-cols-2 gap-4">
          {/* Total Work Hours */}
          <div className="rounded-lg border p-4">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Clock className="h-4 w-4" />
              {t('totalHours')}
            </div>
            <p className="mt-1 text-2xl font-bold tabular-nums">
              {formatHours(summary.totalWorkHours)}
            </p>
          </div>

          {/* Balance */}
          <div
            className={cn(
              'rounded-lg border p-4',
              isOvertime && 'border-green-300 bg-green-50 dark:bg-green-950/20',
              isUndertime && 'border-red-300 bg-red-50 dark:bg-red-950/20'
            )}
          >
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              {isOvertime ? (
                <TrendingUp className="h-4 w-4 text-green-600" />
              ) : isUndertime ? (
                <TrendingDown className="h-4 w-4 text-red-600" />
              ) : (
                <Minus className="h-4 w-4" />
              )}
              {t('balance')}
            </div>
            <p
              className={cn(
                'mt-1 text-2xl font-bold tabular-nums',
                isOvertime && 'text-green-600',
                isUndertime && 'text-red-600'
              )}
            >
              {isOvertime && '+'}
              {formatHours(Math.abs(summary.balanceHours))}
            </p>
          </div>

          {/* Overtime */}
          <div className="rounded-lg border p-4">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <TrendingUp className="h-4 w-4" />
              {t('overtime')}
            </div>
            <p className="mt-1 text-2xl font-bold tabular-nums">
              {formatHours(summary.overtimeHours)}
            </p>
          </div>

          {/* Work Days */}
          <div className="rounded-lg border p-4">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Target className="h-4 w-4" />
              {t('workDays')}
            </div>
            <p className="mt-1 text-2xl font-bold tabular-nums">{summary.workDays}</p>
          </div>
        </div>

        {/* Absence info */}
        {(summary.sickDays > 0 || summary.vacationDays > 0) && (
          <div className="rounded-lg bg-muted p-4">
            <p className="text-sm font-medium">{t('absencesThisMonth')}</p>
            <div className="mt-2 flex gap-4 text-sm">
              {summary.sickDays > 0 && (
                <span className="text-red-600">
                  {summary.sickDays} {t('sickDays')}
                </span>
              )}
              {summary.vacationDays > 0 && (
                <span className="text-blue-600">
                  {summary.vacationDays} {t('vacationDays')}
                </span>
              )}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
