import { useState, useEffect, useCallback } from 'react';
import {
  Typography, Card, Row, Col, Statistic, Table, Tag, Button, Space, message,
  Tabs, Input, Popconfirm, Descriptions, Badge,
} from 'antd';
import {
  ArrowLeftOutlined, CheckCircleOutlined, UserOutlined, DollarOutlined,
  MailOutlined, ScanOutlined, CopyOutlined, TagOutlined, VideoCameraOutlined,
  EnvironmentOutlined, LinkOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import { useParams, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

const { Title, Text } = Typography;

export default function EventDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [event, setEvent] = useState<Record<string, unknown> | null>(null);
  const [stats, setStats] = useState<Record<string, unknown> | null>(null);
  const [tickets, setTickets] = useState<Record<string, unknown>[]>([]);
  const [ticketPagination, setTicketPagination] = useState({ page: 1, limit: 20, total: 0 });
  const [checkIns, setCheckIns] = useState<Record<string, unknown>[]>([]);
  const [ticketSearch, setTicketSearch] = useState('');
  const [loading, setLoading] = useState(false);
  const [joiningMeeting, setJoiningMeeting] = useState(false);

  const fetchEvent = useCallback(async () => {
    if (!id) return;
    try {
      const [eventRes, statsRes] = await Promise.all([
        api.get(`/ticketed-events/admin/${id}`),
        api.get(`/ticketed-events/admin/${id}/stats`),
      ]);
      setEvent(eventRes.data);
      setStats(statsRes.data);
    } catch {
      message.error('Failed to load event');
    }
  }, [id]);

  const fetchTickets = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    try {
      const params: Record<string, string | number> = {
        page: ticketPagination.page,
        limit: ticketPagination.limit,
      };
      if (ticketSearch) params.search = ticketSearch;
      const { data } = await api.get(`/ticketed-events/admin/${id}/tickets`, { params });
      setTickets(data.tickets);
      setTicketPagination(p => ({ ...p, total: data.pagination.total }));
    } catch {
      message.error('Failed to load tickets');
    } finally {
      setLoading(false);
    }
  }, [id, ticketPagination.page, ticketPagination.limit, ticketSearch]);

  const fetchCheckIns = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get(`/ticketed-events/admin/${id}/checkins`, { params: { limit: 50 } });
      setCheckIns(data.checkIns);
    } catch { /* silent */ }
  }, [id]);

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

  const handleResend = async (ticketId: string) => {
    try {
      await api.post(`/ticketed-events/admin/${id}/resend-ticket/${ticketId}`);
      message.success('Ticket email resent');
    } catch {
      message.error('Failed to resend');
    }
  };

  const handleCancelTicket = async (ticketId: string) => {
    try {
      await api.post(`/ticketed-events/admin/${id}/tickets/${ticketId}/cancel`);
      message.success('Ticket cancelled');
      fetchTickets();
      fetchEvent();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Failed to cancel';
      message.error(msg);
    }
  };

  const handleJoinAsModerator = async () => {
    setJoiningMeeting(true);
    try {
      const { data } = await api.post(`/ticketed-events/admin/${id}/meeting-token`);
      window.open(data.jitsiUrl, '_blank', 'noopener,noreferrer');
    } catch {
      message.error('Failed to generate meeting token');
    } finally {
      setJoiningMeeting(false);
    }
  };

  if (!event) return null;

  const e = event as Record<string, unknown>;
  const s = stats as Record<string, unknown> | null;

  const ticketColumns = [
    { title: 'Code', dataIndex: 'ticketCode', key: 'code', render: (v: string) => <Text code>{v}</Text> },
    { title: 'Holder', dataIndex: 'holderName', key: 'holder', render: (v: string, r: Record<string, unknown>) => v || (r.holderEmail as string) },
    { title: 'Email', dataIndex: 'holderEmail', key: 'email', responsive: ['lg' as const] },
    { title: 'Tier', key: 'tier', render: (_: unknown, r: Record<string, unknown>) => String((r.tier as Record<string, unknown>)?.name || '—') },
    {
      title: 'Status', dataIndex: 'status', key: 'status',
      render: (s: string) => {
        const colors: Record<string, string> = { VALID: 'green', CHECKED_IN: 'blue', CANCELLED: 'red', REFUNDED: 'orange' };
        return <Tag color={colors[s]}>{s}</Tag>;
      },
    },
    { title: 'Issued', dataIndex: 'issuedAt', key: 'issued', render: (d: string) => dayjs(d).format('MMM D, HH:mm'), responsive: ['md' as const] },
    {
      title: 'Actions', key: 'actions',
      render: (_: unknown, record: Record<string, unknown>) => (
        <Space size="small">
          <Button size="small" icon={<MailOutlined />} onClick={() => handleResend(record.id as string)}>Resend</Button>
          {record.status === 'VALID' && (
            <Popconfirm title="Cancel this ticket?" onConfirm={() => handleCancelTicket(record.id as string)}>
              <Button size="small" danger>Cancel</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  const checkInColumns = [
    { title: 'Ticket', key: 'ticket', render: (_: unknown, r: Record<string, unknown>) => {
      const t = r.ticket as Record<string, unknown>;
      return `${t?.ticketCode} — ${t?.holderName || t?.holderEmail}`;
    }},
    { title: 'Method', dataIndex: 'method', key: 'method' },
    { title: 'By', key: 'by', render: (_: unknown, r: Record<string, unknown>) => (r.checkedInBy as Record<string, unknown>)?.name || 'System' },
    { title: 'Time', dataIndex: 'checkedInAt', key: 'time', render: (d: string) => dayjs(d).format('MMM D, HH:mm:ss') },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/app/events')}>Back</Button>
        <Title level={3} style={{ margin: 0 }}>{e.title as string}</Title>
        <Tag color={
          e.status === 'PUBLISHED' ? 'success' : e.status === 'DRAFT' ? 'default' : e.status === 'CANCELLED' ? 'error' : 'warning'
        }>{(e.status as string).replace('_', ' ')}</Tag>
      </Space>

      <Descriptions bordered size="small" style={{ marginBottom: 24 }}>
        <Descriptions.Item label="Date">{dayjs(e.date as string).format('MMMM D, YYYY')}</Descriptions.Item>
        <Descriptions.Item label="Time">{e.startTime as string} – {e.endTime as string}</Descriptions.Item>
        <Descriptions.Item label="Format">{
          e.eventFormat === 'ONLINE' ? <Tag icon={<VideoCameraOutlined />} color="purple">Online</Tag>
          : e.eventFormat === 'HYBRID' ? <Tag color="geekblue"><EnvironmentOutlined /> + <VideoCameraOutlined /> Hybrid</Tag>
          : <Tag icon={<EnvironmentOutlined />}>In-Person</Tag>
        }</Descriptions.Item>
        <Descriptions.Item label="Venue">{(e.venueName as string) || '—'}</Descriptions.Item>
        <Descriptions.Item label="Visibility"><Tag>{e.visibility as string}</Tag></Descriptions.Item>
        <Descriptions.Item label="Slug">{e.slug as string}</Descriptions.Item>
        <Descriptions.Item label="Actions">
          <Space>
            <Button size="small" icon={<CopyOutlined />} onClick={() => {
              navigator.clipboard.writeText(`${window.location.origin}/event/${e.slug}`);
              message.success('Link copied');
            }}>Copy Link</Button>
            {e.status === 'PUBLISHED' && (
              <Button size="small" type="primary" icon={<ScanOutlined />}
                onClick={() => navigate(`/app/events/${id}/checkin`)}>
                Check-in Scanner
              </Button>
            )}
          </Space>
        </Descriptions.Item>
      </Descriptions>

      {/* Meeting Room card for ONLINE/HYBRID events */}
      {(e.eventFormat === 'ONLINE' || e.eventFormat === 'HYBRID') && !!e.meeting && (
        <Card size="small" title={<><VideoCameraOutlined /> Meeting Room</>} style={{ marginBottom: 24 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space>
              <Badge status={(e.meeting as Record<string, unknown>).isActive ? 'success' : 'default'}
                text={(e.meeting as Record<string, unknown>).isActive ? 'Active' : 'Inactive'} />
            </Space>
            <Space wrap>
              <Button type="primary" icon={<VideoCameraOutlined />}
                loading={joiningMeeting} onClick={handleJoinAsModerator}>
                Join as Moderator
              </Button>
              <Button icon={<LinkOutlined />} onClick={() => {
                navigator.clipboard.writeText(`${window.location.origin}/event/${e.slug}#meeting`);
                message.success('Guest link copied');
              }}>
                Copy Guest Link
              </Button>
            </Space>
          </Space>
        </Card>
      )}

      {s && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col xs={12} sm={6}>
            <Card size="small"><Statistic title="Tickets Sold" value={s.totalTickets as number} prefix={<TagOutlined />} /></Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card size="small"><Statistic title="Revenue" value={(s.totalRevenue as number) / 100} prefix={<DollarOutlined />} precision={2} /></Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card size="small"><Statistic title="Checked In" value={s.checkedIn as number} prefix={<CheckCircleOutlined />} /></Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card size="small"><Statistic title="Capacity" value={e.maxAttendees ? `${e.currentAttendees}/${e.maxAttendees}` : `${e.currentAttendees}`} prefix={<UserOutlined />} /></Card>
          </Col>
        </Row>
      )}

      {s && (s.tierStats as unknown[])?.length > 0 && (
        <Card size="small" title="Tier Breakdown" style={{ marginBottom: 24 }}>
          <Table
            dataSource={s.tierStats as Record<string, unknown>[]}
            rowKey="id"
            pagination={false}
            size="small"
            scroll={{ x: 'max-content' }}
            columns={[
              { title: 'Tier', dataIndex: 'name', key: 'name' },
              { title: 'Type', dataIndex: 'tierType', key: 'type', render: (v: string) => <Tag>{v}</Tag> },
              { title: 'Price', dataIndex: 'priceCAD', key: 'price', render: (v: number) => v > 0 ? `$${(v / 100).toFixed(2)}` : 'Free' },
              { title: 'Sold', key: 'sold', render: (_: unknown, r: Record<string, unknown>) => {
                const max = r.maxQuantity as number | null;
                return max ? `${r.soldCount}/${max}` : String(r.soldCount);
              }},
              { title: 'Active', dataIndex: 'isActive', key: 'active', render: (v: boolean) => v ? <Badge status="success" text="Yes" /> : <Badge status="default" text="No" /> },
            ]}
          />
        </Card>
      )}

      <Tabs items={[
        {
          key: 'tickets',
          label: `Tickets (${ticketPagination.total})`,
          children: (
            <>
              <Input
                placeholder="Search by name, email, or code..."
                prefix={<UserOutlined />}
                value={ticketSearch}
                onChange={e => setTicketSearch(e.target.value)}
                style={{ maxWidth: 300, width: '100%', marginBottom: 16 }}
                allowClear
              />
              <Table
                dataSource={tickets}
                columns={ticketColumns}
                rowKey="id"
                loading={loading}
                size="small"
                scroll={{ x: 'max-content' }}
                pagination={{
                  current: ticketPagination.page,
                  pageSize: ticketPagination.limit,
                  total: ticketPagination.total,
                  onChange: (page, pageSize) => setTicketPagination(p => ({ ...p, page, limit: pageSize })),
                }}
              />
            </>
          ),
        },
        {
          key: 'checkins',
          label: `Check-ins (${checkIns.length})`,
          children: (
            <Table
              dataSource={checkIns}
              columns={checkInColumns}
              rowKey="id"
              size="small"
              scroll={{ x: 'max-content' }}
              pagination={{ pageSize: 20 }}
            />
          ),
        },
      ]} />
    </div>
  );
}
