'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { format, parseISO } from 'date-fns';
import { de, enUS, type Locale } from 'date-fns/locale';
import {
  CheckCircle,
  XCircle,
  Calendar,
  Clock,
  AlertCircle,
  Inbox,
  User,
} 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 { ScrollArea } from '@/components/ui/scroll-area';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  usePendingAbsenceRequests,
  useApproveAbsence,
  useRejectAbsence,
} from '@/hooks/hr/use-absences';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import type { Absence } from '@/types/hr';
import { ABSENCE_TYPE_INFO } from '@/types/hr';

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

/**
 * List of pending absence requests for managers to approve/reject
 */
export function AbsenceApprovalList({ locale, departmentId }: AbsenceApprovalListProps) {
  const t = useTranslations('hr.absences');
  const tAbsenceTypes = useTranslations('hr.absenceTypes');
  const tCommon = useTranslations('common');
  const { toast } = useToast();
  const dateLocale = locale === 'de' ? de : enUS;

  const { data: requests, isLoading, error } = usePendingAbsenceRequests(departmentId);
  const approveAbsence = useApproveAbsence();
  const rejectAbsence = useRejectAbsence();

  // Rejection dialog state
  const [rejectDialog, setRejectDialog] = useState<{ open: boolean; absenceId: string | null }>({
    open: false,
    absenceId: null,
  });
  const [rejectionReason, setRejectionReason] = useState('');

  const handleApprove = async (id: string) => {
    try {
      await approveAbsence.mutateAsync(id);
      toast({
        title: t('approved'),
        description: t('approvedDesc'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorApprove'),
        variant: 'destructive',
      });
    }
  };

  const handleReject = async () => {
    if (!rejectDialog.absenceId) return;

    try {
      await rejectAbsence.mutateAsync({
        id: rejectDialog.absenceId,
        reason: rejectionReason,
      });
      toast({
        title: t('rejected'),
        description: t('rejectedDesc'),
      });
      setRejectDialog({ open: false, absenceId: null });
      setRejectionReason('');
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorReject'),
        variant: 'destructive',
      });
    }
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-40" />
          <Skeleton className="h-4 w-60" />
        </CardHeader>
        <CardContent className="space-y-3">
          {[1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-24 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('errorLoadingRequests')}</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Clock className="h-5 w-5" />
                {t('pendingApprovals')}
              </CardTitle>
              <CardDescription>{t('pendingApprovalsDesc')}</CardDescription>
            </div>
            {requests && requests.length > 0 && (
              <Badge variant="secondary">{requests.length}</Badge>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {!requests || requests.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <Inbox className="h-10 w-10 text-muted-foreground/50" />
              <p className="mt-4 text-muted-foreground">{t('noRequests')}</p>
            </div>
          ) : (
            <ScrollArea className="h-[400px] pr-4">
              <div className="space-y-3">
                {requests.map((request) => (
                  <ApprovalItem
                    key={request.id}
                    request={request}
                    locale={locale}
                    dateLocale={dateLocale}
                    onApprove={handleApprove}
                    onReject={(id) => setRejectDialog({ open: true, absenceId: id })}
                    isProcessing={approveAbsence.isPending || rejectAbsence.isPending}
                    t={t}
                  />
                ))}
              </div>
            </ScrollArea>
          )}
        </CardContent>
      </Card>

      {/* Rejection Dialog */}
      <Dialog open={rejectDialog.open} onOpenChange={(open) => {
        if (!open) {
          setRejectDialog({ open: false, absenceId: null });
          setRejectionReason('');
        }
      }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t('rejectRequest')}</DialogTitle>
            <DialogDescription>{t('rejectRequestDesc')}</DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <Label htmlFor="reason">{t('rejectionReason')}</Label>
            <Textarea
              id="reason"
              placeholder={t('rejectionReasonPlaceholder')}
              value={rejectionReason}
              onChange={(e) => setRejectionReason(e.target.value)}
              rows={3}
            />
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setRejectDialog({ open: false, absenceId: null });
                setRejectionReason('');
              }}
              disabled={rejectAbsence.isPending}
            >
              {tCommon('cancel')}
            </Button>
            <Button
              variant="destructive"
              onClick={handleReject}
              disabled={rejectAbsence.isPending}
            >
              {t('reject')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

interface ApprovalItemProps {
  request: Absence;
  locale: string;
  dateLocale: Locale;
  onApprove: (id: string) => void;
  onReject: (id: string) => void;
  isProcessing: boolean;
  t: (key: string) => string;
}

function ApprovalItem({
  request,
  locale,
  dateLocale,
  onApprove,
  onReject,
  isProcessing,
  t,
}: ApprovalItemProps) {
  const tAbsenceTypes = useTranslations('hr.absenceTypes');
  const typeInfo = ABSENCE_TYPE_INFO[request.type];
  const startDate = parseISO(request.startDate);
  const endDate = parseISO(request.endDate);
  const isSameDay = request.startDate === request.endDate;

  return (
    <div className="rounded-lg border p-4">
      <div className="flex items-start gap-4">
        {/* Employee info */}
        <Avatar className="h-10 w-10">
          <AvatarImage src={request.employee.avatarUrl} />
          <AvatarFallback>
            {request.employee.firstName[0]}
            {request.employee.lastName[0]}
          </AvatarFallback>
        </Avatar>

        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <div>
              <h4 className="font-medium">
                {request.employee.firstName} {request.employee.lastName}
              </h4>
              <Badge className={cn(typeInfo.bgColor, typeInfo.color, 'mt-1')} variant="secondary">
                {tAbsenceTypes(typeInfo.labelKey)}
              </Badge>
            </div>
            <span className="text-xl font-bold">{request.days}</span>
          </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 })}
                {request.halfDay && (
                  <span className="ml-1">
                    ({request.halfDayPeriod === 'MORNING' ? t('morning') : t('afternoon')})
                  </span>
                )}
              </span>
            ) : (
              <span>
                {format(startDate, 'PPP', { locale: dateLocale })} -{' '}
                {format(endDate, 'PPP', { locale: dateLocale })}
              </span>
            )}
          </div>

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

          {/* Action buttons */}
          <div className="flex items-center gap-2 mt-3">
            <Button
              size="sm"
              onClick={() => onApprove(request.id)}
              disabled={isProcessing}
              className="gap-1"
            >
              <CheckCircle className="h-4 w-4" />
              {t('approve')}
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => onReject(request.id)}
              disabled={isProcessing}
              className="gap-1 text-destructive hover:text-destructive"
            >
              <XCircle className="h-4 w-4" />
              {t('reject')}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
