import { useEffect, useState, useRef, type FormEvent } from 'react';
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ArrowLeft, Send, Lock, MessageCircle } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { Avatar } from '@/components/ui/Avatar';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { supportAPI } from '@/api/client';
import { useAuthStore } from '@/stores/authStore';
import { cn } from '@/lib/cn';
import { staggerContainer, staggerItem } from '@/lib/animations';

const statusVariants: Record<string, 'success' | 'warning' | 'info' | 'default'> = {
  open: 'warning',
  assigned: 'info',
  in_progress: 'info',
  waiting_on_user: 'warning',
  reopened: 'warning',
  resolved: 'success',
  closed: 'default',
};

export default function TicketDetail() {
  const { id } = useParams<{ id: string }>();
  const user = useAuthStore((s) => s.user);
  const { toast } = useToast();
  const [ticket, setTicket] = useState<any>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [reply, setReply] = useState('');
  const [sending, setSending] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!id) return;
    supportAPI.getTicket(id)
      .then(({ data }) => {
        setTicket(data.ticket);
        setMessages(data.messages || []);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [id]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  async function handleSendReply(e: FormEvent) {
    e.preventDefault();
    if (!reply.trim() || !id) return;
    setSending(true);
    try {
      const { data } = await supportAPI.addMessage(id, { content: reply.trim() });
      const newMsg = data.message || data;
      setMessages((prev) => [...prev, newMsg]);
      setReply('');
      toast('Reply sent', 'success');
    } catch (err: any) {
      const msg = err.response?.data?.error || 'Failed to send reply';
      toast(msg, 'error');
    } finally {
      setSending(false);
    }
  }

  if (loading) {
    return (
      <PageTransition className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-4">
        <SkeletonCard />
        <SkeletonCard />
        <SkeletonCard />
      </PageTransition>
    );
  }

  if (!ticket) {
    return (
      <PageTransition className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-16 text-center">
        <h2 className="text-xl font-bold text-[#f0f0f5] mb-2">Ticket not found</h2>
        <p className="text-[#a0a0b8] mb-6">This ticket doesn't exist or you don't have access.</p>
        <Link to="/support" className="text-[#ff6b2c] hover:text-[#ff8a50] transition-colors text-sm">
          Back to Support
        </Link>
      </PageTransition>
    );
  }

  const isClosed = ticket.status === 'closed' || ticket.status === 'resolved';
  const statusVariant = statusVariants[ticket.status] || 'default';
  const statusLabel = (ticket.status || '').replace(/_/g, ' ');

  return (
    <PageTransition className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <motion.div
        initial={{ opacity: 0, x: -8 }}
        animate={{ opacity: 1, x: 0 }}
      >
        <Link to="/support" className="inline-flex items-center gap-1.5 text-sm text-[#5a5a72] hover:text-[#a0a0b8] transition-colors mb-6">
          <ArrowLeft className="w-4 h-4" /> Back to Tickets
        </Link>
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
      >
        <Card className="mb-6 relative overflow-hidden">
          <div className={cn(
            'absolute top-0 left-0 right-0 h-0.5',
            isClosed ? 'bg-[#1e1e30]' : 'bg-[#ff6b2c]/50'
          )} />
          <div className="flex items-start justify-between gap-4 mb-3">
            <h1 className="text-lg font-bold text-[#f0f0f5]">{ticket.subject || ticket.Subject}</h1>
            <Badge variant={statusVariant} className="capitalize flex-shrink-0">
              {statusLabel}
            </Badge>
          </div>
          <div className="flex items-center gap-2 text-xs text-[#5a5a72]">
            <span className="capitalize">{(ticket.category || '').replace(/_/g, ' ')}</span>
            <span>&middot;</span>
            <span>
              Created {ticket.created_at ? new Date(ticket.created_at).toLocaleDateString() : ''}
            </span>
          </div>
        </Card>
      </motion.div>

      <motion.div
        variants={staggerContainer}
        initial="initial"
        animate="animate"
        className="space-y-4 mb-6"
      >
        {messages.length === 0 && (
          <motion.div variants={staggerItem}>
            <Card className="text-center py-8">
              <MessageCircle className="w-10 h-10 text-[#5a5a72]/20 mx-auto mb-3" />
              <p className="text-sm text-[#5a5a72]">No messages yet. Start the conversation below.</p>
            </Card>
          </motion.div>
        )}

        {messages.map((msg) => {
          const isStaff = msg.is_staff || msg.IsStaff;
          const authorId = msg.author_id || msg.AuthorID;
          const isSelf = authorId === user?.id;
          const authorName = msg.author_name || msg.author?.username || msg.Author?.Username || 'User';
          const authorAvatar = msg.author_avatar || msg.author?.steam_avatar_url || msg.Author?.SteamAvatarURL;
          const createdAt = msg.created_at || msg.CreatedAt;

          return (
            <motion.div key={msg.id || msg.ID} variants={staggerItem}>
              <div className={cn('flex gap-3', isSelf && !isStaff && 'flex-row-reverse')}>
                <Avatar
                  src={authorAvatar}
                  username={authorName}
                  size="sm"
                  className="mt-1 flex-shrink-0"
                />
                <div className={cn('max-w-[80%] min-w-0', isSelf && !isStaff && 'items-end')}>
                  <div className={cn(
                    'flex items-center gap-2 mb-1',
                    isSelf && !isStaff && 'flex-row-reverse'
                  )}>
                    <span className={cn(
                      'text-xs font-medium',
                      isStaff ? 'text-[#ff8a50]' : 'text-[#a0a0b8]'
                    )}>
                      {authorName}
                      {isStaff && (
                        <span className="ml-1 text-[10px] text-[#ff6b2c]/70">(Staff)</span>
                      )}
                    </span>
                    <span className="text-[10px] text-[#5a5a72]">
                      {createdAt ? new Date(createdAt).toLocaleString() : ''}
                    </span>
                  </div>
                  <div className={cn(
                    'px-4 py-3 rounded-2xl text-sm leading-relaxed',
                    isStaff
                      ? 'bg-[#ff6b2c]/[0.06] border border-[#ff6b2c]/10 text-[#f0f0f5] rounded-tl-md'
                      : isSelf
                        ? 'bg-[#1e1e30] border border-[#1e1e30] text-[#f0f0f5] rounded-tr-md'
                        : 'bg-bg-elevated border border-[#1e1e30] text-[#a0a0b8] rounded-tl-md'
                  )}>
                    <p className="whitespace-pre-wrap break-words">{msg.content || msg.Content}</p>
                  </div>
                </div>
              </div>
            </motion.div>
          );
        })}
        <div ref={messagesEndRef} />
      </motion.div>

      {!isClosed ? (
        <motion.form
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          onSubmit={handleSendReply}
          className="flex gap-3"
        >
          <textarea
            value={reply}
            onChange={(e) => setReply(e.target.value)}
            rows={2}
            placeholder="Type your reply..."
            className="flex-1 px-4 py-3 bg-bg-elevated border border-[#1e1e30] rounded-xl text-[#f0f0f5] text-sm resize-none focus:border-[#ff6b2c] focus:shadow-[0_0_0_3px_rgba(255,107,44,0.15)] outline-none transition-all placeholder:text-[#5a5a72]"
          />
          <Button
            type="submit"
            loading={sending}
            disabled={!reply.trim()}
            className="self-end"
          >
            <Send className="w-4 h-4" />
          </Button>
        </motion.form>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
        >
          <Card className="text-center py-4">
            <div className="flex items-center justify-center gap-2">
              <Lock className="w-4 h-4 text-[#5a5a72]" />
              <p className="text-sm text-[#5a5a72]">This ticket is {ticket.status === 'resolved' ? 'resolved' : 'closed'}.</p>
            </div>
          </Card>
        </motion.div>
      )}
    </PageTransition>
  );
}
