'use client';

import { useTranslations } from 'next-intl';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import Link from 'next/link';
import { Headphones, MessageCircle, AlertTriangle, Clock, MoreHorizontal } from 'lucide-react';

import { cn } from '@/lib/utils';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { WidgetContainer } from '../../widget-container';
import { useTickets, useTicketCounts } from '@/hooks/integrations';
import type { TicketPriority, TicketStatus } from '@/types/integrations';
import { useState } from 'react';

interface TicketsWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  maxItems?: number;
  className?: string;
}

/** Priority badge configuration */
const priorityConfig: Record<
  TicketPriority,
  { variant: 'default' | 'secondary' | 'destructive' | 'warning'; icon: typeof AlertTriangle }
> = {
  urgent: { variant: 'destructive', icon: AlertTriangle },
  high: { variant: 'warning', icon: AlertTriangle },
  medium: { variant: 'secondary', icon: Clock },
  low: { variant: 'default', icon: Clock },
};

/**
 * Tickets Widget - Displays open FreeScout tickets with priority
 */
export function TicketsWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  maxItems = 5,
  className,
}: TicketsWidgetProps) {
  const t = useTranslations('widgets.tickets');
  const [statusFilter, setStatusFilter] = useState<TicketStatus | 'all'>('open');
  const { data: tickets, isLoading } = useTickets({
    status: statusFilter === 'all' ? undefined : statusFilter,
    limit: maxItems,
  });
  const { data: counts } = useTicketCounts();
  const dateLocale = locale === 'de' ? de : enUS;

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={
        <div className="relative">
          <Headphones className="h-4 w-4 text-primary" />
          {counts && counts.open > 0 && (
            <span className="absolute -right-1 -top-1 flex h-3 w-3 items-center justify-center rounded-full bg-destructive text-[8px] text-white">
              {counts.open > 9 ? '9+' : counts.open}
            </span>
          )}
        </div>
      }
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      {/* Status Filter */}
      <div className="mb-3">
        <Select
          value={statusFilter}
          onValueChange={(value) => setStatusFilter(value as TicketStatus | 'all')}
        >
          <SelectTrigger className="h-8 text-sm">
            <SelectValue placeholder={t('filterStatus')} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t('status.all')}</SelectItem>
            <SelectItem value="open">{t('status.open')}</SelectItem>
            <SelectItem value="pending">{t('status.pending')}</SelectItem>
            <SelectItem value="resolved">{t('status.resolved')}</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <ScrollArea className="h-[180px] pr-2">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="space-y-2 rounded-lg border p-3">
                <Skeleton className="h-4 w-3/4" />
                <Skeleton className="h-3 w-1/2" />
              </div>
            ))}
          </div>
        ) : tickets && tickets.length > 0 ? (
          <div className="space-y-2">
            {tickets.map((ticket, index) => {
              const priority = priorityConfig[ticket.priority];
              const PriorityIcon = priority.icon;

              return (
                <motion.div
                  key={ticket.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.2, delay: index * 0.05 }}
                  className="rounded-lg border p-3 transition-colors hover:bg-muted/50"
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-muted-foreground">
                          #{ticket.number}
                        </span>
                        <Badge variant={priority.variant} className="gap-1">
                          <PriorityIcon className="h-3 w-3" />
                          {t(`priority.${ticket.priority}`)}
                        </Badge>
                      </div>
                      <p className="mt-1 truncate font-medium">{ticket.subject}</p>
                      <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
                        <span className="truncate">{ticket.customerName}</span>
                        <span className="flex items-center gap-1">
                          <MessageCircle className="h-3 w-3" />
                          {ticket.replyCount}
                        </span>
                      </div>
                      <p className="mt-1 text-xs text-muted-foreground">
                        {ticket.lastReplyAt
                          ? formatDistanceToNow(ticket.lastReplyAt, {
                              addSuffix: true,
                              locale: dateLocale,
                            })
                          : formatDistanceToNow(ticket.createdAt, {
                              addSuffix: true,
                              locale: dateLocale,
                            })}
                      </p>
                    </div>

                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0">
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem>{t('viewTicket')}</DropdownMenuItem>
                        <DropdownMenuItem>{t('reply')}</DropdownMenuItem>
                        <DropdownMenuItem>{t('assign')}</DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </motion.div>
              );
            })}
          </div>
        ) : (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {t('noTickets')}
          </div>
        )}
      </ScrollArea>

      {/* Footer link */}
      <div className="mt-3 border-t pt-3">
        <Button variant="ghost" size="sm" className="w-full" asChild>
          <Link href={`/${locale}/integrations/freescout`}>
            <Headphones className="mr-2 h-4 w-4" />
            {t('viewAll')}
          </Link>
        </Button>
      </div>
    </WidgetContainer>
  );
}
