import { useState, useEffect } from 'react';
import {
  Typography, Card, Row, Col, Tag, Button, Spin, Empty, Space, Grid,
} from 'antd';
import {
  CalendarOutlined, ClockCircleOutlined, EnvironmentOutlined,
  TagOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

const { Title, Text } = Typography;

interface MyTicket {
  id: string;
  ticketCode: string;
  status: string;
  holderName: string | null;
  holderEmail: string;
  issuedAt: string;
  checkedInAt: string | null;
  tier: { name: string; tierType: string; priceCAD: number };
  event: {
    id: string;
    slug: string;
    title: string;
    date: string;
    startTime: string;
    endTime: string;
    venueName: string | null;
    coverImageUrl: string | null;
  };
  qrUrl: string;
}

export default function MyTicketsPage() {
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [tickets, setTickets] = useState<MyTicket[]>([]);
  const [loading, setLoading] = useState(true);

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

  const fetchTickets = async () => {
    setLoading(true);
    try {
      const { data } = await api.get('/ticketed-events/my-tickets');
      setTickets(data.tickets);
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 80 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (tickets.length === 0) {
    return (
      <div style={{ padding: isMobile ? 16 : 24 }}>
        <Title level={3}><TagOutlined /> My Tickets</Title>
        <Empty
          description="You don't have any tickets yet"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <Button type="primary" onClick={() => navigate('/events')}>Browse Events</Button>
        </Empty>
      </div>
    );
  }

  // Group tickets by event
  const grouped = tickets.reduce<Record<string, MyTicket[]>>((acc, t) => {
    const key = t.event.id;
    if (!acc[key]) acc[key] = [];
    acc[key].push(t);
    return acc;
  }, {});

  const statusColors: Record<string, string> = {
    VALID: 'green',
    CHECKED_IN: 'blue',
    CANCELLED: 'red',
    REFUNDED: 'orange',
  };

  return (
    <div style={{ padding: isMobile ? 16 : 24 }}>
      <Title level={3}><TagOutlined /> My Tickets</Title>

      {Object.entries(grouped).map(([eventId, eventTickets]) => {
        const ev = eventTickets[0]!.event;
        const isPast = dayjs(ev.date).isBefore(dayjs(), 'day');

        return (
          <Card
            key={eventId}
            style={{ marginBottom: 16, opacity: isPast ? 0.7 : 1 }}
            title={
              <Space>
                <Text strong>{ev.title}</Text>
                {isPast && <Tag>Past</Tag>}
              </Space>
            }
            extra={
              <Button size="small" onClick={() => navigate(`/event/${ev.slug}`)}>
                View Event
              </Button>
            }
          >
            <Space wrap style={{ marginBottom: 12 }}>
              <Tag icon={<CalendarOutlined />}>{dayjs(ev.date).format('MMM D, YYYY')}</Tag>
              <Tag icon={<ClockCircleOutlined />}>{ev.startTime} – {ev.endTime}</Tag>
              {ev.venueName && <Tag icon={<EnvironmentOutlined />}>{ev.venueName}</Tag>}
            </Space>

            <Row gutter={[12, 12]}>
              {eventTickets.map(ticket => (
                <Col xs={24} sm={12} md={8} key={ticket.id}>
                  <Card
                    size="small"
                    hoverable
                    onClick={() => navigate(`/event/${ev.slug}/ticket/${ticket.ticketCode}`)}
                    style={{ textAlign: 'center' }}
                  >
                    <img
                      src={ticket.qrUrl}
                      alt={`QR ${ticket.ticketCode}`}
                      style={{ width: 120, height: 120, marginBottom: 8 }}
                    />
                    <div>
                      <Text code style={{ fontSize: 14 }}>{ticket.ticketCode}</Text>
                    </div>
                    <div style={{ marginTop: 4 }}>
                      <Tag color={statusColors[ticket.status]} style={{ fontSize: 11 }}>
                        {ticket.status}
                      </Tag>
                    </div>
                    <Text type="secondary" style={{ fontSize: 12 }}>{ticket.tier.name}</Text>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        );
      })}
    </div>
  );
}
