import { useEffect, useState, type FormEvent } from 'react';
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Plus, MessageSquare, CheckCircle, HelpCircle, ArrowRight } 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 { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { Modal } from '@/components/ui/Modal';
import { SkeletonRow } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { supportAPI } from '@/api/client';
import { TICKET_CATEGORIES } from '@/lib/constants';
import { cn } from '@/lib/cn';
import { formatRelativeTime } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

const statusBadges: Record<string, { variant: 'success' | 'warning' | 'info' | 'default'; label: string }> = {
  open: { variant: 'warning', label: 'Open' },
  assigned: { variant: 'info', label: 'Assigned' },
  in_progress: { variant: 'info', label: 'In Progress' },
  waiting_on_user: { variant: 'warning', label: 'Awaiting Reply' },
  reopened: { variant: 'warning', label: 'Reopened' },
  resolved: { variant: 'success', label: 'Resolved' },
  closed: { variant: 'default', label: 'Closed' },
};

export default function Support() {
  const { toast } = useToast();
  const [tickets, setTickets] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [createModal, setCreateModal] = useState(false);
  const [category, setCategory] = useState('bug_report');
  const [subject, setSubject] = useState('');
  const [body, setBody] = useState('');
  const [submitting, setSubmitting] = useState(false);

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

  async function handleCreateTicket(e: FormEvent) {
    e.preventDefault();
    if (!subject.trim()) {
      toast('Please enter a subject', 'warning');
      return;
    }
    if (subject.trim().length < 5) {
      toast('Subject must be at least 5 characters', 'warning');
      return;
    }
    if (!body.trim() || body.trim().length < 10) {
      toast('Message must be at least 10 characters', 'warning');
      return;
    }
    setSubmitting(true);
    try {
      const { data } = await supportAPI.createTicket({ category, subject: subject.trim(), body: body.trim() });
      const newTicket = data.ticket || data;
      setTickets((prev) => [newTicket, ...prev]);
      setCreateModal(false);
      setSubject('');
      setBody('');
      toast('Ticket created successfully', 'success');
    } catch (err: any) {
      const msg = err.response?.data?.error || 'Failed to create ticket';
      toast(msg, 'error');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <PageTransition className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex items-center justify-between mb-8">
        <div>
          <motion.h1
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-2xl sm:text-3xl font-extrabold text-[#f0f0f5] tracking-tight"
          >
            Support
          </motion.h1>
          <motion.p
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.05 }}
            className="text-sm text-[#a0a0b8] mt-1"
          >
            Need help? Create a ticket and we'll get back to you
          </motion.p>
        </div>
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.1 }}
        >
          <Button onClick={() => setCreateModal(true)}>
            <Plus className="w-4 h-4" /> New Ticket
          </Button>
        </motion.div>
      </div>

      {loading ? (
        <div className="space-y-3">
          {[...Array(4)].map((_, i) => <SkeletonRow key={i} />)}
        </div>
      ) : tickets.length > 0 ? (
        <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-2">
          {tickets.map((ticket) => {
            const statusInfo = statusBadges[ticket.status] || statusBadges.open;
            return (
              <motion.div key={ticket.id || ticket.ID} variants={staggerItem}>
                <Link to={`/support/${ticket.id || ticket.ID}`}>
                  <Card variant="interactive" className="flex items-center gap-4 group">
                    <div className="w-9 h-9 rounded-lg bg-[#0f0f18] border border-[#1e1e30] flex items-center justify-center flex-shrink-0">
                      <MessageSquare className="w-4 h-4 text-[#5a5a72]" />
                    </div>

                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-[#f0f0f5] truncate group-hover:text-[#ff8a50] transition-colors">
                        {ticket.subject || ticket.Subject}
                      </p>
                      <p className="text-xs text-[#5a5a72] capitalize">
                        {(ticket.category || ticket.Category || '').replace(/_/g, ' ')}
                      </p>
                    </div>

                    <Badge variant={statusInfo.variant}>{statusInfo.label}</Badge>

                    <span className="text-xs text-[#5a5a72] flex-shrink-0 hidden sm:block">
                      {ticket.updated_at ? formatRelativeTime(ticket.updated_at) : ''}
                    </span>

                    <ArrowRight className="w-4 h-4 text-[#5a5a72] opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
                  </Card>
                </Link>
              </motion.div>
            );
          })}
        </motion.div>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >
          <Card className="text-center py-16">
            <motion.div
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ delay: 0.3, type: 'spring', stiffness: 200 }}
            >
              <CheckCircle className="w-14 h-14 text-emerald-500/20 mx-auto mb-4" />
            </motion.div>
            <h3 className="text-lg font-semibold text-[#f0f0f5] mb-1">No tickets</h3>
            <p className="text-sm text-[#a0a0b8] mb-6">
              You haven't created any support tickets yet. Need help?
            </p>
            <Button onClick={() => setCreateModal(true)}>
              <HelpCircle className="w-4 h-4" /> Create a Ticket
            </Button>
          </Card>
        </motion.div>
      )}

      <Modal open={createModal} onClose={() => setCreateModal(false)} title="Create Support Ticket" maxWidth="max-w-xl">
        <form onSubmit={handleCreateTicket} className="space-y-4">
          <Select
            label="Category"
            value={category}
            onChange={setCategory}
            options={TICKET_CATEGORIES.map((c) => ({ value: c.id, label: c.name }))}
          />
          <Input
            label="Subject"
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
          />
          <div>
            <label className="block text-[11px] text-[#5a5a72] font-medium mb-1.5 uppercase tracking-wider">
              Message
            </label>
            <textarea
              value={body}
              onChange={(e) => setBody(e.target.value)}
              rows={5}
              className="w-full px-4 py-3 bg-bg-elevated border border-[#1e1e30] rounded-lg 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]"
              placeholder="Describe your issue in detail..."
            />
            <p className="text-[10px] text-[#5a5a72] mt-1">
              {body.length < 10 ? `${10 - body.length} more character${10 - body.length !== 1 ? 's' : ''} needed` : ''}
            </p>
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <Button variant="secondary" type="button" onClick={() => setCreateModal(false)}>
              Cancel
            </Button>
            <Button type="submit" loading={submitting}>
              Create Ticket
            </Button>
          </div>
        </form>
      </Modal>
    </PageTransition>
  );
}
