import { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Tag,
  Space,
  Form,
  Switch,
  Popconfirm,
  message,
  Typography,
  Row,
  Col,
  DatePicker,
  TimePicker,
  Drawer,
  Card,
  Tooltip,
  Grid,
  Divider,
  Modal,
  InputNumber,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  SearchOutlined,
  CalendarOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  TeamOutlined,
  EditOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type {
  SchedulingPoll,
  PollsListResponse,
  PollDetailResponse,
  SchedulingPollStatus,
  PollVoteValue,
} from '@/types/api';
import {
  POLL_STATUS_COLORS,
  POLL_STATUS_LABELS,
  VOTE_VALUE_COLORS,
  VOTE_VALUE_LABELS,
} from '@/types/api';

const { Text, Title } = Typography;

const TIMEZONE_OPTIONS = [
  'America/Vancouver',
  'America/Edmonton',
  'America/Regina',
  'America/Winnipeg',
  'America/Toronto',
  'America/Halifax',
  'America/St_Johns',
  'America/New_York',
  'America/Chicago',
  'America/Denver',
  'America/Los_Angeles',
];

export default function MeetingPlannerPage() {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [polls, setPolls] = useState<SchedulingPoll[]>([]);
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<SchedulingPollStatus | undefined>();

  // Create drawer
  const [createOpen, setCreateOpen] = useState(false);
  const [createForm] = Form.useForm();
  const [creating, setCreating] = useState(false);

  // Detail drawer
  const [detailOpen, setDetailOpen] = useState(false);
  const [selectedPoll, setSelectedPoll] = useState<PollDetailResponse | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  // Finalize modal
  const [finalizeOpen, setFinalizeOpen] = useState(false);
  const [selectedOptionId, setSelectedOptionId] = useState<string>('');
  const [finalizing, setFinalizing] = useState(false);

  // Convert modal
  const [convertOpen, setConvertOpen] = useState(false);
  const [convertForm] = Form.useForm();
  const [converting, setConverting] = useState(false);

  // Prep checklist (participant needs aggregate)
  const [needsSummary, setNeedsSummary] = useState<any>(null);
  const [needsLoading, setNeedsLoading] = useState(false);

  // Edit drawer
  const [editOpen, setEditOpen] = useState(false);
  const [editForm] = Form.useForm();
  const [editing, setEditing] = useState(false);
  const [editPoll, setEditPoll] = useState<PollDetailResponse | null>(null);
  const [newOptionDate, setNewOptionDate] = useState<dayjs.Dayjs | null>(null);
  const [newOptionStart, setNewOptionStart] = useState<dayjs.Dayjs | null>(null);
  const [newOptionEnd, setNewOptionEnd] = useState<dayjs.Dayjs | null>(null);

  const fetchPolls = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, any> = { page: pagination.page, limit: pagination.limit };
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;
      const { data } = await api.get<PollsListResponse>('/meeting-planner', { params });
      setPolls(data.polls);
      setPagination((p) => ({ ...p, total: data.pagination.total }));
    } catch {
      message.error('Failed to load polls');
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.limit, search, statusFilter]);

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

  const fetchPollDetail = async (id: string) => {
    setDetailLoading(true);
    try {
      const { data } = await api.get<PollDetailResponse>(`/meeting-planner/${id}`);
      setSelectedPoll(data);
      setDetailOpen(true);
      fetchNeedsSummary(data);
    } catch {
      message.error('Failed to load poll details');
    } finally {
      setDetailLoading(false);
    }
  };

  const fetchNeedsSummary = async (pollDetail: PollDetailResponse) => {
    if (pollDetail.status !== 'FINALIZED') { setNeedsSummary(null); return; }
    setNeedsLoading(true);
    try {
      // Collect userIds and contactIds from YES voters on finalized option
      const yesVotes = pollDetail.votes?.filter(
        (v) => v.optionId === pollDetail.finalizedOptionId && v.value === 'YES'
      ) || [];
      const userIds = yesVotes.map((v) => v.userId).filter(Boolean);
      const contactIds = yesVotes.map((v) => v.contactId).filter(Boolean);
      if (userIds.length === 0 && contactIds.length === 0) { setNeedsSummary(null); setNeedsLoading(false); return; }
      const params: string[] = [];
      if (userIds.length) params.push(`userIds=${userIds.join(',')}`);
      if (contactIds.length) params.push(`contactIds=${contactIds.join(',')}`);
      const { data } = await api.get(`/people/needs/aggregate?${params.join('&')}`);
      setNeedsSummary(data.summary);
    } catch {
      setNeedsSummary(null);
    } finally {
      setNeedsLoading(false);
    }
  };

  const handleCreate = async (values: any) => {
    setCreating(true);
    try {
      const options = values.options.map((opt: any) => ({
        date: opt.date.format('YYYY-MM-DD'),
        startTime: opt.startTime.format('HH:mm'),
        endTime: opt.endTime.format('HH:mm'),
      }));
      await api.post('/meeting-planner', {
        title: values.title,
        description: values.description,
        location: values.location,
        timezone: values.timezone,
        allowAnonymous: values.allowAnonymous ?? true,
        isPrivate: values.isPrivate ?? false,
        notifyOnVote: values.notifyOnVote ?? true,
        votingDeadline: values.votingDeadline?.toISOString(),
        autoFinalize: values.autoFinalize ?? false,
        autoFinalizeThreshold: values.autoFinalizeThreshold ?? null,
        autoConvertToCalendar: values.autoConvertToCalendar ?? false,
        autoConvertToGancio: values.autoConvertToGancio ?? false,
        autoConvertToShift: values.autoConvertToShift ?? false,
        tieBreaker: values.tieBreaker ?? 'earliest',
        autoEnrollVoters: values.autoEnrollVoters ?? true,
        options,
      });
      message.success('Poll created');
      setCreateOpen(false);
      createForm.resetFields();
      fetchPolls();
    } catch {
      message.error('Failed to create poll');
    } finally {
      setCreating(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/meeting-planner/${id}`);
      message.success('Poll deleted');
      fetchPolls();
    } catch {
      message.error('Failed to delete poll');
    }
  };

  const handleFinalize = async () => {
    if (!selectedPoll || !selectedOptionId) return;
    setFinalizing(true);
    try {
      await api.post(`/meeting-planner/${selectedPoll.id}/finalize`, {
        optionId: selectedOptionId,
      });
      message.success('Poll finalized');
      setFinalizeOpen(false);
      fetchPollDetail(selectedPoll.id);
      fetchPolls();
    } catch {
      message.error('Failed to finalize poll');
    } finally {
      setFinalizing(false);
    }
  };

  const handleConvertToShift = async (values: any) => {
    if (!selectedPoll) return;
    setConverting(true);
    try {
      await api.post(`/meeting-planner/${selectedPoll.id}/convert-to-shift`, {
        maxVolunteers: values.maxVolunteers,
        isPublic: values.isPublic ?? true,
      });
      message.success('Converted to shift');
      setConvertOpen(false);
      convertForm.resetFields();
      fetchPollDetail(selectedPoll.id);
    } catch {
      message.error('Failed to convert to shift');
    } finally {
      setConverting(false);
    }
  };

  const handleConvertToEvent = async () => {
    if (!selectedPoll) return;
    try {
      await api.post(`/meeting-planner/${selectedPoll.id}/convert-to-event`);
      message.success('Converted to Gancio event');
      fetchPollDetail(selectedPoll.id);
    } catch {
      message.error('Failed to convert to event');
    }
  };

  const handleDeleteComment = async (commentId: string) => {
    if (!selectedPoll) return;
    try {
      await api.delete(`/meeting-planner/${selectedPoll.id}/comments/${commentId}`);
      message.success('Comment deleted');
      fetchPollDetail(selectedPoll.id);
    } catch {
      message.error('Failed to delete comment');
    }
  };

  const handleRemoveVoter = async (voterKey: string) => {
    if (!selectedPoll) return;
    try {
      await api.delete(`/meeting-planner/${selectedPoll.id}/voters/${encodeURIComponent(voterKey)}`);
      message.success('Voter removed');
      fetchPollDetail(selectedPoll.id);
    } catch {
      message.error('Failed to remove voter');
    }
  };

  const openEditDrawer = async (id: string) => {
    try {
      const { data } = await api.get<PollDetailResponse>(`/meeting-planner/${id}`);
      setEditPoll(data);
      editForm.setFieldsValue({
        title: data.title,
        description: data.description || '',
        location: data.location || '',
        timezone: data.timezone,
        allowAnonymous: data.allowAnonymous,
        isPrivate: data.isPrivate,
        notifyOnVote: data.notifyOnVote,
        votingDeadline: data.votingDeadline ? dayjs(data.votingDeadline) : null,
      });
      setEditOpen(true);
    } catch {
      message.error('Failed to load poll');
    }
  };

  const handleUpdate = async (values: any) => {
    if (!editPoll) return;
    setEditing(true);
    try {
      await api.put(`/meeting-planner/${editPoll.id}`, {
        title: values.title,
        description: values.description || null,
        location: values.location || null,
        timezone: values.timezone,
        allowAnonymous: values.allowAnonymous,
        isPrivate: values.isPrivate,
        notifyOnVote: values.notifyOnVote,
        votingDeadline: values.votingDeadline?.toISOString() || null,
      });
      message.success('Poll updated');
      setEditOpen(false);
      setEditPoll(null);
      editForm.resetFields();
      fetchPolls();
      // Refresh detail drawer if same poll is open
      if (selectedPoll?.id === editPoll.id) {
        fetchPollDetail(editPoll.id);
      }
    } catch {
      message.error('Failed to update poll');
    } finally {
      setEditing(false);
    }
  };

  const handleUpdateOption = async (optionId: string, field: string, value: string) => {
    if (!editPoll) return;
    // Optimistic update: immediately reflect the change in local state
    const optimisticDate = field === 'date' ? value + 'T00:00:00.000Z' : undefined;
    setEditPoll((prev) => prev ? {
      ...prev,
      options: prev.options.map((opt: any) =>
        opt.id === optionId
          ? { ...opt, [field]: optimisticDate ?? value }
          : opt
      ),
    } : prev);
    try {
      await api.put(`/meeting-planner/${editPoll.id}/options/${optionId}`, { [field]: value });
      message.success('Option updated');
    } catch {
      // Revert on failure by refetching
      const { data } = await api.get<PollDetailResponse>(`/meeting-planner/${editPoll.id}`);
      setEditPoll(data);
      message.error('Failed to update option');
    }
  };

  const handleAddOption = async (option: { date: string; startTime: string; endTime: string }) => {
    if (!editPoll) return;
    try {
      await api.post(`/meeting-planner/${editPoll.id}/options`, { options: [option] });
      message.success('Option added');
      // Refresh edit poll data
      const { data } = await api.get<PollDetailResponse>(`/meeting-planner/${editPoll.id}`);
      setEditPoll(data);
    } catch {
      message.error('Failed to add option');
    }
  };

  const handleRemoveOption = async (optionId: string) => {
    if (!editPoll) return;
    try {
      await api.delete(`/meeting-planner/${editPoll.id}/options/${optionId}`);
      message.success('Option removed');
      const { data } = await api.get<PollDetailResponse>(`/meeting-planner/${editPoll.id}`);
      setEditPoll(data);
    } catch {
      message.error('Failed to remove option');
    }
  };

  const copyShareLink = (slug: string) => {
    const url = `${window.location.origin}/poll/${slug}`;
    navigator.clipboard.writeText(url);
    message.success('Share link copied');
  };

  const columns: ColumnsType<SchedulingPoll> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record) => (
        <Button type="link" onClick={() => fetchPollDetail(record.id)} style={{ padding: 0 }}>
          {title}
        </Button>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 110,
      render: (status: SchedulingPollStatus) => (
        <Tag color={POLL_STATUS_COLORS[status]}>{POLL_STATUS_LABELS[status]}</Tag>
      ),
    },
    {
      title: 'Options',
      key: 'options',
      width: 80,
      render: (_, record) => record._count?.options ?? 0,
    },
    {
      title: 'Votes',
      key: 'votes',
      width: 80,
      render: (_, record) => record._count?.votes ?? 0,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: string) => dayjs(date).format('MMM D, YYYY'),
      responsive: ['md'],
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 140,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="Edit poll">
            <Button size="small" icon={<EditOutlined />} onClick={() => openEditDrawer(record.id)} />
          </Tooltip>
          <Tooltip title="Copy share link">
            <Button size="small" icon={<CopyOutlined />} onClick={() => copyShareLink(record.slug)} />
          </Tooltip>
          <Popconfirm title="Delete this poll?" onConfirm={() => handleDelete(record.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // --- Voting Matrix Component ---
  const VotingMatrix = ({ poll }: { poll: PollDetailResponse }) => {
    if (!poll.options?.length) return <Text type="secondary">No options yet</Text>;

    const bestScore = Math.max(...poll.options.map((o) => o.score ?? 0));

    return (
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr>
              <th style={{ padding: '8px 12px', borderBottom: '2px solid #303030', textAlign: 'left', minWidth: 120 }}>
                Voter
              </th>
              <th style={{ padding: '8px 4px', borderBottom: '2px solid #303030', width: 36 }} />
              {poll.options.map((opt) => (
                <th
                  key={opt.id}
                  style={{
                    padding: '8px 12px',
                    borderBottom: '2px solid #303030',
                    textAlign: 'center',
                    minWidth: 100,
                    background: opt.score === bestScore && bestScore > 0 ? 'rgba(82, 196, 26, 0.1)' : undefined,
                  }}
                >
                  <div>{dayjs(opt.date).format('MMM D')}</div>
                  <div style={{ fontSize: 11, opacity: 0.7 }}>{opt.startTime}–{opt.endTime}</div>
                  {poll.finalizedOptionId === opt.id && (
                    <Tag color="blue" style={{ marginTop: 4 }}>Selected</Tag>
                  )}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {poll.voters?.map((voter, i) => (
              <tr key={i}>
                <td style={{ padding: '6px 12px', borderBottom: '1px solid #303030' }}>
                  {voter.name}
                </td>
                <td style={{ padding: '6px 4px', borderBottom: '1px solid #303030', textAlign: 'center' }}>
                  <Popconfirm
                    title={`Remove ${voter.name}'s votes?`}
                    onConfirm={() => handleRemoveVoter(voter.voterKey)}
                  >
                    <Button size="small" type="text" danger icon={<DeleteOutlined />} />
                  </Popconfirm>
                </td>
                {poll.options.map((opt) => {
                  const value = voter.votes[opt.id] as PollVoteValue | undefined;
                  return (
                    <td
                      key={opt.id}
                      style={{
                        padding: '6px 12px',
                        borderBottom: '1px solid #303030',
                        textAlign: 'center',
                        background: value ? `${VOTE_VALUE_COLORS[value]}20` : undefined,
                      }}
                    >
                      {value ? (
                        <Tag
                          color={value === 'YES' ? 'green' : value === 'IF_NEED_BE' ? 'gold' : 'default'}
                          style={{ margin: 0 }}
                        >
                          {VOTE_VALUE_LABELS[value]}
                        </Tag>
                      ) : (
                        <Text type="secondary">—</Text>
                      )}
                    </td>
                  );
                })}
              </tr>
            ))}
            {/* Tally row */}
            <tr style={{ fontWeight: 600 }}>
              <td style={{ padding: '8px 12px', borderTop: '2px solid #303030' }}>Score</td>
              <td style={{ borderTop: '2px solid #303030' }} />
              {poll.options.map((opt) => (
                <td
                  key={opt.id}
                  style={{
                    padding: '8px 12px',
                    borderTop: '2px solid #303030',
                    textAlign: 'center',
                    background: opt.score === bestScore && bestScore > 0 ? 'rgba(82, 196, 26, 0.15)' : undefined,
                  }}
                >
                  <div>{opt.score ?? 0}</div>
                  <div style={{ fontSize: 11, opacity: 0.7 }}>
                    {opt.yesCount}Y / {opt.ifNeedBeCount}M / {opt.noCount}N
                  </div>
                </td>
              ))}
            </tr>
          </tbody>
        </table>
      </div>
    );
  };

  // Calculate active drawer width for content adjustment
  const getActiveDrawerWidth = () => {
    if (createOpen) return 560;
    if (editOpen) return 560;
    if (detailOpen) return 720;
    return 0;
  };
  const activeDrawerWidth = getActiveDrawerWidth();

  return (
    <div style={{ padding: screens.md ? 24 : 16 }}>
      {/* Main content shifts left when drawer opens */}
      <div
        style={{
          marginRight: isMobile ? 0 : activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Col>
          <Title level={4} style={{ margin: 0 }}>
            <CalendarOutlined style={{ marginRight: 8 }} />
            Meeting Planner
          </Title>
        </Col>
        <Col>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
            {screens.md ? 'Create Poll' : 'New'}
          </Button>
        </Col>
      </Row>

      {/* Filters */}
      <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={8}>
          <Input
            placeholder="Search polls..."
            prefix={<SearchOutlined />}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            allowClear
          />
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Select
            placeholder="Filter by status"
            style={{ width: '100%' }}
            allowClear
            value={statusFilter}
            onChange={setStatusFilter}
            options={Object.entries(POLL_STATUS_LABELS).map(([value, label]) => ({ value, label }))}
          />
        </Col>
      </Row>

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

      {/* Create Poll Drawer */}
      <Drawer
        title="Create Scheduling Poll"
        open={createOpen}
        onClose={() => { setCreateOpen(false); createForm.resetFields(); }}
        width={isMobile ? '100%' : 560}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Space>
            <Button onClick={() => { setCreateOpen(false); createForm.resetFields(); }} disabled={creating}>
              Cancel
            </Button>
            <Button type="primary" loading={creating} onClick={() => createForm.submit()}>
              Create
            </Button>
          </Space>
        }
      >
        <Form
          form={createForm}
          layout="vertical"
          onFinish={handleCreate}
          initialValues={{
            timezone: 'America/Edmonton',
            allowAnonymous: true,
            isPrivate: false,
            notifyOnVote: true,
            autoFinalize: false,
            autoConvertToCalendar: false,
            autoConvertToGancio: false,
            autoConvertToShift: false,
            tieBreaker: 'earliest',
            autoEnrollVoters: true,
            options: [
              { date: null, startTime: null, endTime: null },
            ],
          }}
        >
          <Form.Item name="title" label="Title" rules={[{ required: true }]}>
            <Input placeholder="e.g., Team Planning Meeting" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} placeholder="What is this meeting about?" />
          </Form.Item>
          <Form.Item name="location" label="Location">
            <Input placeholder="e.g., Community Centre Room 204" />
          </Form.Item>
          <Form.Item name="timezone" label="Timezone">
            <Select options={TIMEZONE_OPTIONS.map((tz) => ({ value: tz, label: tz }))} />
          </Form.Item>

          <Divider>Date/Time Options</Divider>

          <Form.List name="options">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name }) => (
                  <Row key={key} gutter={8} align="middle" style={{ marginBottom: 8 }}>
                    <Col flex="auto">
                      <Space wrap>
                        <Form.Item name={[name, 'date']} noStyle rules={[{ required: true, message: 'Date required' }]}>
                          <DatePicker format="YYYY-MM-DD" placeholder="Date" />
                        </Form.Item>
                        <Form.Item name={[name, 'startTime']} noStyle rules={[{ required: true, message: 'Start required' }]}>
                          <TimePicker format="HH:mm" minuteStep={15} placeholder="Start" />
                        </Form.Item>
                        <Form.Item name={[name, 'endTime']} noStyle rules={[{ required: true, message: 'End required' }]}>
                          <TimePicker format="HH:mm" minuteStep={15} placeholder="End" />
                        </Form.Item>
                      </Space>
                    </Col>
                    <Col>
                      {fields.length > 1 && (
                        <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
                      )}
                    </Col>
                  </Row>
                ))}
                <Button
                  type="dashed"
                  onClick={() => add({ date: null, startTime: null, endTime: null })}
                  block
                  icon={<PlusOutlined />}
                  disabled={fields.length >= 20}
                >
                  Add Option
                </Button>
              </>
            )}
          </Form.List>

          <Divider>Settings</Divider>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="allowAnonymous" label="Allow Anonymous" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="isPrivate" label="Private Poll" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="notifyOnVote" label="Notify on Vote" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="votingDeadline" label="Voting Deadline (optional)">
            <DatePicker showTime format="YYYY-MM-DD HH:mm" style={{ width: '100%' }} />
          </Form.Item>

          <Divider>Auto-Finalize</Divider>

          <Form.Item name="autoFinalize" label="Automatically finalize this poll" valuePropName="checked">
            <Switch />
          </Form.Item>

          <Form.Item noStyle shouldUpdate={(prev, cur) => prev.autoFinalize !== cur.autoFinalize}>
            {({ getFieldValue }) =>
              getFieldValue('autoFinalize') && (
                <>
                  <Form.Item
                    name="autoFinalizeThreshold"
                    label="Vote threshold (optional)"
                    tooltip="Finalize when this many people vote YES on any option"
                  >
                    <InputNumber min={1} max={100} placeholder="e.g., 5" style={{ width: '100%' }} />
                  </Form.Item>
                  <Form.Item name="tieBreaker" label="Tie-breaker strategy">
                    <Select
                      options={[
                        { value: 'earliest', label: 'Pick earliest date' },
                        { value: 'organizer_choice', label: 'Let me choose manually' },
                      ]}
                    />
                  </Form.Item>

                  <Divider orientation="left" plain style={{ fontSize: 12 }}>
                    Auto-Convert On Finalize
                  </Divider>

                  <Row gutter={16}>
                    <Col span={8}>
                      <Form.Item name="autoConvertToCalendar" label="Calendar" valuePropName="checked">
                        <Switch size="small" />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item name="autoConvertToGancio" label="Public Event" valuePropName="checked">
                        <Switch size="small" />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item name="autoConvertToShift" label="Shift" valuePropName="checked">
                        <Switch size="small" />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item noStyle shouldUpdate={(prev, cur) => prev.autoConvertToShift !== cur.autoConvertToShift}>
                    {({ getFieldValue: gfv }) =>
                      gfv('autoConvertToShift') && (
                        <Form.Item
                          name="autoEnrollVoters"
                          label="Auto-enroll YES voters into shift"
                          valuePropName="checked"
                          tooltip="When enabled, voters who said YES are automatically signed up. When disabled, they receive a confirmation email instead."
                        >
                          <Switch size="small" />
                        </Form.Item>
                      )
                    }
                  </Form.Item>
                </>
              )
            }
          </Form.Item>
        </Form>
      </Drawer>

      {/* Poll Detail Drawer */}
      <Drawer
        title={selectedPoll?.title || 'Poll Details'}
        open={detailOpen}
        onClose={() => { setDetailOpen(false); setSelectedPoll(null); }}
        width={isMobile ? '100%' : 720}
        loading={detailLoading}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          selectedPoll && (
            <Space>
              <Button
                size="small"
                icon={<CopyOutlined />}
                onClick={() => copyShareLink(selectedPoll.slug)}
              >
                Share
              </Button>
            </Space>
          )
        }
      >
        {selectedPoll && (
          <>
            {/* Status + Meta */}
            <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
              <Col>
                <Tag color={POLL_STATUS_COLORS[selectedPoll.status]}>
                  {POLL_STATUS_LABELS[selectedPoll.status]}
                </Tag>
              </Col>
              <Col>
                <Text type="secondary">
                  {selectedPoll._count?.votes ?? 0} votes across {selectedPoll._count?.options ?? 0} options
                </Text>
              </Col>
            </Row>

            {selectedPoll.description && (
              <Text style={{ display: 'block', marginBottom: 16 }}>{selectedPoll.description}</Text>
            )}
            {selectedPoll.location && (
              <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
                Location: {selectedPoll.location}
              </Text>
            )}
            {selectedPoll.autoFinalize && (
              <Card size="small" style={{ marginBottom: 16, background: '#f6ffed', borderColor: '#b7eb8f' }}>
                <Space wrap>
                  <Tag color="green">Auto-Finalize</Tag>
                  {selectedPoll.autoFinalizeThreshold && (
                    <Text type="secondary">Threshold: {selectedPoll.autoFinalizeThreshold} YES votes</Text>
                  )}
                  {selectedPoll.votingDeadline && (
                    <Text type="secondary">Deadline: {dayjs(selectedPoll.votingDeadline).format('YYYY-MM-DD HH:mm')}</Text>
                  )}
                  <Text type="secondary">Tie: {selectedPoll.tieBreaker === 'earliest' ? 'earliest date' : 'manual'}</Text>
                  {selectedPoll.autoConvertToCalendar && <Tag>Calendar</Tag>}
                  {selectedPoll.autoConvertToGancio && <Tag>Gancio</Tag>}
                  {selectedPoll.autoConvertToShift && <Tag>Shift</Tag>}
                  {selectedPoll.autoConvertToShift && selectedPoll.autoEnrollVoters && <Tag color="cyan">Auto-Enroll</Tag>}
                </Space>
              </Card>
            )}
            {selectedPoll.convertedCalendarItemId && (
              <Tag color="purple" icon={<CheckCircleOutlined />} style={{ marginBottom: 8 }}>
                Converted to Calendar Item
              </Tag>
            )}

            {/* Voting Matrix */}
            <Card size="small" title="Voting Matrix" style={{ marginBottom: 16 }}>
              <VotingMatrix poll={selectedPoll} />
            </Card>

            {/* Actions */}
            <Card size="small" title="Actions" style={{ marginBottom: 16 }}>
              <Space wrap>
                {selectedPoll.status === 'OPEN' && (
                  <Button
                    type="primary"
                    icon={<CheckCircleOutlined />}
                    onClick={() => {
                      setSelectedOptionId('');
                      setFinalizeOpen(true);
                    }}
                  >
                    Finalize
                  </Button>
                )}
                {selectedPoll.status === 'FINALIZED' && !selectedPoll.convertedShiftId && (
                  <Button
                    icon={<TeamOutlined />}
                    onClick={() => {
                      convertForm.resetFields();
                      setConvertOpen(true);
                    }}
                  >
                    Convert to Shift
                  </Button>
                )}
                {selectedPoll.status === 'FINALIZED' && !selectedPoll.convertedGancioEventId && (
                  <Popconfirm title="Convert to Gancio event?" onConfirm={handleConvertToEvent}>
                    <Button icon={<CalendarOutlined />}>Convert to Event</Button>
                  </Popconfirm>
                )}
                {selectedPoll.convertedShiftId && (
                  <Tag color="blue" icon={<CheckCircleOutlined />}>Converted to Shift</Tag>
                )}
                {selectedPoll.convertedGancioEventId && (
                  <Tag color="green" icon={<CheckCircleOutlined />}>Converted to Event</Tag>
                )}
                {selectedPoll.status === 'OPEN' && (
                  <Popconfirm
                    title="Close this poll?"
                    onConfirm={async () => {
                      await api.put(`/meeting-planner/${selectedPoll.id}`, { status: 'CLOSED' });
                      message.success('Poll closed');
                      fetchPollDetail(selectedPoll.id);
                      fetchPolls();
                    }}
                  >
                    <Button icon={<ClockCircleOutlined />}>Close</Button>
                  </Popconfirm>
                )}
              </Space>
            </Card>

            {/* Prep Checklist — participant needs summary for finalized polls */}
            {selectedPoll.status === 'FINALIZED' && (
              <Card
                size="small"
                title="Prep Checklist"
                loading={needsLoading}
                style={{ marginBottom: 16 }}
              >
                {!needsSummary || needsSummary.total === 0 ? (
                  <Text type="secondary" style={{ fontSize: 13 }}>
                    No participant needs reported yet.
                  </Text>
                ) : (
                  <div style={{ fontSize: 13 }}>
                    <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                      {needsSummary.total} participant(s) reported needs
                    </Text>
                    {(needsSummary.accessibility.wheelchair > 0 || needsSummary.accessibility.groundFloor > 0 ||
                      needsSummary.accessibility.hearingLoop > 0 || needsSummary.accessibility.signLanguage > 0 ||
                      needsSummary.accessibility.other > 0) && (
                      <div style={{ marginBottom: 8 }}>
                        <Text strong>Accessibility:</Text>
                        <div style={{ paddingLeft: 12 }}>
                          {needsSummary.accessibility.wheelchair > 0 && <div>Wheelchair access: {needsSummary.accessibility.wheelchair}</div>}
                          {needsSummary.accessibility.groundFloor > 0 && <div>Ground floor: {needsSummary.accessibility.groundFloor}</div>}
                          {needsSummary.accessibility.hearingLoop > 0 && <div>Hearing loop: {needsSummary.accessibility.hearingLoop}</div>}
                          {needsSummary.accessibility.signLanguage > 0 && <div>Sign language: {needsSummary.accessibility.signLanguage}</div>}
                          {needsSummary.accessibility.other > 0 && <div>Other: {needsSummary.accessibility.other}</div>}
                        </div>
                      </div>
                    )}
                    {(needsSummary.dietary.vegan > 0 || needsSummary.dietary.vegetarian > 0 ||
                      needsSummary.dietary.glutenFree > 0 || needsSummary.dietary.halal > 0 ||
                      needsSummary.dietary.kosher > 0 || needsSummary.dietary.nutAllergy > 0 ||
                      needsSummary.dietary.other > 0) && (
                      <div style={{ marginBottom: 8 }}>
                        <Text strong>Dietary:</Text>
                        <div style={{ paddingLeft: 12 }}>
                          {needsSummary.dietary.vegan > 0 && <div>Vegan: {needsSummary.dietary.vegan}</div>}
                          {needsSummary.dietary.vegetarian > 0 && <div>Vegetarian: {needsSummary.dietary.vegetarian}</div>}
                          {needsSummary.dietary.glutenFree > 0 && <div>Gluten-free: {needsSummary.dietary.glutenFree}</div>}
                          {needsSummary.dietary.halal > 0 && <div>Halal: {needsSummary.dietary.halal}</div>}
                          {needsSummary.dietary.kosher > 0 && <div>Kosher: {needsSummary.dietary.kosher}</div>}
                          {needsSummary.dietary.nutAllergy > 0 && <div>Nut allergy: {needsSummary.dietary.nutAllergy}</div>}
                          {needsSummary.dietary.other > 0 && <div>Other: {needsSummary.dietary.other}</div>}
                        </div>
                      </div>
                    )}
                    {needsSummary.childcare > 0 && <div><Text strong>Childcare:</Text> {needsSummary.childcare}</div>}
                    {needsSummary.transportation > 0 && <div><Text strong>Transportation:</Text> {needsSummary.transportation}</div>}
                    {needsSummary.translation > 0 && (
                      <div>
                        <Text strong>Translation:</Text> {needsSummary.translation}
                        {Object.keys(needsSummary.languages).length > 0 && (
                          <span> ({Object.entries(needsSummary.languages).map(([lang, count]) => `${lang}: ${count}`).join(', ')})</span>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </Card>
            )}

            {/* Comments */}
            {selectedPoll.comments && selectedPoll.comments.length > 0 && (
              <Card size="small" title={`Comments (${selectedPoll.comments.length})`}>
                {selectedPoll.comments.map((comment) => (
                  <div key={comment.id} style={{ marginBottom: 12, padding: '8px 0', borderBottom: '1px solid #303030' }}>
                    <Row justify="space-between">
                      <Col>
                        <Text strong>{comment.authorName}</Text>
                        <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
                          {dayjs(comment.createdAt).format('MMM D, h:mm A')}
                        </Text>
                      </Col>
                      <Col>
                        <Popconfirm title="Delete comment?" onConfirm={() => handleDeleteComment(comment.id)}>
                          <Button size="small" danger type="text" icon={<DeleteOutlined />} />
                        </Popconfirm>
                      </Col>
                    </Row>
                    <Text style={{ display: 'block', marginTop: 4 }}>{comment.content}</Text>
                  </div>
                ))}
              </Card>
            )}
          </>
        )}
      </Drawer>

      {/* Edit Poll Drawer */}
      <Drawer
        title="Edit Poll"
        open={editOpen}
        onClose={() => { setEditOpen(false); setEditPoll(null); editForm.resetFields(); setNewOptionDate(null); setNewOptionStart(null); setNewOptionEnd(null); }}
        width={isMobile ? '100%' : 560}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Space>
            <Button onClick={() => { setEditOpen(false); setEditPoll(null); editForm.resetFields(); setNewOptionDate(null); setNewOptionStart(null); setNewOptionEnd(null); }}>
              Cancel
            </Button>
            <Button type="primary" loading={editing} onClick={() => editForm.submit()}>
              Save
            </Button>
          </Space>
        }
      >
        <Form form={editForm} layout="vertical" onFinish={handleUpdate}>
          <Form.Item name="title" label="Title" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} />
          </Form.Item>
          <Form.Item name="location" label="Location">
            <Input />
          </Form.Item>
          <Form.Item name="timezone" label="Timezone">
            <Select options={TIMEZONE_OPTIONS.map((tz) => ({ value: tz, label: tz }))} />
          </Form.Item>

          <Divider>Settings</Divider>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="allowAnonymous" label="Allow Anonymous" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="isPrivate" label="Private Poll" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="notifyOnVote" label="Notify on Vote" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="votingDeadline" label="Voting Deadline (optional)">
            <DatePicker showTime format="YYYY-MM-DD HH:mm" style={{ width: '100%' }} />
          </Form.Item>
        </Form>

        {/* Options management for OPEN polls */}
        {editPoll?.status === 'OPEN' && (
          <>
            <Divider>Date/Time Options</Divider>
            {editPoll.options?.map((opt) => (
              <Row key={opt.id} gutter={8} align="middle" style={{ marginBottom: 8 }}>
                <Col flex="auto">
                  <Space wrap>
                    <DatePicker
                      format="YYYY-MM-DD"
                      value={dayjs(opt.date)}
                      onChange={(d) => {
                        if (d) handleUpdateOption(opt.id, 'date', d.format('YYYY-MM-DD'));
                      }}
                    />
                    <TimePicker
                      format="HH:mm"
                      minuteStep={15}
                      value={dayjs(opt.startTime, 'HH:mm')}
                      onChange={(t) => {
                        if (t) handleUpdateOption(opt.id, 'startTime', t.format('HH:mm'));
                      }}
                    />
                    <TimePicker
                      format="HH:mm"
                      minuteStep={15}
                      value={dayjs(opt.endTime, 'HH:mm')}
                      onChange={(t) => {
                        if (t) handleUpdateOption(opt.id, 'endTime', t.format('HH:mm'));
                      }}
                    />
                  </Space>
                </Col>
                <Col>
                  {(editPoll.options?.length ?? 0) > 1 && (
                    <Popconfirm title="Remove this option?" onConfirm={() => handleRemoveOption(opt.id)}>
                      <Button size="small" danger icon={<DeleteOutlined />} />
                    </Popconfirm>
                  )}
                </Col>
              </Row>
            ))}
            <Row gutter={8} align="middle" style={{ marginTop: 12 }}>
              <Col flex="auto">
                <Space wrap>
                  <DatePicker
                    format="YYYY-MM-DD"
                    placeholder="Date"
                    value={newOptionDate}
                    onChange={setNewOptionDate}
                  />
                  <TimePicker
                    format="HH:mm"
                    minuteStep={15}
                    placeholder="Start"
                    value={newOptionStart}
                    onChange={setNewOptionStart}
                  />
                  <TimePicker
                    format="HH:mm"
                    minuteStep={15}
                    placeholder="End"
                    value={newOptionEnd}
                    onChange={setNewOptionEnd}
                  />
                </Space>
              </Col>
              <Col>
                <Button
                  icon={<PlusOutlined />}
                  onClick={() => {
                    if (!newOptionDate || !newOptionStart || !newOptionEnd) {
                      message.warning('Fill in date, start, and end time');
                      return;
                    }
                    handleAddOption({
                      date: newOptionDate.format('YYYY-MM-DD'),
                      startTime: newOptionStart.format('HH:mm'),
                      endTime: newOptionEnd.format('HH:mm'),
                    }).then(() => {
                      setNewOptionDate(null);
                      setNewOptionStart(null);
                      setNewOptionEnd(null);
                    });
                  }}
                >
                  Add
                </Button>
              </Col>
            </Row>
          </>
        )}
      </Drawer>

      {/* Finalize Modal */}
      <Modal
        title="Finalize Poll"
        open={finalizeOpen}
        onCancel={() => setFinalizeOpen(false)}
        onOk={handleFinalize}
        confirmLoading={finalizing}
        okText="Finalize"
        okButtonProps={{ disabled: !selectedOptionId }}
      >
        <Text style={{ display: 'block', marginBottom: 16 }}>
          Select the winning date/time option:
        </Text>
        <Select
          placeholder="Select option"
          style={{ width: '100%' }}
          value={selectedOptionId || undefined}
          onChange={setSelectedOptionId}
          options={selectedPoll?.options?.map((opt) => ({
            value: opt.id,
            label: `${dayjs(opt.date).format('MMM D, YYYY')} ${opt.startTime}–${opt.endTime} (score: ${opt.score ?? 0})`,
          }))}
        />
      </Modal>

      {/* Convert to Shift Modal */}
      <Modal
        title="Convert to Volunteer Shift"
        open={convertOpen}
        onCancel={() => setConvertOpen(false)}
        onOk={() => convertForm.submit()}
        confirmLoading={converting}
        okText="Create Shift"
      >
        <Form form={convertForm} layout="vertical" onFinish={handleConvertToShift} initialValues={{ maxVolunteers: 10, isPublic: true }}>
          <Form.Item name="maxVolunteers" label="Max Volunteers" rules={[{ required: true }]}>
            <Input type="number" min={1} />
          </Form.Item>
          <Form.Item name="isPublic" label="Public" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
