'use client';

import { useTranslations } from 'next-intl';
import { format, parseISO } from 'date-fns';
import { de, enUS, type Locale } from 'date-fns/locale';
import {
  Clock,
  Coffee,
  AlertCircle,
  CheckCircle2,
  Edit2,
  MoreVertical,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useTimeEntries } from '@/hooks/hr/use-time-tracking';
import { cn } from '@/lib/utils';
import type { TimeEntry, TimeEntryType } from '@/types/hr';

interface TimeEntryListProps {
  locale: string;
  employeeId?: string;
  limit?: number;
  onEditEntry?: (entry: TimeEntry) => void;
}

/**
 * List of time entries with duration, breaks, and status
 */
export function TimeEntryList({
  locale,
  employeeId,
  limit = 10,
  onEditEntry,
}: TimeEntryListProps) {
  const t = useTranslations('hr.timeTracking');

  const { data: entries, isLoading, error } = useTimeEntries({ employeeId, limit });
  const dateLocale = locale === 'de' ? de : enUS;

  // Format duration from minutes
  const formatDuration = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${hours}h ${mins}m`;
  };

  // Get type badge
  const getTypeBadge = (type: TimeEntryType) => {
    switch (type) {
      case 'REGULAR':
        return null;
      case 'OVERTIME':
        return (
          <Badge variant="secondary" className="bg-blue-100 text-blue-700">
            {t('overtime')}
          </Badge>
        );
      case 'CORRECTION':
        return (
          <Badge variant="secondary" className="bg-yellow-100 text-yellow-700">
            {t('corrected')}
          </Badge>
        );
    }
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-32" />
          <Skeleton className="h-4 w-48" />
        </CardHeader>
        <CardContent className="space-y-3">
          {[1, 2, 3, 4, 5].map((i) => (
            <Skeleton key={i} className="h-16 w-full" />
          ))}
        </CardContent>
      </Card>
    );
  }

  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('errorLoadingEntries')}</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Clock className="h-5 w-5" />
          {t('recentEntries')}
        </CardTitle>
        <CardDescription>{t('recentEntriesDesc')}</CardDescription>
      </CardHeader>
      <CardContent>
        {!entries || entries.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-8 text-center">
            <Clock className="h-10 w-10 text-muted-foreground/50" />
            <p className="mt-4 text-muted-foreground">{t('noEntries')}</p>
          </div>
        ) : (
          <ScrollArea className="h-[400px] pr-4">
            <div className="space-y-3">
              {entries.map((entry) => (
                <TimeEntryItem
                  key={entry.id}
                  entry={entry}
                  locale={locale}
                  dateLocale={dateLocale}
                  formatDuration={formatDuration}
                  getTypeBadge={getTypeBadge}
                  onEdit={onEditEntry}
                  t={t}
                />
              ))}
            </div>
          </ScrollArea>
        )}
      </CardContent>
    </Card>
  );
}

interface TimeEntryItemProps {
  entry: TimeEntry;
  locale: string;
  dateLocale: Locale;
  formatDuration: (minutes: number) => string;
  getTypeBadge: (type: TimeEntryType) => React.ReactNode;
  onEdit?: (entry: TimeEntry) => void;
  t: (key: string) => string;
}

function TimeEntryItem({
  entry,
  locale,
  dateLocale,
  formatDuration,
  getTypeBadge,
  onEdit,
  t,
}: TimeEntryItemProps) {
  const date = parseISO(entry.date);

  return (
    <div
      className={cn(
        'flex items-center justify-between rounded-lg border p-4',
        !entry.isApproved && 'border-yellow-300 bg-yellow-50 dark:bg-yellow-950/20'
      )}
    >
      <div className="space-y-1">
        <div className="flex items-center gap-2">
          <span className="font-medium">
            {format(date, 'EEEE, d. MMM', { locale: dateLocale })}
          </span>
          {getTypeBadge(entry.type)}
          {!entry.isApproved && (
            <Badge variant="outline" className="text-yellow-600">
              {t('pendingApproval')}
            </Badge>
          )}
        </div>
        <div className="flex items-center gap-4 text-sm text-muted-foreground">
          <span className="flex items-center gap-1">
            <Clock className="h-3 w-3" />
            {entry.clockIn || '--:--'} - {entry.clockOut || '--:--'}
          </span>
          {entry.totalBreakMinutes > 0 && (
            <span className="flex items-center gap-1">
              <Coffee className="h-3 w-3" />
              {entry.totalBreakMinutes}m {t('break')}
            </span>
          )}
        </div>
      </div>

      <div className="flex items-center gap-4">
        <div className="text-right">
          <p className="font-semibold tabular-nums">
            {formatDuration(entry.totalWorkMinutes)}
          </p>
          {entry.overtimeMinutes > 0 && (
            <p className="text-xs text-blue-600">
              +{formatDuration(entry.overtimeMinutes)} {t('overtime')}
            </p>
          )}
        </div>

        <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 onClick={() => onEdit?.(entry)}>
              <Edit2 className="mr-2 h-4 w-4" />
              {t('requestCorrection')}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </div>
  );
}
