import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { MessageSquare } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { SkeletonRow } from '@/components/ui/Skeleton';
import { adminAPI } from '@/api/client';
import { useToast } from '@/components/ui/Toast';
import { formatRelativeTime } from '@/lib/constants';
import { cn } from '@/lib/cn';
import { staggerContainer, staggerItem } from '@/lib/animations';

const priorityColors = ['', 'danger', 'warning', 'info', 'default'] as const;
const priorityLabels = ['', 'Critical', 'High', 'Medium', 'Low'];

export default function TicketQueue() {
  const { toast } = useToast();
  const [tickets, setTickets] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminAPI.getTickets().then(({ data }) => {
      setTickets(data.tickets || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, []);

  async function handleAssign(ticketId: string) {
    try {
      await adminAPI.assignTicket(ticketId);
      toast('Ticket assigned to you', 'success');
      setTickets((prev) => prev.map((t) => t.id === ticketId ? { ...t, status: 'assigned' } : t));
    } catch {
      toast('Failed to assign ticket', 'error');
    }
  }

  return (
    <div className="p-6">
      <h1 className="text-xl font-bold text-text-primary mb-6">Support Tickets</h1>

      {loading ? (
        <div className="space-y-3">{[...Array(5)].map((_, i) => <SkeletonRow key={i} />)}</div>
      ) : tickets.length > 0 ? (
        <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-2">
          {tickets.map((ticket) => (
            <motion.div key={ticket.id} variants={staggerItem}>
              <Card variant="interactive" className="flex items-center gap-4">
                <MessageSquare className="w-5 h-5 text-text-muted flex-shrink-0" />
                <div className="flex-1 min-w-0">
                  <Link to={`/admin/tickets/${ticket.id}`} className="text-sm font-medium text-text-primary hover:text-amber-400 transition-colors truncate block">
                    {ticket.subject}
                  </Link>
                  <p className="text-xs text-text-muted">by {ticket.user_name} · {ticket.category?.replace('_', ' ')}</p>
                </div>
                <Badge variant={(priorityColors[ticket.priority] as any) || 'default'}>
                  {priorityLabels[ticket.priority] || 'Unknown'}
                </Badge>
                <Badge variant={ticket.status === 'assigned' ? 'info' : 'warning'}>
                  {ticket.status?.replace('_', ' ')}
                </Badge>
                {ticket.status === 'open' && (
                  <Button variant="secondary" size="sm" onClick={() => handleAssign(ticket.id)}>
                    Assign
                  </Button>
                )}
                <span className="text-xs text-text-muted flex-shrink-0">
                  {ticket.created_at ? formatRelativeTime(ticket.created_at) : ''}
                </span>
              </Card>
            </motion.div>
          ))}
        </motion.div>
      ) : (
        <Card className="text-center py-12">
          <MessageSquare className="w-12 h-12 text-text-muted/20 mx-auto mb-3" />
          <p className="text-text-secondary">No open tickets</p>
        </Card>
      )}
    </div>
  );
}
