'use client';

import { useTranslations } from 'next-intl';
import { format, parseISO, differenceInDays } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  Palmtree,
  Calendar,
  Clock,
  AlertTriangle,
  AlertCircle,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { useVacationBalance } from '@/hooks/hr/use-absences';
import { cn } from '@/lib/utils';

interface VacationBalanceProps {
  locale: string;
  employeeId: string;
  year?: number;
  compact?: boolean;
}

/**
 * Vacation balance display showing remaining, used, and pending days
 */
export function VacationBalance({
  locale,
  employeeId,
  year = new Date().getFullYear(),
  compact = false,
}: VacationBalanceProps) {
  const t = useTranslations('hr.absences');
  const dateLocale = locale === 'de' ? de : enUS;

  const { data: balance, isLoading, error } = useVacationBalance(employeeId, year);

  if (isLoading) {
    return (
      <Card className={cn(compact && 'shadow-none border-0')}>
        {!compact && (
          <CardHeader>
            <Skeleton className="h-6 w-32" />
          </CardHeader>
        )}
        <CardContent className={cn(compact && 'p-0')}>
          <div className="space-y-4">
            <Skeleton className="h-4 w-full" />
            <div className="grid grid-cols-3 gap-4">
              <Skeleton className="h-16 w-full" />
              <Skeleton className="h-16 w-full" />
              <Skeleton className="h-16 w-full" />
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error || !balance) {
    return (
      <Card className={cn(compact && 'shadow-none border-0')}>
        <CardContent className="flex flex-col items-center justify-center py-8">
          <AlertCircle className="h-10 w-10 text-destructive" />
          <p className="mt-2 text-sm text-muted-foreground">{t('errorLoadingBalance')}</p>
        </CardContent>
      </Card>
    );
  }

  const usedPercent = Math.round((balance.usedDays / balance.totalDays) * 100);
  const pendingPercent = Math.round((balance.pendingDays / balance.totalDays) * 100);

  // Check if expiration is approaching
  const expirationWarning =
    balance.expiringDays > 0 &&
    balance.expirationDate &&
    differenceInDays(parseISO(balance.expirationDate), new Date()) <= 60;

  if (compact) {
    return (
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium">{t('vacationBalance')}</span>
          <span className="text-2xl font-bold">{balance.remainingDays}</span>
        </div>
        <Progress value={usedPercent} className="h-2" />
        <div className="flex justify-between text-xs text-muted-foreground">
          <span>
            {balance.usedDays} {t('used')}
          </span>
          <span>
            {balance.totalDays} {t('total')}
          </span>
        </div>
      </div>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Palmtree className="h-5 w-5" />
          {t('vacationBalance')}
        </CardTitle>
        <CardDescription>{year}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Main balance display */}
        <div className="text-center">
          <p className="text-5xl font-bold">{balance.remainingDays}</p>
          <p className="text-sm text-muted-foreground">{t('daysRemaining')}</p>
        </div>

        {/* Progress bar */}
        <div className="space-y-2">
          <div className="h-4 w-full rounded-full bg-muted overflow-hidden flex">
            <div
              className="h-full bg-primary transition-all"
              style={{ width: `${usedPercent}%` }}
            />
            <div
              className="h-full bg-yellow-400 transition-all"
              style={{ width: `${pendingPercent}%` }}
            />
          </div>
          <div className="flex justify-between text-xs">
            <div className="flex items-center gap-1">
              <div className="h-2 w-2 rounded-full bg-primary" />
              <span>
                {balance.usedDays} {t('used')}
              </span>
            </div>
            <div className="flex items-center gap-1">
              <div className="h-2 w-2 rounded-full bg-yellow-400" />
              <span>
                {balance.pendingDays} {t('pending')}
              </span>
            </div>
            <div className="flex items-center gap-1">
              <div className="h-2 w-2 rounded-full bg-muted" />
              <span>
                {balance.remainingDays} {t('available')}
              </span>
            </div>
          </div>
        </div>

        {/* Stats grid */}
        <div className="grid grid-cols-3 gap-4">
          <div className="rounded-lg border p-3 text-center">
            <p className="text-xl font-semibold">{balance.totalDays}</p>
            <p className="text-xs text-muted-foreground">{t('totalEntitlement')}</p>
          </div>
          <div className="rounded-lg border p-3 text-center">
            <p className="text-xl font-semibold">{balance.usedDays}</p>
            <p className="text-xs text-muted-foreground">{t('taken')}</p>
          </div>
          <div className="rounded-lg border p-3 text-center">
            <p className="text-xl font-semibold">{balance.pendingDays}</p>
            <p className="text-xs text-muted-foreground">{t('planned')}</p>
          </div>
        </div>

        {/* Carried over days */}
        {balance.carriedOverDays > 0 && (
          <div className="rounded-lg bg-muted p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">{t('carriedOver')}</span>
              </div>
              <Badge variant="secondary">{balance.carriedOverDays} {t('days')}</Badge>
            </div>
          </div>
        )}

        {/* Expiration warning */}
        {expirationWarning && (
          <div className="rounded-lg border border-yellow-300 bg-yellow-50 dark:bg-yellow-950/20 p-4">
            <div className="flex items-start gap-3">
              <AlertTriangle className="h-5 w-5 text-yellow-600 mt-0.5" />
              <div>
                <p className="font-medium text-yellow-800 dark:text-yellow-200">
                  {t('expirationWarning')}
                </p>
                <p className="text-sm text-yellow-700 dark:text-yellow-300">
                  {t('expirationWarningDesc', {
                    days: balance.expiringDays,
                    date: format(parseISO(balance.expirationDate!), 'PPP', {
                      locale: dateLocale,
                    }),
                  })}
                </p>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
