import { useEffect, useState, type FormEvent } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft, Send } from 'lucide-react';
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 { Toggle } from '@/components/ui/Toggle';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { adminAPI } from '@/api/client';
import { cn } from '@/lib/cn';
import { motion } from 'framer-motion';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function TicketManage() {
  const { id } = useParams<{ id: string }>();
  const { toast } = useToast();
  const [ticket, setTicket] = useState<any>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [reply, setReply] = useState('');
  const [isInternal, setIsInternal] = useState(false);
  const [sending, setSending] = useState(false);

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

  async function handleReply(e: FormEvent) {
    e.preventDefault();
    if (!reply.trim() || !id) return;
    setSending(true);
    try {
      const { data } = await adminAPI.replyTicket(id, { content: reply, is_internal: isInternal });
      setMessages((prev) => [...prev, data.message]);
      setReply('');
      toast(isInternal ? 'Internal note added' : 'Reply sent', 'success');
    } catch {
      toast('Failed to send reply', 'error');
    } finally {
      setSending(false);
    }
  }

  async function handleClose() {
    if (!id) return;
    try {
      await adminAPI.closeTicket(id, { resolution: 'Resolved by staff' });
      setTicket((prev: any) => ({ ...prev, status: 'closed' }));
      toast('Ticket closed', 'success');
    } catch {
      toast('Failed to close ticket', 'error');
    }
  }

  if (loading) return <div className="p-6 space-y-4"><SkeletonCard /><SkeletonCard /></div>;
  if (!ticket) return <div className="p-6 text-text-muted">Ticket not found.</div>;

  return (
    <div className="p-6 max-w-3xl">
      <Link to="/admin/tickets" className="inline-flex items-center gap-1.5 text-sm text-text-muted hover:text-text-secondary transition-colors mb-6">
        <ArrowLeft className="w-4 h-4" /> Back to Tickets
      </Link>

      <Card className="mb-6">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h1 className="text-lg font-bold text-text-primary mb-1">{ticket.subject}</h1>
            <p className="text-xs text-text-muted">
              by {ticket.user_name} · {ticket.category?.replace('_', ' ')}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant={ticket.status === 'closed' ? 'default' : 'warning'}>{ticket.status?.replace('_', ' ')}</Badge>
            {ticket.status !== 'closed' && (
              <Button variant="secondary" size="sm" onClick={handleClose}>Close</Button>
            )}
          </div>
        </div>
      </Card>

      <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-3 mb-6">
        {messages.map((msg) => (
          <motion.div key={msg.id} variants={staggerItem}>
            <div className={cn(
              'flex gap-3 px-4 py-3 rounded-xl border',
              msg.is_internal ? 'bg-amber-500/5 border-amber-500/20' : 'bg-bg-elevated border-white/[0.06]'
            )}>
              <Avatar src={msg.author_avatar} username={msg.author_name || 'User'} size="sm" className="mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-medium text-text-secondary">{msg.author_name}</span>
                  {msg.is_internal && <Badge variant="warning">Internal</Badge>}
                  {msg.is_staff && <Badge variant="info">Staff</Badge>}
                  <span className="text-[10px] text-text-muted">
                    {msg.created_at ? new Date(msg.created_at).toLocaleString() : ''}
                  </span>
                </div>
                <p className="text-sm text-text-primary">{msg.content}</p>
              </div>
            </div>
          </motion.div>
        ))}
      </motion.div>

      {ticket.status !== 'closed' && (
        <form onSubmit={handleReply} className="space-y-3">
          <textarea
            value={reply}
            onChange={(e) => setReply(e.target.value)}
            rows={3}
            placeholder={isInternal ? 'Add internal note...' : 'Type your reply...'}
            className="w-full px-4 py-3 bg-bg-elevated border border-white/10 rounded-xl text-text-primary text-sm resize-none focus:border-amber-500 outline-none transition-all"
          />
          <div className="flex items-center justify-between">
            <Toggle checked={isInternal} onChange={setIsInternal} label="Internal note (hidden from user)" />
            <Button type="submit" loading={sending}>
              <Send className="w-4 h-4" /> {isInternal ? 'Add Note' : 'Send Reply'}
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}
