'use client';

import { useState, useEffect, useCallback } from 'react';

import { Plus, Search, Ticket, CheckCircle, AlertCircle, Loader, ChevronRight, Paperclip, Send, X, ArrowLeft } from 'lucide-react';
import { listTickets, createTicket, updateTicket } from '@client/api/support-tickets';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';

type TicketStatus = 'open' | 'in_progress' | 'resolved' | 'closed';
type TicketPriority = 'low' | 'medium' | 'high' | 'urgent';
type View = 'list' | 'new' | 'detail';

interface SupportTicket {
  id: string;
  subject: string;
  category: string;
  priority: TicketPriority;
  status: TicketStatus;
  createdAt: string;
  updatedAt: string;
  description: string;
  messages: any[];
}

const statusConfig: Record<string, { label: string; color: string; bg: string; icon: React.ReactNode }> = {
  open: { label: 'Open', color: 'hsl(210, 100%, 40%)', bg: 'hsl(210, 100%, 96%)', icon: <AlertCircle size={13} /> },
  in_progress: { label: 'In Progress', color: 'hsl(38, 92%, 40%)', bg: 'hsl(38, 100%, 96%)', icon: <Loader size={13} /> },
  resolved: { label: 'Resolved', color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)', icon: <CheckCircle size={13} /> },
  closed: { label: 'Closed', color: 'hsl(220, 9%, 46%)', bg: 'hsl(220, 9%, 96%)', icon: <X size={13} /> },
};

const priorityConfig: Record<string, { label: string; color: string; bg: string }> = {
  low: { label: 'Low', color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)' },
  medium: { label: 'Medium', color: 'hsl(38, 92%, 40%)', bg: 'hsl(38, 100%, 96%)' },
  high: { label: 'High', color: 'hsl(22, 89%, 48%)', bg: 'hsl(22, 100%, 96%)' },
  urgent: { label: 'Urgent', color: 'hsl(0, 84%, 44%)', bg: 'hsl(0, 84%, 97%)' },
};

function apiRowToTicket(row: any): SupportTicket {
  return {
    id: row.id,
    subject: row.subject || '',
    category: row.category || 'Other',
    priority: row.priority || 'medium',
    status: row.status || 'open',
    createdAt: row.created_at ? new Date(row.created_at).toLocaleString() : '',
    updatedAt: row.updated_at ? new Date(row.updated_at).toLocaleString() : '',
    description: row.description || '',
    messages: Array.isArray(row.messages) ? row.messages : [],
  };
}

export default function SupportTicketsPage() {
  const { t } = useLanguage();
  usePageHeader(t('help.supportTickets', "Support Tickets"), t('help.ticketsDescription', "Manage your support requests and get help from our team."));
  const { restaurantId, user } = useAuth();

  const [view, setView] = useState<View>('list');
  const [selectedTicket, setSelectedTicket] = useState<SupportTicket | null>(null);
  const [tickets, setTickets] = useState<SupportTicket[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<TicketStatus | 'all'>('all');
  const [replyText, setReplyText] = useState('');
  const [newTicket, setNewTicket] = useState({ subject: '', category: 'AI Agent', priority: 'medium' as TicketPriority, description: '' });
  const [saving, setSaving] = useState(false);

  const fetchTickets = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const result = await listTickets({ limit: '100' });
      setTickets((result.tickets || []).map(apiRowToTicket));
    } catch (err: any) {
      toast.error(t('help.failedToLoad', 'Failed to load tickets: ') + err.message);
    } finally {
      setLoading(false);
    }
  }, [restaurantId, t]);

  useEffect(() => { fetchTickets(); }, [fetchTickets]);

  const handleSubmitTicket = async () => {
    if (!restaurantId || !newTicket.subject.trim()) return;
    setSaving(true);
    try {
      const result = await createTicket({
        subject: newTicket.subject,
        category: newTicket.category,
        priority: newTicket.priority,
        description: newTicket.description,
        status: 'open',
        messages: newTicket.description ? [{ id: '1', author: user?.email || t('help.you', 'You'), role: 'user', content: newTicket.description, timestamp: new Date().toISOString() }] : [],
      });
      setTickets(prev => [apiRowToTicket(result.ticket), ...prev]);
      setView('list');
      setNewTicket({ subject: '', category: 'AI Agent', priority: 'medium', description: '' });
      toast.success(t('help.ticketSubmitted', 'Support ticket submitted'));
    } catch (err: any) {
      toast.error(t('help.failedToSubmit', 'Failed to submit ticket: ') + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleSendReply = async () => {
    if (!selectedTicket || !replyText.trim()) return;
    try {
      const newMessage = { id: Date.now().toString(), author: user?.email || t('help.you', 'You'), role: 'user', content: replyText, timestamp: new Date().toISOString() };
      const updatedMessages = [...selectedTicket.messages, newMessage];
      await updateTicket(selectedTicket.id, { messages: [newMessage] });
      setSelectedTicket(prev => prev ? { ...prev, messages: updatedMessages } : null);
      setTickets(prev => prev.map(t => t.id === selectedTicket.id ? { ...t, messages: updatedMessages } : t));
      setReplyText('');
      toast.success(t('help.replySent', 'Reply sent'));
    } catch (err: any) {
      toast.error(t('help.failedToSendReply', 'Failed to send reply: ') + err.message);
    }
  };

  const filtered = tickets.filter(t => {
    const matchSearch = !searchQuery || t.subject.toLowerCase().includes(searchQuery.toLowerCase());
    const matchStatus = statusFilter === 'all' || t.status === statusFilter;
    return matchSearch && matchStatus;
  });

  const openTicket = (ticket: SupportTicket) => { setSelectedTicket(ticket); setView('detail'); };

  if (view === 'new') {
    return (
      <>
        <div className="max-w-2xl">
          <button className="flex items-center gap-2 text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }} onClick={() => setView('list')}>
            <ArrowLeft size={15} /> {t('help.backToTickets', 'Back to tickets')}
          </button>
          <div className="rounded-2xl p-6" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <h3 className="font-semibold text-base mb-5" style={{ color: 'hsl(var(--foreground))' }}>{t('help.raiseTicket', 'Raise a Support Ticket')}</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('help.subject', 'Subject')} *</label>
                <input type="text" placeholder={t('help.subjectPlaceholder', "Brief description of your issue")} value={newTicket.subject} onChange={e => setNewTicket({ ...newTicket, subject: e.target.value })} className="input-base w-full" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('help.category', 'Category')} *</label>
                  <select value={newTicket.category} onChange={e => setNewTicket({ ...newTicket, category: e.target.value })} className="input-base w-full">
                    {['AI Agent', 'Orders & Menu', 'Table Bookings', 'Integrations', 'Billing', 'Feature Request', 'Other'].map(c => <option key={c} value={c}>{t(`help.categories.${c}`, c)}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('help.priority', 'Priority')} *</label>
                  <select value={newTicket.priority} onChange={e => setNewTicket({ ...newTicket, priority: e.target.value as TicketPriority })} className="input-base w-full">
                    <option value="low">{t('help.priorityLow', 'Low')}</option>
                    <option value="medium">{t('help.priorityMedium', 'Medium')}</option>
                    <option value="high">{t('help.priorityHigh', 'High')}</option>
                    <option value="urgent">{t('help.priorityUrgent', 'Urgent')}</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('help.description', 'Description')} *</label>
                <textarea rows={6} placeholder={t('help.descriptionPlaceholder', "Describe your issue in detail...")} value={newTicket.description} onChange={e => setNewTicket({ ...newTicket, description: e.target.value })} className="input-base w-full resize-none" />
              </div>
              <div className="flex gap-3 pt-2">
                <button className="btn-primary flex-1" onClick={handleSubmitTicket} disabled={saving}>
                  {saving ? <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Send size={15} />}
                  {t('help.submitTicket', 'Submit Ticket')}
                </button>
                <button className="btn-secondary" onClick={() => setView('list')}>{t('help.cancel', 'Cancel')}</button>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  if (view === 'detail' && selectedTicket) {
    const sc = statusConfig[selectedTicket.status] || statusConfig.open;
    const pc = priorityConfig[selectedTicket.priority] || priorityConfig.medium;
    return (
      <>
        <div className="max-w-3xl">
          <button className="flex items-center gap-2 text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }} onClick={() => setView('list')}>
            <ArrowLeft size={15} /> {t('help.backToTickets', 'Back to tickets')}
          </button>
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
            <div className="lg:col-span-2 space-y-4">
              <div className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="p-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                  <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('help.conversationThread', 'Conversation Thread')}</h3>
                </div>
                <div className="p-4 space-y-4 max-h-96 overflow-y-auto">
                  {selectedTicket.messages.map((msg: any) => (
                    <div key={msg.id} className={`flex gap-3 ${msg.role === 'support' ? 'flex-row-reverse' : ''}`}>
                      <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold shrink-0" style={{ background: msg.role === 'support' ? 'linear-gradient(135deg, hsl(231, 40%, 30%), hsl(231, 40%, 50%))' : 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}>
                        {msg.role === 'support' ? 'S' : 'U'}
                      </div>
                      <div className={`flex-1 ${msg.role === 'support' ? 'items-end' : 'items-start'} flex flex-col`}>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{msg.author}</span>
                          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{new Date(msg.timestamp).toLocaleString()}</span>
                        </div>
                        <div className="p-3 rounded-xl text-sm leading-relaxed max-w-sm" style={{ backgroundColor: msg.role === 'support' ? 'hsl(231, 40%, 14%)' : 'hsl(var(--muted))', color: msg.role === 'support' ? 'white' : 'hsl(var(--foreground))' }}>
                          {msg.content}
                        </div>
                      </div>
                    </div>
                  ))}
                  {selectedTicket.messages.length === 0 && (
                    <p className="text-xs text-center py-4" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('help.noMessages', 'No messages yet')}</p>
                  )}
                </div>
                {selectedTicket.status !== 'resolved' && selectedTicket.status !== 'closed' && (
                  <div className="p-4" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                    <textarea rows={3} placeholder={t('help.replyPlaceholder', "Write a reply...")} value={replyText} onChange={e => setReplyText(e.target.value)} className="input-base w-full resize-none mb-3" />
                    <div className="flex items-center justify-between">
                      <button className="flex items-center gap-1.5 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}><Paperclip size={13} /> {t('help.attachFile', 'Attach file')}</button>
                      <button className="btn-primary text-sm" onClick={handleSendReply}><Send size={13} /> {t('help.sendReply', 'Send Reply')}</button>
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="space-y-4">
              <div className="rounded-2xl p-4" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <h4 className="text-xs font-semibold uppercase tracking-wide mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('help.ticketDetails', 'Ticket Details')}</h4>
                <div className="space-y-3">
                  {[
                    { label: t('help.statusLabel', 'Status'), value: <span className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: sc.bg, color: sc.color }}>{sc.icon} {t(`help.status.${selectedTicket.status}`, sc.label)}</span> },
                    { label: t('help.priorityLabel', 'Priority'), value: <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: pc.bg, color: pc.color }}>{t(`help.priority.${selectedTicket.priority}`, pc.label)}</span> },
                    { label: t('help.categoryLabel', 'Category'), value: <span className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t(`help.categories.${selectedTicket.category}`, selectedTicket.category)}</span> },
                    { label: t('help.createdLabel', 'Created'), value: <span className="text-xs" style={{ color: 'hsl(var(--foreground))' }}>{selectedTicket.createdAt}</span> },
                  ].map(row => (
                    <div key={row.label} className="flex items-center justify-between">
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{row.label}</span>
                      {row.value}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex items-center gap-3">
          <div className="relative max-w-xs">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
            <input className="input-base pl-9 text-sm" placeholder={t('help.searchPlaceholder', 'Search tickets...')} value={searchQuery} onChange={e => setSearchQuery(e.target.value)} />
          </div>
          <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            {(['all', 'open', 'in_progress', 'resolved', 'closed'] as const).map(s => (
              <button
                key={s}
                onClick={() => setStatusFilter(s)}
                className="px-3 py-1.5 rounded-lg text-xs font-medium transition-all capitalize"
                style={{ backgroundColor: statusFilter === s ? 'hsl(var(--surface))' : 'transparent', color: statusFilter === s ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
              >
                {t(`help.status.${s}`, s === 'in_progress' ? 'In Progress' : s.charAt(0).toUpperCase() + s.slice(1))}
              </button>
            ))}
          </div>
        </div>
        <button className="btn-primary" onClick={() => setView('new')}><Plus size={15} /> {t('help.newTicket', 'New Ticket')}</button>
      </div>

      {loading ? (
        <div className="card overflow-hidden">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="flex items-center gap-4 px-5 py-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <div className="w-8 h-8 rounded-full skeleton shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="h-3.5 w-40 rounded skeleton mb-1.5" />
                <div className="h-3 w-24 rounded skeleton" />
              </div>
              <div className="h-5 w-16 rounded-full skeleton" />
              <div className="h-3 w-20 rounded skeleton" />
            </div>
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Ticket size={32} className="mx-auto mb-3 opacity-30" />
          <p className="font-medium">{t('help.noTickets', 'No support tickets')}</p>
          <p className="text-xs mt-1">{t('help.noTicketsDescription', 'Create a ticket if you need help with anything')}</p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map(ticket => {
            const sc = statusConfig[ticket.status] || statusConfig.open;
            const pc = priorityConfig[ticket.priority] || priorityConfig.medium;
            return (
              <div
                key={ticket.id}
                className="rounded-2xl p-4 cursor-pointer transition-all hover:shadow-md"
                style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}
                onClick={() => openTicket(ticket)}
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--muted-foreground))' }}>{ticket.id.slice(0, 8).toUpperCase()}</span>
                      <span className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: sc.bg, color: sc.color }}>{sc.icon} {t(`help.status.${ticket.status}`, sc.label)}</span>
                      <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: pc.bg, color: pc.color }}>{t(`help.priority.${ticket.priority}`, pc.label)}</span>
                    </div>
                    <h3 className="font-semibold text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{ticket.subject}</h3>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t(`help.categories.${ticket.category}`, ticket.category)} · {ticket.createdAt}</p>
                  </div>
                  <ChevronRight size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />
                </div>
              </div>
            );
          })}
        </div>
      )}
    </>
  );
}
