'use client';

import { useState, useEffect } from 'react';
import { useLanguage } from '@/context/LanguageContext';
import { ticketsApi, eventsApi, Ticket, Event } from '@/lib/api';
import { parseDate } from '@/lib/utils';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import { AdminPageSkeleton } from '@/components/ui/Skeleton';
import Input from '@/components/ui/Input';
import { BottomSheet, MoreMenu, DropdownItem, AdminMobileStyles } from '@/components/admin/MobileComponents';
import { CheckCircleIcon, XCircleIcon, PlusIcon, FunnelIcon, XMarkIcon } from '@heroicons/react/24/outline';
import toast from 'react-hot-toast';
import clsx from 'clsx';

export default function AdminTicketsPage() {
  const { t, locale } = useLanguage();
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedEvent, setSelectedEvent] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [mobileFilterOpen, setMobileFilterOpen] = useState(false);
  
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [creating, setCreating] = useState(false);
  const [createForm, setCreateForm] = useState({
    eventId: '', firstName: '', lastName: '', email: '', phone: '',
    preferredLanguage: 'en' as 'en' | 'es', autoCheckin: false, adminNote: '',
  });

  useEffect(() => {
    Promise.all([ticketsApi.getAll(), eventsApi.getAll()])
      .then(([ticketsRes, eventsRes]) => {
        setTickets(ticketsRes.tickets);
        setEvents(eventsRes.events);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const loadTickets = async () => {
    try {
      const params: any = {};
      if (selectedEvent) params.eventId = selectedEvent;
      if (statusFilter) params.status = statusFilter;
      const { tickets } = await ticketsApi.getAll(params);
      setTickets(tickets);
    } catch (error) {
      toast.error('Failed to load tickets');
    }
  };

  useEffect(() => {
    if (!loading) loadTickets();
  }, [selectedEvent, statusFilter]);

  const handleCheckin = async (id: string) => {
    try {
      await ticketsApi.checkin(id);
      toast.success('Check-in successful');
      loadTickets();
    } catch (error: any) {
      toast.error(error.message || 'Check-in failed');
    }
  };

  const handleCancel = async (id: string) => {
    if (!confirm('Are you sure you want to cancel this ticket?')) return;
    try {
      await ticketsApi.cancel(id);
      toast.success('Ticket cancelled');
      loadTickets();
    } catch (error) {
      toast.error('Failed to cancel ticket');
    }
  };

  const handleConfirm = async (id: string) => {
    try {
      await ticketsApi.updateStatus(id, 'confirmed');
      toast.success('Ticket confirmed');
      loadTickets();
    } catch (error) {
      toast.error('Failed to confirm ticket');
    }
  };

  const handleCreateTicket = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!createForm.eventId) { toast.error('Please select an event'); return; }
    setCreating(true);
    try {
      await ticketsApi.adminCreate({
        eventId: createForm.eventId, firstName: createForm.firstName,
        lastName: createForm.lastName || undefined, email: createForm.email,
        phone: createForm.phone, preferredLanguage: createForm.preferredLanguage,
        autoCheckin: createForm.autoCheckin, adminNote: createForm.adminNote || undefined,
      });
      toast.success('Ticket created successfully');
      setShowCreateForm(false);
      setCreateForm({ eventId: '', firstName: '', lastName: '', email: '', phone: '', preferredLanguage: 'en', autoCheckin: false, adminNote: '' });
      loadTickets();
    } catch (error: any) {
      toast.error(error.message || 'Failed to create ticket');
    } finally {
      setCreating(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return parseDate(dateStr).toLocaleDateString(locale === 'es' ? 'es-ES' : 'en-US', {
      month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', timeZone: 'America/Asuncion',
    });
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      pending: 'badge-warning', confirmed: 'badge-success', cancelled: 'badge-danger', checked_in: 'badge-info',
    };
    const labels: Record<string, string> = {
      pending: t('admin.tickets.status.pending'), confirmed: t('admin.tickets.status.confirmed'),
      cancelled: t('admin.tickets.status.cancelled'), checked_in: t('admin.tickets.status.checkedIn'),
    };
    return <span className={`badge ${styles[status] || 'badge-gray'}`}>{labels[status] || status}</span>;
  };

  const getEventName = (eventId: string) => events.find(e => e.id === eventId)?.title || 'Unknown Event';

  const hasActiveFilters = selectedEvent || statusFilter;

  const getPrimaryAction = (ticket: Ticket) => {
    if (ticket.status === 'pending') return { label: 'Confirm', onClick: () => handleConfirm(ticket.id) };
    if (ticket.status === 'confirmed') return { label: t('admin.tickets.checkin'), onClick: () => handleCheckin(ticket.id) };
    return null;
  };

  if (loading) {
    return <AdminPageSkeleton cols={5} />;
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl md:text-2xl font-bold text-primary-dark">{t('admin.tickets.title')}</h1>
        <Button onClick={() => setShowCreateForm(true)} className="hidden md:flex">
          <PlusIcon className="w-5 h-5 mr-2" /> Create Ticket
        </Button>
      </div>

      {/* Create Ticket Modal */}
      {showCreateForm && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center p-0 md:p-4">
          <Card className="w-full md:max-w-lg max-h-[90vh] flex flex-col overflow-hidden rounded-t-2xl md:rounded-card">
            <div className="flex items-center justify-between p-4 border-b border-secondary-light-gray flex-shrink-0">
              <h2 className="text-base font-bold">Create Ticket Manually</h2>
              <button onClick={() => setShowCreateForm(false)}
                className="p-2 hover:bg-gray-100 rounded-btn min-h-[44px] min-w-[44px] flex items-center justify-center">
                <XMarkIcon className="w-5 h-5" />
              </button>
            </div>
            <form onSubmit={handleCreateTicket} className="p-4 space-y-4 overflow-y-auto flex-1 min-h-0">
              <div>
                <label className="block text-sm font-medium mb-1">Event *</label>
                <select value={createForm.eventId}
                  onChange={(e) => setCreateForm({ ...createForm, eventId: e.target.value })}
                  className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray min-h-[44px]" required>
                  <option value="">Select an event</option>
                  {events.filter(e => e.status === 'published' || e.status === 'unlisted').map((event) => (
                    <option key={event.id} value={event.id}>{event.title} ({event.availableSeats} spots left)</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <Input label="First Name *" value={createForm.firstName}
                  onChange={(e) => setCreateForm({ ...createForm, firstName: e.target.value })} required placeholder="First name" />
                <Input label="Last Name" value={createForm.lastName}
                  onChange={(e) => setCreateForm({ ...createForm, lastName: e.target.value })} placeholder="Last name" />
              </div>
              <Input label="Email (optional)" type="email" value={createForm.email}
                onChange={(e) => setCreateForm({ ...createForm, email: e.target.value })} placeholder="attendee@email.com" />
              <Input label="Phone (optional)" value={createForm.phone}
                onChange={(e) => setCreateForm({ ...createForm, phone: e.target.value })} placeholder="+595 XXX XXX XXX" />
              <div>
                <label className="block text-sm font-medium mb-1">Preferred Language</label>
                <select value={createForm.preferredLanguage}
                  onChange={(e) => setCreateForm({ ...createForm, preferredLanguage: e.target.value as 'en' | 'es' })}
                  className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray min-h-[44px]">
                  <option value="en">English</option>
                  <option value="es">Spanish</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Admin Note</label>
                <textarea value={createForm.adminNote}
                  onChange={(e) => setCreateForm({ ...createForm, adminNote: e.target.value })}
                  className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray" rows={2}
                  placeholder="Internal note (optional)" />
              </div>
              <div className="flex items-center gap-3">
                <input type="checkbox" id="autoCheckin" checked={createForm.autoCheckin}
                  onChange={(e) => setCreateForm({ ...createForm, autoCheckin: e.target.checked })}
                  className="w-4 h-4 rounded border-secondary-light-gray text-primary-yellow focus:ring-primary-yellow" />
                <label htmlFor="autoCheckin" className="text-sm">Auto check-in immediately</label>
              </div>
              <div className="bg-yellow-50 border border-yellow-200 rounded-btn p-3 text-sm text-yellow-800">
                Creates a ticket with cash payment marked as paid. Use for walk-ins at the door.
              </div>
              <div className="flex gap-3 pt-2">
                <Button type="button" variant="outline" onClick={() => setShowCreateForm(false)} className="flex-1 min-h-[44px]">Cancel</Button>
                <Button type="submit" isLoading={creating} className="flex-1 min-h-[44px]">Create Ticket</Button>
              </div>
            </form>
          </Card>
        </div>
      )}

      {/* Desktop Filters */}
      <Card className="p-4 mb-6 hidden md:block">
        <div className="flex flex-wrap gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">Event</label>
            <select value={selectedEvent} onChange={(e) => setSelectedEvent(e.target.value)}
              className="px-4 py-2 rounded-btn border border-secondary-light-gray min-w-[200px] text-sm">
              <option value="">All Events</option>
              {events.map((event) => (
                <option key={event.id} value={event.id}>{event.title}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Status</label>
            <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}
              className="px-4 py-2 rounded-btn border border-secondary-light-gray min-w-[150px] text-sm">
              <option value="">All Statuses</option>
              <option value="pending">Pending</option>
              <option value="confirmed">Confirmed</option>
              <option value="checked_in">Checked In</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
        </div>
      </Card>

      {/* Mobile Toolbar */}
      <div className="md:hidden mb-4 flex items-center gap-2">
        <button onClick={() => setMobileFilterOpen(true)}
          className={clsx(
            'flex items-center gap-1.5 px-3 py-2 rounded-btn border text-sm min-h-[44px]',
            hasActiveFilters ? 'border-primary-yellow bg-yellow-50 text-primary-dark' : 'border-secondary-light-gray text-gray-600'
          )}>
          <FunnelIcon className="w-4 h-4" />
          Filters {hasActiveFilters && `(${tickets.length})`}
        </button>
        {hasActiveFilters && (
          <button onClick={() => { setSelectedEvent(''); setStatusFilter(''); }}
            className="text-xs text-primary-yellow min-h-[44px] flex items-center">Clear</button>
        )}
      </div>

      {/* Desktop: Table */}
      <Card className="overflow-hidden hidden md:block">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-secondary-gray">
              <tr>
                <th className="text-left px-4 py-2 text-xs font-medium text-gray-500 uppercase tracking-wider">Ticket</th>
                <th className="text-left px-4 py-2 text-xs font-medium text-gray-500 uppercase tracking-wider">Event</th>
                <th className="text-left px-4 py-2 text-xs font-medium text-gray-500 uppercase tracking-wider">Booked</th>
                <th className="text-left px-4 py-2 text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                <th className="text-right px-4 py-2 text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-secondary-light-gray">
              {tickets.length === 0 ? (
                <tr><td colSpan={5} className="px-4 py-12 text-center text-gray-500 text-sm">No tickets found</td></tr>
              ) : (
                tickets.map((ticket) => (
                  <tr key={ticket.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3">
                      <p className="font-mono text-sm font-medium">{ticket.qrCode}</p>
                      <p className="text-[10px] text-gray-400">ID: {ticket.id.slice(0, 8)}...</p>
                    </td>
                    <td className="px-4 py-3 text-sm">{getEventName(ticket.eventId)}</td>
                    <td className="px-4 py-3 text-xs text-gray-500">{formatDate(ticket.createdAt)}</td>
                    <td className="px-4 py-3">{getStatusBadge(ticket.status)}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        {ticket.status === 'pending' && (
                          <Button size="sm" variant="ghost" onClick={() => handleConfirm(ticket.id)}>Confirm</Button>
                        )}
                        {ticket.status === 'confirmed' && (
                          <Button size="sm" onClick={() => handleCheckin(ticket.id)}>
                            <CheckCircleIcon className="w-4 h-4 mr-1" /> {t('admin.tickets.checkin')}
                          </Button>
                        )}
                        {ticket.status !== 'cancelled' && ticket.status !== 'checked_in' && (
                          <button onClick={() => handleCancel(ticket.id)}
                            className="p-2 hover:bg-red-100 text-red-600 rounded-btn" title="Cancel">
                            <XCircleIcon className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {/* Mobile: Card List */}
      <div className="md:hidden space-y-2">
        {tickets.length === 0 ? (
          <div className="text-center py-10 text-gray-500 text-sm">No tickets found</div>
        ) : (
          tickets.map((ticket) => {
            const primary = getPrimaryAction(ticket);
            return (
              <Card key={ticket.id} className="p-3">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0 flex-1">
                    <p className="font-mono text-sm font-medium">{ticket.qrCode}</p>
                    <p className="text-xs text-gray-500 truncate">{getEventName(ticket.eventId)}</p>
                  </div>
                  {getStatusBadge(ticket.status)}
                </div>
                <div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
                  <p className="text-[10px] text-gray-400">{formatDate(ticket.createdAt)}</p>
                  <div className="flex items-center gap-1">
                    {primary && (
                      <Button size="sm" variant={ticket.status === 'confirmed' ? 'primary' : 'outline'}
                        onClick={primary.onClick} className="text-xs px-2.5 py-1.5 min-h-[36px]">
                        {primary.label}
                      </Button>
                    )}
                    {ticket.status !== 'cancelled' && ticket.status !== 'checked_in' && (
                      <MoreMenu>
                        <DropdownItem onClick={() => handleCancel(ticket.id)} className="text-red-600">
                          <XCircleIcon className="w-4 h-4 mr-2" /> Cancel Ticket
                        </DropdownItem>
                      </MoreMenu>
                    )}
                    {ticket.status === 'checked_in' && (
                      <span className="text-[10px] text-green-600 flex items-center gap-1">
                        <CheckCircleIcon className="w-3.5 h-3.5" /> Attended
                      </span>
                    )}
                  </div>
                </div>
              </Card>
            );
          })
        )}
      </div>

      {/* Mobile FAB */}
      <div className="md:hidden fixed bottom-6 right-6 z-40">
        <button onClick={() => setShowCreateForm(true)}
          className="w-14 h-14 bg-primary-yellow text-primary-dark rounded-full shadow-lg flex items-center justify-center hover:bg-yellow-400 active:scale-95 transition-transform">
          <PlusIcon className="w-6 h-6" />
        </button>
      </div>

      {/* Mobile Filter BottomSheet */}
      <BottomSheet open={mobileFilterOpen} onClose={() => setMobileFilterOpen(false)} title="Filters">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Event</label>
            <select value={selectedEvent} onChange={(e) => setSelectedEvent(e.target.value)}
              className="w-full px-3 py-2.5 rounded-btn border border-secondary-light-gray text-sm min-h-[44px]">
              <option value="">All Events</option>
              {events.map((event) => (
                <option key={event.id} value={event.id}>{event.title}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <div className="space-y-1">
              {[
                { value: '', label: 'All Statuses' },
                { value: 'pending', label: 'Pending' },
                { value: 'confirmed', label: 'Confirmed' },
                { value: 'checked_in', label: 'Checked In' },
                { value: 'cancelled', label: 'Cancelled' },
              ].map((opt) => (
                <button key={opt.value} onClick={() => setStatusFilter(opt.value)}
                  className={clsx(
                    'w-full text-left px-3 py-2.5 rounded-btn text-sm min-h-[44px] flex items-center justify-between',
                    statusFilter === opt.value ? 'bg-yellow-50 text-primary-dark font-medium' : 'hover:bg-gray-50'
                  )}>
                  {opt.label}
                  {statusFilter === opt.value && <CheckCircleIcon className="w-4 h-4 text-primary-yellow" />}
                </button>
              ))}
            </div>
          </div>
          <div className="flex gap-3 pt-2">
            <Button variant="outline" onClick={() => { setSelectedEvent(''); setStatusFilter(''); setMobileFilterOpen(false); }} className="flex-1 min-h-[44px]">Clear</Button>
            <Button onClick={() => setMobileFilterOpen(false)} className="flex-1 min-h-[44px]">Apply</Button>
          </div>
        </div>
      </BottomSheet>

      <AdminMobileStyles />
    </div>
  );
}
