import { useState, useEffect } from 'react';
import {
  Typography, Card, Button, Spin, Result, Space, Tag, Grid, Divider,
} from 'antd';
import {
  CalendarOutlined, ClockCircleOutlined, EnvironmentOutlined,
  QrcodeOutlined, CheckCircleOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import { useParams, useNavigate } from 'react-router-dom';

const { Title, Text } = Typography;
const apiBase = '/api';

interface TicketDetail {
  id: string;
  ticketCode: string;
  holderEmail: string;
  holderName: string | null;
  status: string;
  tier: { name: string; tierType: string; priceCAD: number };
  event: {
    title: string;
    slug: string;
    date: string;
    startTime: string;
    endTime: string;
    doorsOpenTime: string | null;
    venueName: string | null;
    venueAddress: string | null;
  };
  qrUrl: string;
}

export default function TicketConfirmationPage() {
  const { slug, ticketCode } = useParams<{ slug: string; ticketCode: string }>();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [ticket, setTicket] = useState<TicketDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!slug || !ticketCode) return;
    fetchTicket();
  }, [slug, ticketCode]); // eslint-disable-line react-hooks/exhaustive-deps

  const fetchTicket = async () => {
    setLoading(true);
    try {
      const { data } = await axios.get(`${apiBase}/ticketed-events/${slug}/ticket/${ticketCode}`);
      setTicket(data);
    } catch (err: unknown) {
      const status = (err as { response?: { status?: number } })?.response?.status;
      setError(status === 404 ? 'Ticket not found' : 'Failed to load ticket');
    } finally {
      setLoading(false);
    }
  };

  const generateIcsUrl = () => {
    if (!ticket) return '';
    const e = ticket.event;
    const dateStr = dayjs(e.date).format('YYYYMMDD');
    const start = `${dateStr}T${e.startTime.replace(':', '')}00`;
    const end = `${dateStr}T${e.endTime.replace(':', '')}00`;
    const ics = [
      'BEGIN:VCALENDAR',
      'VERSION:2.0',
      'BEGIN:VEVENT',
      `DTSTART:${start}`,
      `DTEND:${end}`,
      `SUMMARY:${e.title}`,
      e.venueName ? `LOCATION:${e.venueName}${e.venueAddress ? ' - ' + e.venueAddress : ''}` : '',
      `DESCRIPTION:Ticket: ${ticket.ticketCode}`,
      'END:VEVENT',
      'END:VCALENDAR',
    ].filter(Boolean).join('\r\n');

    return `data:text/calendar;charset=utf-8,${encodeURIComponent(ics)}`;
  };

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

  if (error || !ticket) {
    return (
      <Result
        status="404"
        title={error || 'Ticket Not Found'}
        extra={<Button onClick={() => navigate(`/event/${slug}`)}>View Event</Button>}
      />
    );
  }

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

  return (
    <div style={{
      maxWidth: 500,
      margin: '0 auto',
      padding: isMobile ? '16px 8px' : '24px 16px',
    }}>
      <Card style={{ textAlign: 'center' }}>
        <CheckCircleOutlined style={{ fontSize: 48, color: '#52c41a', marginBottom: 16 }} />
        <Title level={3} style={{ marginBottom: 4 }}>Your Ticket</Title>
        <Text type="secondary">{ticket.event.title}</Text>

        <Divider />

        {/* QR Code */}
        <div style={{ marginBottom: 24 }}>
          <img
            src={ticket.qrUrl}
            alt={`QR Code for ${ticket.ticketCode}`}
            style={{ width: 250, height: 250 }}
          />
        </div>

        {/* Ticket code */}
        <Title level={4} style={{ fontFamily: 'monospace', letterSpacing: 2, marginBottom: 4 }}>
          {ticket.ticketCode}
        </Title>
        <Tag color={statusColors[ticket.status]}>{ticket.status}</Tag>

        <Divider />

        {/* Event details */}
        <Space direction="vertical" style={{ width: '100%', textAlign: 'left' }}>
          <div>
            <CalendarOutlined style={{ marginRight: 8 }} />
            <Text>{dayjs(ticket.event.date).format('MMMM D, YYYY')}</Text>
          </div>
          <div>
            <ClockCircleOutlined style={{ marginRight: 8 }} />
            <Text>
              {ticket.event.startTime} – {ticket.event.endTime}
              {ticket.event.doorsOpenTime && ` (Doors: ${ticket.event.doorsOpenTime})`}
            </Text>
          </div>
          {ticket.event.venueName && (
            <div>
              <EnvironmentOutlined style={{ marginRight: 8 }} />
              <Text>{ticket.event.venueName}</Text>
              {ticket.event.venueAddress && (
                <Text type="secondary" style={{ display: 'block', marginLeft: 22 }}>
                  {ticket.event.venueAddress}
                </Text>
              )}
            </div>
          )}
          <div>
            <QrcodeOutlined style={{ marginRight: 8 }} />
            <Text>{ticket.tier.name}</Text>
            {ticket.tier.tierType === 'PAID' && (
              <Text type="secondary"> — ${(ticket.tier.priceCAD / 100).toFixed(2)}</Text>
            )}
          </div>
        </Space>

        <Divider />

        {/* Holder info */}
        <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
          {ticket.holderName || ticket.holderEmail}
        </Text>

        {/* Actions */}
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button
            type="primary"
            block
            href={generateIcsUrl()}
            download={`${ticket.ticketCode}.ics`}
            icon={<CalendarOutlined />}
          >
            Add to Calendar
          </Button>
          <Button block onClick={() => navigate(`/event/${ticket.event.slug}`)}>
            View Event
          </Button>
        </Space>
      </Card>
    </div>
  );
}
