import { useState, useEffect, useCallback } from 'react';
import {
  Typography, Table, Button, Space, Tag, Input, Select, message, Drawer, Form,
  DatePicker, TimePicker, InputNumber, Divider, Card, Row, Col, Popconfirm,
  Tooltip, Radio, Alert,
} from 'antd';
import {
  PlusOutlined, SearchOutlined, EditOutlined, EyeOutlined, DeleteOutlined,
  CheckCircleOutlined, CloseCircleOutlined, CopyOutlined, ScanOutlined,
  TagOutlined, VideoCameraOutlined, EnvironmentOutlined, StarOutlined, StarFilled,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;

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

interface TicketedEvent {
  id: string;
  slug: string;
  title: string;
  description: string | null;
  date: string;
  startTime: string;
  endTime: string;
  doorsOpenTime: string | null;
  eventFormat: 'IN_PERSON' | 'ONLINE' | 'HYBRID';
  venueName: string | null;
  venueAddress: string | null;
  status: string;
  visibility: string;
  maxAttendees: number | null;
  currentAttendees: number;
  coverImageUrl: string | null;
  organizerName: string | null;
  featured: boolean;
  ticketTiers: TicketTier[];
  _count: { tickets: number; checkIns: number };
  createdAt: string;
}

const STATUS_COLORS: Record<string, string> = {
  DRAFT: 'default',
  PENDING_APPROVAL: 'warning',
  PUBLISHED: 'success',
  CANCELLED: 'error',
  COMPLETED: 'blue',
};

const VISIBILITY_COLORS: Record<string, string> = {
  PUBLIC: 'green',
  UNLISTED: 'orange',
  PRIVATE: 'red',
};

export default function TicketedEventsPage() {
  const navigate = useNavigate();
  const [events, setEvents] = useState<TicketedEvent[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0 });
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<string | undefined>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editingEvent, setEditingEvent] = useState<TicketedEvent | null>(null);
  const [form] = Form.useForm();
  const [saving, setSaving] = useState(false);
  const [enableMeet, setEnableMeet] = useState(false);
  const watchedFormat = Form.useWatch('eventFormat', form);

  const fetchEvents = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string | number> = {
        page: pagination.page,
        limit: pagination.limit,
      };
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;

      const { data } = await api.get('/ticketed-events/admin', { params });
      setEvents(data.events);
      setPagination(p => ({ ...p, total: data.pagination.total }));
    } catch {
      message.error('Failed to load events');
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.limit, search, statusFilter]);

  useEffect(() => { fetchEvents(); }, [fetchEvents]);
  useEffect(() => {
    api.get('/settings').then(({ data }) => setEnableMeet(!!data.enableMeet)).catch(() => {});
  }, []);

  const handleCreate = () => {
    setEditingEvent(null);
    form.resetFields();
    form.setFieldsValue({
      eventFormat: 'IN_PERSON',
      visibility: 'PUBLIC',
      tiers: [{ name: 'General Admission', tierType: 'FREE', priceCAD: 0, maxPerOrder: 10, sortOrder: 0 }],
    });
    setDrawerOpen(true);
  };

  const handleEdit = (event: TicketedEvent) => {
    setEditingEvent(event);
    form.setFieldsValue({
      ...event,
      date: dayjs(event.date),
      startTime: dayjs(event.startTime, 'HH:mm'),
      endTime: dayjs(event.endTime, 'HH:mm'),
      doorsOpenTime: event.doorsOpenTime ? dayjs(event.doorsOpenTime, 'HH:mm') : undefined,
    });
    setDrawerOpen(true);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);

      const payload = {
        ...values,
        date: values.date.format('YYYY-MM-DD'),
        startTime: values.startTime.format('HH:mm'),
        endTime: values.endTime.format('HH:mm'),
        doorsOpenTime: values.doorsOpenTime?.format('HH:mm') || undefined,
      };

      if (editingEvent) {
        const { tiers, ...eventData } = payload;
        await api.put(`/api/ticketed-events/admin/${editingEvent.id}`, eventData);
      } else {
        await api.post('/ticketed-events/admin', payload);
      }

      message.success(editingEvent ? 'Event updated' : 'Event created');
      setDrawerOpen(false);
      fetchEvents();
    } catch {
      message.error('Failed to save event');
    } finally {
      setSaving(false);
    }
  };

  const handlePublish = async (id: string) => {
    try {
      await api.post(`/api/ticketed-events/admin/${id}/publish`);
      message.success('Event published');
      fetchEvents();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Failed to publish';
      message.error(msg);
    }
  };

  const handleCancel = async (id: string) => {
    try {
      await api.post(`/api/ticketed-events/admin/${id}/cancel`);
      message.success('Event cancelled');
      fetchEvents();
    } catch {
      message.error('Failed to cancel event');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/api/ticketed-events/admin/${id}`);
      message.success('Event deleted');
      fetchEvents();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Failed to delete';
      message.error(msg);
    }
  };

  const handleApprove = async (id: string) => {
    try {
      await api.post(`/api/ticketed-events/admin/${id}/approve`);
      message.success('Event approved and published');
      fetchEvents();
    } catch {
      message.error('Failed to approve event');
    }
  };

  const handleFeature = async (id: string, featured: boolean) => {
    try {
      if (featured) {
        // Unfeature all others first (exclusive toggle)
        const othersToUnfeature = events.filter((e) => e.featured && e.id !== id);
        await Promise.all(
          othersToUnfeature.map((e) => api.put(`/api/ticketed-events/admin/${e.id}`, { featured: false }))
        );
      }
      await api.put(`/api/ticketed-events/admin/${id}`, { featured });
      message.success(featured ? 'Event featured on volunteer dashboard' : 'Event unfeatured');
      fetchEvents();
    } catch {
      message.error('Failed to update featured status');
    }
  };

  const copyLink = (slug: string) => {
    navigator.clipboard.writeText(`${window.location.origin}/event/${slug}`);
    message.success('Link copied');
  };

  const columns = [
    {
      title: '',
      key: 'featured',
      width: 36,
      render: (_: unknown, record: TicketedEvent) => (
        <Tooltip title={record.featured ? 'Remove from volunteer dashboard' : 'Feature on volunteer dashboard'}>
          <Button
            type="text"
            size="small"
            icon={record.featured
              ? <StarFilled style={{ color: '#faad14' }} />
              : <StarOutlined style={{ color: 'rgba(255,255,255,0.25)' }} />}
            onClick={(e) => { e.stopPropagation(); handleFeature(record.id, !record.featured); }}
          />
        </Tooltip>
      ),
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: TicketedEvent) => (
        <Space>
          <a onClick={() => navigate(`/app/events/${record.id}`)}>{text}</a>
          {record.featured && <Tag color="gold" style={{ fontSize: 11 }}>Featured</Tag>}
        </Space>
      ),
    },
    {
      title: 'Date',
      dataIndex: 'date',
      key: 'date',
      render: (d: string, r: TicketedEvent) => (
        <span>{dayjs(d).format('MMM D, YYYY')} {r.startTime}</span>
      ),
      sorter: true,
    },
    {
      title: 'Format',
      dataIndex: 'eventFormat',
      key: 'format',
      responsive: ['md' as const],
      render: (f: string) => {
        if (f === 'ONLINE') return <Tag icon={<VideoCameraOutlined />} color="purple">Online</Tag>;
        if (f === 'HYBRID') return <Tag color="geekblue"><EnvironmentOutlined /> + <VideoCameraOutlined /></Tag>;
        return <Tag icon={<EnvironmentOutlined />}>In-Person</Tag>;
      },
    },
    {
      title: 'Venue',
      dataIndex: 'venueName',
      key: 'venue',
      responsive: ['lg' as const],
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (s: string) => <Tag color={STATUS_COLORS[s]}>{s.replace('_', ' ')}</Tag>,
    },
    {
      title: 'Visibility',
      dataIndex: 'visibility',
      key: 'visibility',
      responsive: ['md' as const],
      render: (v: string) => <Tag color={VISIBILITY_COLORS[v]}>{v}</Tag>,
    },
    {
      title: 'Tickets',
      key: 'tickets',
      render: (_: unknown, r: TicketedEvent) => {
        const sold = r._count.tickets;
        const max = r.maxAttendees;
        return max ? `${sold} / ${max}` : `${sold}`;
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, record: TicketedEvent) => (
        <Space size="small">
          <Tooltip title="Edit"><Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} /></Tooltip>
          <Tooltip title="Detail"><Button size="small" icon={<EyeOutlined />} onClick={() => navigate(`/app/events/${record.id}`)} /></Tooltip>
          {record.status === 'DRAFT' && (
            <Tooltip title="Publish"><Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => handlePublish(record.id)} /></Tooltip>
          )}
          {record.status === 'PENDING_APPROVAL' && (
            <Tooltip title="Approve"><Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => handleApprove(record.id)} /></Tooltip>
          )}
          {record.status === 'PUBLISHED' && (
            <>
              <Tooltip title="Copy Link"><Button size="small" icon={<CopyOutlined />} onClick={() => copyLink(record.slug)} /></Tooltip>
              <Tooltip title="Check-in Scanner"><Button size="small" icon={<ScanOutlined />} onClick={() => navigate(`/app/events/${record.id}/checkin`)} /></Tooltip>
              <Popconfirm title="Cancel this event?" onConfirm={() => handleCancel(record.id)}>
                <Tooltip title="Cancel"><Button size="small" danger icon={<CloseCircleOutlined />} /></Tooltip>
              </Popconfirm>
            </>
          )}
          {record.status === 'DRAFT' && (
            <Popconfirm title="Delete this draft?" onConfirm={() => handleDelete(record.id)}>
              <Tooltip title="Delete"><Button size="small" danger icon={<DeleteOutlined />} /></Tooltip>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={3} style={{ margin: 0 }}>
          <TagOutlined style={{ marginRight: 8 }} />
          Ticketed Events
        </Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          Create Event
        </Button>
      </div>

      <Space style={{ marginBottom: 16 }} wrap>
        <Input
          placeholder="Search events..."
          prefix={<SearchOutlined />}
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{ width: 240 }}
          allowClear
        />
        <Select
          placeholder="Filter by status"
          value={statusFilter}
          onChange={setStatusFilter}
          allowClear
          style={{ width: 180 }}
          options={[
            { value: 'DRAFT', label: 'Draft' },
            { value: 'PENDING_APPROVAL', label: 'Pending Approval' },
            { value: 'PUBLISHED', label: 'Published' },
            { value: 'CANCELLED', label: 'Cancelled' },
            { value: 'COMPLETED', label: 'Completed' },
          ]}
        />
      </Space>

      <Table
        dataSource={events}
        columns={columns}
        rowKey="id"
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{
          current: pagination.page,
          pageSize: pagination.limit,
          total: pagination.total,
          showSizeChanger: true,
          onChange: (page, pageSize) => setPagination(p => ({ ...p, page, limit: pageSize })),
        }}
      />

      <Drawer
        title={editingEvent ? 'Edit Event' : 'Create Event'}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={640}
        extra={
          <Button type="primary" onClick={handleSave} loading={saving}>
            {editingEvent ? 'Update' : 'Create'}
          </Button>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="Title" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} />
          </Form.Item>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="date" label="Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="startTime" label="Start Time" rules={[{ required: true }]}>
                <TimePicker format="HH:mm" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="endTime" label="End Time" rules={[{ required: true }]}>
                <TimePicker format="HH:mm" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="doorsOpenTime" label="Doors Open Time">
            <TimePicker format="HH:mm" style={{ width: '100%' }} />
          </Form.Item>

          <Divider>Event Format</Divider>
          <Form.Item name="eventFormat" label="Format" initialValue="IN_PERSON">
            <Radio.Group>
              <Radio.Button value="IN_PERSON"><EnvironmentOutlined /> In-Person</Radio.Button>
              <Tooltip title={!enableMeet ? 'Enable Jitsi Meet in Settings first' : undefined}>
                <Radio.Button value="ONLINE" disabled={!enableMeet}><VideoCameraOutlined /> Online</Radio.Button>
              </Tooltip>
              <Tooltip title={!enableMeet ? 'Enable Jitsi Meet in Settings first' : undefined}>
                <Radio.Button value="HYBRID" disabled={!enableMeet}><EnvironmentOutlined /> + <VideoCameraOutlined /> Hybrid</Radio.Button>
              </Tooltip>
            </Radio.Group>
          </Form.Item>

          {watchedFormat === 'ONLINE' && (
            <Alert type="info" message="A meeting room will be auto-created when you save this event." showIcon style={{ marginBottom: 16 }} />
          )}
          {watchedFormat === 'HYBRID' && (
            <Alert type="info" message="A meeting room will be auto-created alongside your venue." showIcon style={{ marginBottom: 16 }} />
          )}

          {watchedFormat !== 'ONLINE' && (
            <>
              <Divider>Venue</Divider>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item name="venueName" label="Venue Name">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name="venueAddress" label="Venue Address">
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
            </>
          )}

          <Divider>Settings</Divider>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="visibility" label="Visibility" initialValue="PUBLIC">
                <Select options={[
                  { value: 'PUBLIC', label: 'Public' },
                  { value: 'UNLISTED', label: 'Unlisted' },
                  { value: 'PRIVATE', label: 'Private (Invite Only)' },
                ]} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="maxAttendees" label="Max Attendees">
                <InputNumber min={1} style={{ width: '100%' }} placeholder="Unlimited" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="organizerName" label="Organizer Name">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="organizerEmail" label="Organizer Email">
                <Input type="email" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="coverImageUrl" label="Cover Image URL">
            <Input placeholder="https://..." />
          </Form.Item>

          {!editingEvent && (
            <>
              <Divider>Ticket Tiers</Divider>
              <Form.List name="tiers">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...rest }) => (
                      <Card key={key} size="small" style={{ marginBottom: 12 }}
                        extra={fields.length > 1 && <Button size="small" danger onClick={() => remove(name)}>Remove</Button>}
                      >
                        <Row gutter={12}>
                          <Col span={12}>
                            <Form.Item {...rest} name={[name, 'name']} label="Tier Name" rules={[{ required: true }]}>
                              <Input placeholder="e.g. General Admission" />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item {...rest} name={[name, 'tierType']} label="Type" rules={[{ required: true }]}>
                              <Select options={[
                                { value: 'FREE', label: 'Free' },
                                { value: 'PAID', label: 'Paid' },
                                { value: 'DONATION', label: 'Donation' },
                              ]} />
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={12}>
                          <Col span={8}>
                            <Form.Item {...rest} name={[name, 'priceCAD']} label="Price (cents)">
                              <InputNumber min={0} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item {...rest} name={[name, 'maxQuantity']} label="Max Quantity">
                              <InputNumber min={1} style={{ width: '100%' }} placeholder="Unlimited" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item {...rest} name={[name, 'maxPerOrder']} label="Max Per Order" initialValue={10}>
                              <InputNumber min={1} max={100} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Card>
                    ))}
                    <Button type="dashed" onClick={() => add({ tierType: 'FREE', priceCAD: 0, maxPerOrder: 10, sortOrder: fields.length })} block icon={<PlusOutlined />}>
                      Add Tier
                    </Button>
                  </>
                )}
              </Form.List>
            </>
          )}
        </Form>
      </Drawer>
    </div>
  );
}
