'use client';

import { useTranslations } from 'next-intl';
import { format, parseISO } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  Palmtree,
  Thermometer,
  Home,
  Star,
  CalendarOff,
  GraduationCap,
  Calendar,
  User,
  MoreVertical,
  X,
  CheckCircle2,
  XCircle,
  Clock,
  Baby,
  Heart,
  Plane,
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
import type { Absence, AbsenceType, AbsenceRequestStatus } from '@/types/hr';
import { ABSENCE_TYPE_INFO, ABSENCE_STATUS_INFO } from '@/types/hr';

interface AbsenceCardProps {
  absence: Absence;
  locale: string;
  onCancel?: (id: string) => void;
  showEmployee?: boolean;
}

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,
};

/**
 * Card displaying a single absence request with status
 */
export function AbsenceCard({
  absence,
  locale,
  onCancel,
  showEmployee = false,
}: AbsenceCardProps) {
  const t = useTranslations('hr.absences');
  const tAbsenceTypes = useTranslations('hr.absenceTypes');
  const tAbsenceStatus = useTranslations('hr.absenceStatus');
  const dateLocale = locale === 'de' ? de : enUS;

  const typeInfo = ABSENCE_TYPE_INFO[absence.type];
  const statusInfo = ABSENCE_STATUS_INFO[absence.status];
  const Icon = ABSENCE_ICONS[absence.type];

  const startDate = parseISO(absence.startDate);
  const endDate = parseISO(absence.endDate);
  const isSameDay = absence.startDate === absence.endDate;

  // Get status icon
  const StatusIcon =
    absence.status === 'APPROVED'
      ? CheckCircle2
      : absence.status === 'REJECTED'
        ? XCircle
        : absence.status === 'PENDING'
          ? Clock
          : X;

  return (
    <Card
      className={cn(
        'overflow-hidden',
        absence.status === 'PENDING' && 'border-yellow-300',
        absence.status === 'REJECTED' && 'border-red-300 bg-red-50/50 dark:bg-red-950/10',
        absence.status === 'CANCELLED' && 'opacity-60'
      )}
    >
      <CardContent className="p-4">
        <div className="flex items-start gap-4">
          {/* Type icon */}
          <div
            className={cn(
              'flex h-10 w-10 items-center justify-center rounded-lg',
              typeInfo.bgColor
            )}
          >
            <Icon className={cn('h-5 w-5', typeInfo.color)} />
          </div>

          {/* Content */}
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between gap-2">
              <div>
                <h4 className="font-medium">
                  {tAbsenceTypes(typeInfo.labelKey)}
                </h4>
                {showEmployee && (
                  <div className="flex items-center gap-2 mt-1">
                    <Avatar className="h-5 w-5">
                      <AvatarImage src={absence.employee.avatarUrl} />
                      <AvatarFallback className="text-[10px]">
                        {absence.employee.firstName[0]}
                        {absence.employee.lastName[0]}
                      </AvatarFallback>
                    </Avatar>
                    <span className="text-sm text-muted-foreground">
                      {absence.employee.firstName} {absence.employee.lastName}
                    </span>
                  </div>
                )}
              </div>

              <div className="flex items-center gap-2">
                <Badge
                  className={cn(statusInfo.bgColor, statusInfo.color, 'gap-1')}
                  variant="secondary"
                >
                  <StatusIcon className="h-3 w-3" />
                  {tAbsenceStatus(statusInfo.labelKey)}
                </Badge>

                {absence.status === 'PENDING' && onCancel && (
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-8 w-8">
                        <MoreVertical className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem
                        className="text-destructive"
                        onClick={() => onCancel(absence.id)}
                      >
                        <X className="mr-2 h-4 w-4" />
                        {t('cancel')}
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                )}
              </div>
            </div>

            {/* Date range */}
            <div className="flex items-center gap-2 mt-2 text-sm text-muted-foreground">
              <Calendar className="h-4 w-4" />
              {isSameDay ? (
                <span>
                  {format(startDate, 'PPP', { locale: dateLocale })}
                  {absence.halfDay && (
                    <span className="ml-1">
                      ({absence.halfDayPeriod === 'MORNING' ? t('morning') : t('afternoon')})
                    </span>
                  )}
                </span>
              ) : (
                <span>
                  {format(startDate, 'PPP', { locale: dateLocale })} -{' '}
                  {format(endDate, 'PPP', { locale: dateLocale })}
                </span>
              )}
            </div>

            {/* Days count */}
            <div className="mt-1 text-sm">
              <span className="font-medium">{absence.days}</span>{' '}
              <span className="text-muted-foreground">
                {absence.days === 1 ? t('day') : t('days')}
              </span>
            </div>

            {/* Note */}
            {absence.note && (
              <p className="mt-2 text-sm text-muted-foreground line-clamp-2">
                {absence.note}
              </p>
            )}

            {/* Rejection reason */}
            {absence.status === 'REJECTED' && absence.rejectionReason && (
              <div className="mt-2 rounded-md bg-red-100 dark:bg-red-950/30 p-2">
                <p className="text-sm text-red-700 dark:text-red-300">
                  <span className="font-medium">{t('rejectionReason')}:</span>{' '}
                  {absence.rejectionReason}
                </p>
              </div>
            )}

            {/* Approval info */}
            {absence.status === 'APPROVED' && absence.approvedBy && (
              <p className="mt-2 text-xs text-muted-foreground">
                {t('approvedBy')} {absence.approvedBy.firstName} {absence.approvedBy.lastName}
              </p>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
