'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import {
  format,
  startOfMonth,
  endOfMonth,
  eachDayOfInterval,
  isSameMonth,
  isSameDay,
  addMonths,
  subMonths,
  getDay,
  isWeekend,
  parseISO,
} from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  ChevronLeft,
  ChevronRight,
  Palmtree,
  Thermometer,
  Home,
  Star,
  CalendarOff,
  GraduationCap,
  AlertCircle,
  Baby,
  Heart,
  Plane,
  Clock,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { useAbsenceCalendar } from '@/hooks/hr/use-absences';
import { cn } from '@/lib/utils';
import type { AbsenceType, AbsenceCalendarEntry } from '@/types/hr';
import { ABSENCE_TYPE_INFO } from '@/types/hr';

interface AbsenceCalendarProps {
  locale: string;
  departmentId?: string;
}

const ABSENCE_ICONS: Record<AbsenceType, typeof Palmtree> = {
  VACATION: Palmtree,
  SICK: Thermometer,
  SICK_CHILD: Baby,
  HOME_OFFICE: Home,
  SPECIAL_LEAVE: Star,
  UNPAID_LEAVE: CalendarOff,
  PARENTAL_LEAVE: Heart,
  BUSINESS_TRIP: Plane,
  TRAINING: GraduationCap,
  COMPENSATION: Clock,
};

/**
 * Calendar view showing team absences
 */
export function AbsenceCalendar({ locale, departmentId }: AbsenceCalendarProps) {
  const t = useTranslations('hr.absences');
  const tAbsenceTypes = useTranslations('hr.absenceTypes');
  const dateLocale = locale === 'de' ? de : enUS;

  const [currentDate, setCurrentDate] = useState(new Date());
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth() + 1;

  const { data: entries, isLoading, error } = useAbsenceCalendar(year, month, departmentId);

  // Create a map of dates to absences for quick lookup
  const absenceMap = new Map<string, AbsenceCalendarEntry['absences']>();
  entries?.forEach((entry) => {
    absenceMap.set(entry.date, entry.absences);
  });

  // Generate calendar days
  const monthStart = startOfMonth(currentDate);
  const monthEnd = endOfMonth(currentDate);
  const calendarDays = eachDayOfInterval({ start: monthStart, end: monthEnd });

  // Get day offset for first day of month (0 = Sunday, 1 = Monday, etc.)
  const startDayOffset = getDay(monthStart);
  // Adjust for Monday start (German locale)
  const adjustedOffset = startDayOffset === 0 ? 6 : startDayOffset - 1;

  const goToPreviousMonth = () => setCurrentDate(subMonths(currentDate, 1));
  const goToNextMonth = () => setCurrentDate(addMonths(currentDate, 1));
  const goToToday = () => setCurrentDate(new Date());

  // Day names
  const dayNames = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
  const dayNamesEn = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

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

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>{t('teamCalendar')}</CardTitle>
            <CardDescription>
              {format(currentDate, 'MMMM yyyy', { locale: dateLocale })}
            </CardDescription>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={goToToday}>
              {t('today')}
            </Button>
            <Button variant="outline" size="icon" onClick={goToPreviousMonth}>
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button variant="outline" size="icon" onClick={goToNextMonth}>
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="grid grid-cols-7 gap-1">
            {[...Array(35)].map((_, i) => (
              <Skeleton key={i} className="h-20" />
            ))}
          </div>
        ) : (
          <TooltipProvider>
            <div className="grid grid-cols-7 gap-1">
              {/* Day headers */}
              {(locale === 'de' ? dayNames : dayNamesEn).map((day) => (
                <div
                  key={day}
                  className="p-2 text-center text-sm font-medium text-muted-foreground"
                >
                  {day}
                </div>
              ))}

              {/* Empty cells for offset */}
              {[...Array(adjustedOffset)].map((_, i) => (
                <div key={`empty-${i}`} className="p-2" />
              ))}

              {/* Calendar days */}
              {calendarDays.map((day) => {
                const dateStr = format(day, 'yyyy-MM-dd');
                const dayAbsences = absenceMap.get(dateStr) || [];
                const isToday = isSameDay(day, new Date());
                const isWeekendDay = isWeekend(day);

                return (
                  <CalendarDay
                    key={dateStr}
                    day={day}
                    absences={dayAbsences}
                    isToday={isToday}
                    isWeekend={isWeekendDay}
                    locale={locale}
                    t={t}
                  />
                );
              })}
            </div>
          </TooltipProvider>
        )}

        {/* Legend */}
        <div className="mt-6 flex flex-wrap gap-4 border-t pt-4">
          {Object.entries(ABSENCE_TYPE_INFO).map(([type, info]) => {
            const Icon = ABSENCE_ICONS[type as AbsenceType];
            return (
              <div key={type} className="flex items-center gap-1.5">
                <div className={cn('h-3 w-3 rounded', info.bgColor)} />
                <span className="text-xs text-muted-foreground">
                  {tAbsenceTypes(info.labelKey)}
                </span>
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}

interface CalendarDayProps {
  day: Date;
  absences: AbsenceCalendarEntry['absences'];
  isToday: boolean;
  isWeekend: boolean;
  locale: string;
  t: (key: string) => string;
}

function CalendarDay({ day, absences, isToday, isWeekend, locale, t }: CalendarDayProps) {
  const tAbsenceTypes = useTranslations('hr.absenceTypes');
  const hasAbsences = absences.length > 0;
  const maxDisplay = 2;
  const moreCount = absences.length - maxDisplay;

  return (
    <div
      className={cn(
        'min-h-[80px] rounded-lg border p-1.5 transition-colors',
        isToday && 'border-primary bg-primary/5',
        isWeekend && 'bg-muted/50',
        !hasAbsences && 'hover:bg-muted/30'
      )}
    >
      <div
        className={cn(
          'text-sm',
          isToday && 'font-bold text-primary',
          isWeekend && 'text-muted-foreground'
        )}
      >
        {format(day, 'd')}
      </div>

      <div className="mt-1 space-y-0.5">
        {absences.slice(0, maxDisplay).map((absence) => {
          const typeInfo = ABSENCE_TYPE_INFO[absence.type];
          const Icon = ABSENCE_ICONS[absence.type];

          return (
            <Tooltip key={absence.id}>
              <TooltipTrigger asChild>
                <div
                  className={cn(
                    'flex items-center gap-1 rounded px-1 py-0.5 text-[10px]',
                    typeInfo.bgColor,
                    typeInfo.color,
                    absence.isHalfDay && 'opacity-70'
                  )}
                >
                  <Icon className="h-2.5 w-2.5 flex-shrink-0" />
                  <span className="truncate">
                    {absence.employee.firstName[0]}. {absence.employee.lastName}
                  </span>
                </div>
              </TooltipTrigger>
              <TooltipContent>
                <div className="flex items-center gap-2">
                  <Avatar className="h-6 w-6">
                    <AvatarImage src={absence.employee.avatar || undefined} />
                    <AvatarFallback className="text-[10px]">
                      {absence.employee.firstName[0]}
                      {absence.employee.lastName[0]}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <p className="font-medium">
                      {absence.employee.firstName} {absence.employee.lastName}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {tAbsenceTypes(typeInfo.labelKey)}
                      {absence.isHalfDay && ` (${t('halfDay')})`}
                    </p>
                  </div>
                </div>
              </TooltipContent>
            </Tooltip>
          );
        })}

        {moreCount > 0 && (
          <div className="text-[10px] text-muted-foreground pl-1">
            +{moreCount} {t('more')}
          </div>
        )}
      </div>
    </div>
  );
}
