import { useState, useEffect } from 'react';
import {
  Typography, Card, Button, Row, Col, Tag, Spin, Result, Grid, Space,
  Input, message, Divider,
} from 'antd';
import {
  CalendarOutlined, ClockCircleOutlined, EnvironmentOutlined,
  TagOutlined, UserOutlined, LockOutlined, VideoCameraOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import DOMPurify from 'dompurify';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth.store';

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

interface TicketTier {
  id: string;
  name: string;
  description: string | null;
  tierType: 'PAID' | 'FREE' | 'DONATION';
  priceCAD: number;
  minDonationCAD: number | null;
  maxQuantity: number | null;
  soldCount: number;
  maxPerOrder: number;
  isActive: boolean;
  salesStartAt: string | null;
  salesEndAt: string | null;
}

interface EventDetail {
  id: string;
  slug: string;
  title: string;
  description: string | null;
  richDescription: string | null;
  date: string;
  startTime: string;
  endTime: string;
  doorsOpenTime: string | null;
  eventFormat: 'IN_PERSON' | 'ONLINE' | 'HYBRID';
  hasMeeting: boolean;
  venueName: string | null;
  venueAddress: string | null;
  coverImageUrl: string | null;
  maxAttendees: number | null;
  currentAttendees: number;
  organizerName: string | null;
  visibility: string;
  ticketTiers: TicketTier[];
}

export default function TicketedEventDetailPage() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { user, isAuthenticated } = useAuthStore();

  const [event, setEvent] = useState<EventDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [inviteCode, setInviteCode] = useState(searchParams.get('code') || '');
  const [needsInviteCode, setNeedsInviteCode] = useState(false);
  const [checkingOut, setCheckingOut] = useState<string | null>(null);

  // Guest info for non-authenticated users
  const [guestEmail, setGuestEmail] = useState('');
  const [guestName, setGuestName] = useState('');

  // Meeting access
  const [meetingTicketCode, setMeetingTicketCode] = useState('');
  const [meetingAccess, setMeetingAccess] = useState<{ jitsiRoom: string; domain: string; eventTitle: string } | null>(null);
  const [meetingLoading, setMeetingLoading] = useState(false);
  const [meetingError, setMeetingError] = useState('');

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

  const fetchEvent = async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = {};
      if (inviteCode) params.inviteCode = inviteCode;
      const { data } = await axios.get(`${apiBase}/ticketed-events/${slug}`, { params });
      if (data.requiresInviteCode) {
        setNeedsInviteCode(true);
        setEvent(null);
      } else {
        setEvent(data);
        setNeedsInviteCode(false);
      }
    } catch (err: unknown) {
      const status = (err as { response?: { status?: number } })?.response?.status;
      if (status === 404) {
        setEvent(null);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCheckout = async (tier: TicketTier) => {
    const email = isAuthenticated ? user?.email : guestEmail.trim();
    const name = isAuthenticated ? user?.name : guestName.trim();

    if (!email) {
      message.warning('Please enter your email address');
      return;
    }

    setCheckingOut(tier.id);
    try {
      if (tier.tierType === 'FREE') {
        await axios.post(`${apiBase}/ticketed-events/${slug}/register`, {
          tierId: tier.id,
          holderEmail: email,
          holderName: name || undefined,
        });
        message.success('Registration successful! Check your email for your ticket.');
        fetchEvent();
      } else {
        const { data } = await axios.post(`${apiBase}/ticketed-events/${slug}/checkout`, {
          tierId: tier.id,
          quantity: 1,
          buyerEmail: email,
          buyerName: name || undefined,
        });
        window.location.href = data.url;
      }
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Failed to process';
      message.error(msg);
    } finally {
      setCheckingOut(null);
    }
  };

  const isTierAvailable = (tier: TicketTier) => {
    if (!tier.isActive) return false;
    if (tier.maxQuantity && tier.soldCount >= tier.maxQuantity) return false;
    if (tier.salesStartAt && dayjs().isBefore(dayjs(tier.salesStartAt))) return false;
    if (tier.salesEndAt && dayjs().isAfter(dayjs(tier.salesEndAt))) return false;
    return true;
  };

  const isSoldOut = event?.maxAttendees
    ? event.currentAttendees >= event.maxAttendees
    : false;

  const handleGetMeetingLink = async () => {
    if (!meetingTicketCode.trim()) {
      setMeetingError('Please enter your ticket code');
      return;
    }
    setMeetingLoading(true);
    setMeetingError('');
    setMeetingAccess(null);
    try {
      const { data } = await axios.get(`${apiBase}/ticketed-events/${slug}/meeting-access`, {
        params: { ticketCode: meetingTicketCode.trim() },
      });
      setMeetingAccess(data);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Invalid ticket code';
      setMeetingError(msg);
    } finally {
      setMeetingLoading(false);
    }
  };

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

  if (needsInviteCode) {
    return (
      <div style={{ maxWidth: 400, margin: '0 auto', padding: isMobile ? '24px 16px' : 48 }}>
        <Result
          icon={<LockOutlined style={{ color: '#faad14' }} />}
          title="Private Event"
          subTitle="This event requires an invite code to view."
        />
        <Space.Compact style={{ width: '100%' }}>
          <Input
            placeholder="Enter invite code"
            value={inviteCode}
            onChange={e => setInviteCode(e.target.value)}
            onPressEnter={fetchEvent}
          />
          <Button type="primary" onClick={fetchEvent}>Submit</Button>
        </Space.Compact>
      </div>
    );
  }

  if (!event) {
    return (
      <Result
        status="404"
        title="Event Not Found"
        subTitle="This event may have been removed or doesn't exist."
        extra={<Button onClick={() => navigate('/events')}>Browse Events</Button>}
      />
    );
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: isMobile ? '16px 8px' : '24px 16px' }}>
      {/* Cover image */}
      {event.coverImageUrl && (
        <div style={{
          marginBottom: 24,
          borderRadius: 12,
          overflow: 'hidden',
          maxHeight: 400,
        }}>
          <img
            src={event.coverImageUrl}
            alt={event.title}
            style={{ width: '100%', objectFit: 'cover' }}
          />
        </div>
      )}

      {/* Title + date */}
      <Title level={2} style={{ marginBottom: 8 }}>{event.title}</Title>

      <Space wrap style={{ marginBottom: 24 }}>
        <Tag icon={<CalendarOutlined />} color="blue">
          {dayjs(event.date).format('MMMM D, YYYY')}
        </Tag>
        <Tag icon={<ClockCircleOutlined />}>
          {event.startTime} – {event.endTime}
          {event.doorsOpenTime && ` (Doors: ${event.doorsOpenTime})`}
        </Tag>
        {event.eventFormat === 'ONLINE' ? (
          <Tag icon={<VideoCameraOutlined />} color="purple">Online Event</Tag>
        ) : event.eventFormat === 'HYBRID' ? (
          <>
            {event.venueName && <Tag icon={<EnvironmentOutlined />} color="green">{event.venueName}</Tag>}
            <Tag icon={<VideoCameraOutlined />} color="purple">Also Online</Tag>
          </>
        ) : (
          event.venueName && <Tag icon={<EnvironmentOutlined />} color="green">{event.venueName}</Tag>
        )}
        {event.maxAttendees && (
          <Tag icon={<UserOutlined />}>
            {event.currentAttendees}/{event.maxAttendees} attendees
          </Tag>
        )}
      </Space>

      {/* Description */}
      {event.richDescription ? (
        <Card style={{ marginBottom: 24 }}>
          <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(event.richDescription) }} />
        </Card>
      ) : event.description ? (
        <Card style={{ marginBottom: 24 }}>
          <Paragraph>{event.description}</Paragraph>
        </Card>
      ) : null}

      {/* Venue details */}
      {event.venueAddress && (
        <Card size="small" style={{ marginBottom: 24 }}>
          <Space>
            <EnvironmentOutlined />
            <div>
              <Text strong>{event.venueName}</Text>
              <br />
              <Text type="secondary">{event.venueAddress}</Text>
            </div>
          </Space>
        </Card>
      )}

      {/* Organizer */}
      {event.organizerName && (
        <Text type="secondary" style={{ display: 'block', marginBottom: 24 }}>
          Organized by {event.organizerName}
        </Text>
      )}

      <Divider />

      {/* Ticket tiers */}
      <Title level={4} style={{ marginBottom: 16 }}>
        <TagOutlined /> Tickets
      </Title>

      {isSoldOut && (
        <Result
          status="warning"
          title="Sold Out"
          subTitle="This event has reached capacity."
          style={{ marginBottom: 24 }}
        />
      )}

      {/* Guest info form for non-authenticated users */}
      {!isAuthenticated && !isSoldOut && (
        <Card size="small" style={{ marginBottom: 16 }}>
          <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
            Enter your details to get tickets:
          </Text>
          <Row gutter={[12, 12]}>
            <Col xs={24} sm={12}>
              <Input
                placeholder="Email *"
                value={guestEmail}
                onChange={e => setGuestEmail(e.target.value)}
              />
            </Col>
            <Col xs={24} sm={12}>
              <Input
                placeholder="Name (optional)"
                value={guestName}
                onChange={e => setGuestName(e.target.value)}
              />
            </Col>
          </Row>
        </Card>
      )}

      <Row gutter={[16, 16]}>
        {event.ticketTiers.map(tier => {
          const available = isTierAvailable(tier) && !isSoldOut;
          const remaining = tier.maxQuantity ? tier.maxQuantity - tier.soldCount : null;

          return (
            <Col xs={24} sm={12} key={tier.id}>
              <Card
                style={{
                  height: '100%',
                  opacity: available ? 1 : 0.6,
                }}
              >
                <Title level={5} style={{ marginBottom: 4 }}>{tier.name}</Title>
                {tier.description && (
                  <Paragraph type="secondary" style={{ fontSize: 13 }}>{tier.description}</Paragraph>
                )}

                <div style={{ marginBottom: 12 }}>
                  {tier.tierType === 'FREE' ? (
                    <Tag color="green">Free</Tag>
                  ) : tier.tierType === 'DONATION' ? (
                    <Tag color="orange">
                      Donation {tier.minDonationCAD ? `(min $${(tier.minDonationCAD / 100).toFixed(2)})` : ''}
                    </Tag>
                  ) : (
                    <Text strong style={{ fontSize: 18 }}>
                      ${(tier.priceCAD / 100).toFixed(2)}
                    </Text>
                  )}
                </div>

                {remaining !== null && (
                  <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>
                    {remaining > 0 ? `${remaining} remaining` : 'Sold out'}
                  </Text>
                )}

                <Button
                  type="primary"
                  block
                  disabled={!available}
                  loading={checkingOut === tier.id}
                  onClick={() => handleCheckout(tier)}
                >
                  {!available
                    ? (remaining === 0 ? 'Sold Out' : 'Unavailable')
                    : tier.tierType === 'FREE'
                      ? 'Register Free'
                      : `Get Tickets — $${(tier.priceCAD / 100).toFixed(2)}`
                  }
                </Button>
              </Card>
            </Col>
          );
        })}
      </Row>

      {/* Online Access card for ONLINE/HYBRID events */}
      {event.eventFormat !== 'IN_PERSON' && event.hasMeeting && (
        <>
          <Divider />
          <Card
            title={<><VideoCameraOutlined style={{ marginRight: 8 }} />Online Access</>}
            style={{ marginBottom: 24 }}
          >
            <Paragraph type="secondary">
              Enter your ticket code to get your meeting link.
            </Paragraph>
            <Space.Compact style={{ width: '100%', maxWidth: 400, marginBottom: 16 }}>
              <Input
                placeholder="Enter ticket code"
                value={meetingTicketCode}
                onChange={e => setMeetingTicketCode(e.target.value)}
                onPressEnter={handleGetMeetingLink}
              />
              <Button type="primary" onClick={handleGetMeetingLink} loading={meetingLoading}>
                Get Link
              </Button>
            </Space.Compact>
            {meetingError && (
              <Text type="danger" style={{ display: 'block', marginBottom: 12 }}>{meetingError}</Text>
            )}
            {meetingAccess && (
              <Button
                type="primary"
                size="large"
                block
                style={{ maxWidth: 400 }}
                icon={<VideoCameraOutlined />}
                onClick={() => window.open(`https://${meetingAccess.domain}/${meetingAccess.jitsiRoom}`, '_blank')}
              >
                Join Meeting
              </Button>
            )}
          </Card>
        </>
      )}
    </div>
  );
}
