import { useState, useEffect, useCallback } from 'react';
import { Table, Button, Drawer, Form, Input, Space, Upload, App, Typography, Popconfirm, Tabs, Select, Collapse, Tag } from 'antd';
import { PlusOutlined, UploadOutlined, PhoneOutlined, DeleteOutlined, ImportOutlined, DatabaseOutlined, UserOutlined, EnvironmentOutlined, CalendarOutlined, MessageOutlined, ContactsOutlined, UnorderedListOutlined, UserAddOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { api } from '@/lib/api';
import type { SmsContactList, SmsContactListEntry, SmsPaginatedResponse } from '@/types/sms';
import type { AppOutletContext } from '@/types/api';
import { useOutletContext } from 'react-router-dom';
import { useDebounce } from '@/hooks/useDebounce';

const { Text } = Typography;
const { TextArea } = Input;

interface PreviewResult {
  total: number;
  sample: { phone: string; name?: string }[];
}

export default function SmsContactsPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { message } = App.useApp();

  // --- Contacts (entries) state ---
  const [entries, setEntries] = useState<SmsContactListEntry[]>([]);
  const [entriesTotal, setEntriesTotal] = useState(0);
  const [entriesPage, setEntriesPage] = useState(1);
  const [entriesLoading, setEntriesLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const debouncedSearch = useDebounce(searchText, 300);
  const [filterListId, setFilterListId] = useState<string | undefined>();

  // --- Lists state ---
  const [lists, setLists] = useState<SmsContactList[]>([]);
  const [listsTotal, setListsTotal] = useState(0);
  const [listsPage, setListsPage] = useState(1);
  const [listsLoading, setListsLoading] = useState(true);

  // --- Drawers ---
  const [createOpen, setCreateOpen] = useState(false);
  const [addContactOpen, setAddContactOpen] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [importListId, setImportListId] = useState<string | null>(null);
  const [csvText, setCsvText] = useState('');
  const [createForm] = Form.useForm();
  const [addContactForm] = Form.useForm();
  const [createSaving, setCreateSaving] = useState(false);
  const [addContactSaving, setAddContactSaving] = useState(false);

  // --- Selection + bulk actions ---
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [addToListModalOpen, setAddToListModalOpen] = useState(false);
  const [addToListTargetId, setAddToListTargetId] = useState<string | undefined>();
  const [addToListLoading, setAddToListLoading] = useState(false);

  // Import state
  const [preview, setPreview] = useState<PreviewResult | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);

  // Filter state for each tab
  const [userRole, setUserRole] = useState<string | undefined>();
  const [addrProvince, setAddrProvince] = useState<string | undefined>();
  const [addrSupportLevel, setAddrSupportLevel] = useState<string | undefined>();
  const [signupShiftId, setSignupShiftId] = useState<string | undefined>();
  const [convCampaignId, setConvCampaignId] = useState<string | undefined>();
  const [convResponseType, setConvResponseType] = useState<string | undefined>();
  const [contactTag, setContactTag] = useState<string | undefined>();
  const [contactSupportLevel, setContactSupportLevel] = useState<string | undefined>();

  // Dropdown options loaded from API
  const [shifts, setShifts] = useState<{ id: string; title: string }[]>([]);
  const [smsCampaigns, setSmsCampaigns] = useState<{ id: string; name: string }[]>([]);

  useEffect(() => {
    setPageHeader({ title: 'SMS Contacts', subtitle: 'Manage contacts across all lists' });
  }, [setPageHeader]);

  // --- Fetch all entries (contacts-first view) ---
  const fetchEntries = useCallback(async (p = 1) => {
    setEntriesLoading(true);
    try {
      const params: Record<string, string | number> = { page: p, limit: 50 };
      if (filterListId) params.listId = filterListId;
      if (debouncedSearch) params.search = debouncedSearch;
      const { data } = await api.get<SmsPaginatedResponse<SmsContactListEntry>>('/sms/contacts/all-entries', { params });
      setEntries(data.items);
      setEntriesTotal(data.total);
      setEntriesPage(p);
    } finally {
      setEntriesLoading(false);
    }
  }, [filterListId, debouncedSearch]);

  // --- Fetch lists (for dropdown + lists panel) ---
  const fetchLists = useCallback(async (p = 1) => {
    setListsLoading(true);
    try {
      const { data } = await api.get<SmsPaginatedResponse<SmsContactList>>('/sms/contacts', { params: { page: p, limit: 50 } });
      setLists(data.items);
      setListsTotal(data.total);
      setListsPage(p);
    } finally {
      setListsLoading(false);
    }
  }, []);

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

  // Re-fetch entries when filters or page change
  useEffect(() => {
    setEntriesPage(1);
    fetchEntries(1);
  }, [fetchEntries]);

  // Load shifts and SMS campaigns for filter dropdowns when import drawer opens
  const loadFilterOptions = useCallback(async () => {
    try {
      const [shiftsRes, campaignsRes] = await Promise.all([
        api.get('/map/shifts', { params: { limit: 100 } }),
        api.get('/sms/campaigns', { params: { limit: 100 } }),
      ]);
      setShifts((shiftsRes.data.items || []).map((s: { id: string; title: string }) => ({ id: s.id, title: s.title })));
      setSmsCampaigns((campaignsRes.data.items || []).map((c: { id: string; name: string }) => ({ id: c.id, name: c.name })));
    } catch {
      // Silently fail — dropdowns will be empty
    }
  }, []);

  const closeCreateDrawer = () => { setCreateOpen(false); };
  const closeAddContactDrawer = () => { setAddContactOpen(false); };
  const closeImportDrawer = () => { setImportOpen(false); resetImportState(); };

  const handleCreate = async (values: { name: string }) => {
    setCreateSaving(true);
    try {
      const { data } = await api.post('/sms/contacts', values);
      message.success('Contact list created');
      closeCreateDrawer();
      createForm.resetFields();
      fetchLists();
      // Auto-select the new list in the filter
      setFilterListId(data.id);
    } catch {
      message.error('Failed to create list');
    } finally {
      setCreateSaving(false);
    }
  };

  const handleAddContact = async (values: { listId: string; phone: string; name?: string; email?: string }) => {
    setAddContactSaving(true);
    try {
      const { listId, ...body } = values;
      await api.post(`/sms/contacts/${listId}/entries`, body);
      message.success('Contact added');
      closeAddContactDrawer();
      addContactForm.resetFields();
      fetchEntries(entriesPage);
      fetchLists();
    } catch {
      message.error('Failed to add contact');
    } finally {
      setAddContactSaving(false);
    }
  };

  const openAddContactDrawer = () => {
    // Pre-fill the list if one is selected in the filter
    if (filterListId) {
      addContactForm.setFieldsValue({ listId: filterListId });
    } else if (lists.length === 1) {
      addContactForm.setFieldsValue({ listId: lists[0]!.id });
    }
    setAddContactOpen(true);
  };

  const handleAddToList = async () => {
    if (!addToListTargetId || selectedRowKeys.length === 0) return;
    setAddToListLoading(true);
    try {
      const selected = entries.filter(e => selectedRowKeys.includes(e.id));
      const payload = selected.map(e => ({ phone: e.phone, name: e.name || undefined, email: e.email || undefined }));
      const { data } = await api.post(`/sms/contacts/${addToListTargetId}/entries/bulk`, { entries: payload });
      message.success(`Added ${data.imported} contact${data.imported !== 1 ? 's' : ''} to list${data.skipped ? ` (${data.skipped} skipped)` : ''}`);
      setAddToListModalOpen(false);
      setAddToListTargetId(undefined);
      setSelectedRowKeys([]);
      fetchEntries(entriesPage);
      fetchLists();
    } catch {
      message.error('Failed to add contacts to list');
    } finally {
      setAddToListLoading(false);
    }
  };

  const handleArchive = async (id: string) => {
    try {
      await api.delete(`/sms/contacts/${id}`);
      message.success('List archived');
      // If we're filtering by this list, clear the filter
      if (filterListId === id) setFilterListId(undefined);
      fetchLists();
      fetchEntries(1);
    } catch {
      message.error('Failed to archive list');
    }
  };

  const handleImportCsv = async () => {
    if (!importListId || !csvText.trim()) return;
    setImportLoading(true);
    try {
      const { data } = await api.post(`/sms/contacts/${importListId}/import-csv`, { csv: csvText });
      message.success(`Imported ${data.imported} contacts (${data.skipped} skipped)`);
      closeImportDrawer();
      fetchLists();
      fetchEntries(entriesPage);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Import failed';
      message.error(msg);
    } finally {
      setImportLoading(false);
    }
  };

  const handleImportFromPhone = async () => {
    if (!importListId) return;
    setImportLoading(true);
    try {
      const { data } = await api.post(`/sms/contacts/${importListId}/import-phone`);
      message.success(`Imported ${data.imported} contacts from phone`);
      closeImportDrawer();
      fetchLists();
      fetchEntries(entriesPage);
    } catch {
      message.error('Failed to import from phone');
    } finally {
      setImportLoading(false);
    }
  };

  const handleDeleteEntry = async (entry: SmsContactListEntry) => {
    try {
      await api.delete(`/sms/contacts/${entry.listId}/entries/${entry.id}`);
      message.success('Contact removed');
      fetchEntries(entriesPage);
      fetchLists();
    } catch {
      message.error('Failed to remove contact');
    }
  };

  const openImportDrawer = (listId?: string) => {
    if (listId) {
      setImportListId(listId);
    } else if (filterListId) {
      setImportListId(filterListId);
    } else if (lists.length === 1) {
      setImportListId(lists[0]!.id);
    } else {
      message.info('Select a list first, or use the filter dropdown to choose one');
      return;
    }
    setImportOpen(true);
    loadFilterOptions();
  };

  const resetImportState = () => {
    setCsvText('');
    setPreview(null);
    setUserRole(undefined);
    setAddrProvince(undefined);
    setAddrSupportLevel(undefined);
    setSignupShiftId(undefined);
    setConvCampaignId(undefined);
    setConvResponseType(undefined);
    setContactTag(undefined);
    setContactSupportLevel(undefined);
  };

  // Preview handlers for each source
  const handlePreview = async (source: string) => {
    setPreviewLoading(true);
    setPreview(null);
    try {
      let params: Record<string, string> = {};
      switch (source) {
        case 'users':
          if (userRole) params.role = userRole;
          break;
        case 'addresses':
          if (addrProvince) params.province = addrProvince;
          if (addrSupportLevel) params.supportLevel = addrSupportLevel;
          break;
        case 'signups':
          if (signupShiftId) params.shiftId = signupShiftId;
          break;
        case 'conversations':
          if (convCampaignId) params.campaignId = convCampaignId;
          if (convResponseType) params.responseType = convResponseType;
          break;
        case 'contacts':
          if (contactTag) params.tag = contactTag;
          if (contactSupportLevel) params.supportLevel = contactSupportLevel;
          break;
      }
      const { data } = await api.get<PreviewResult>(`/sms/contacts/preview-${source}`, { params });
      setPreview(data);
    } catch {
      message.error('Failed to load preview');
    } finally {
      setPreviewLoading(false);
    }
  };

  // Import handlers for each source
  const handleDatabaseImport = async (source: string) => {
    if (!importListId) return;
    setImportLoading(true);
    try {
      let body: Record<string, string | undefined> = {};
      switch (source) {
        case 'users':
          body = { role: userRole };
          break;
        case 'addresses':
          body = { province: addrProvince, supportLevel: addrSupportLevel };
          break;
        case 'signups':
          body = { shiftId: signupShiftId };
          break;
        case 'conversations':
          body = { campaignId: convCampaignId, responseType: convResponseType };
          break;
        case 'contacts':
          body = { tag: contactTag, supportLevel: contactSupportLevel };
          break;
      }
      const { data } = await api.post(`/sms/contacts/${importListId}/import-${source}`, body);
      message.success(`Imported ${data.imported} contacts (${data.skipped} skipped)`);
      closeImportDrawer();
      fetchLists();
      fetchEntries(entriesPage);
    } catch {
      message.error('Import failed');
    } finally {
      setImportLoading(false);
    }
  };

  // Render a preview table + import button for a database source tab
  const renderPreviewSection = (source: string) => (
    <div style={{ marginTop: 12 }}>
      <Space>
        <Button onClick={() => handlePreview(source)} loading={previewLoading}>Preview</Button>
      </Space>
      {preview && (
        <div style={{ marginTop: 12 }}>
          <Text strong>{preview.total} contact{preview.total !== 1 ? 's' : ''} found</Text>
          {preview.sample.length > 0 && (
            <Table
              rowKey="phone"
              size="small"
              pagination={false}
              style={{ marginTop: 8 }}
              dataSource={preview.sample}
              columns={[
                { title: 'Phone', dataIndex: 'phone', width: 140 },
                { title: 'Name', dataIndex: 'name', render: (v: string) => v || <Text type="secondary">-</Text> },
              ]}
            />
          )}
          <Button
            type="primary"
            style={{ marginTop: 12 }}
            onClick={() => handleDatabaseImport(source)}
            loading={importLoading}
            disabled={preview.total === 0}
          >
            Import {preview.total} contact{preview.total !== 1 ? 's' : ''}
          </Button>
        </div>
      )}
    </div>
  );

  // --- Main contacts table columns ---
  const contactColumns: ColumnsType<SmsContactListEntry> = [
    { title: 'Phone', dataIndex: 'phone', width: 140 },
    { title: 'Name', dataIndex: 'name', render: (v) => v || <Text type="secondary">-</Text> },
    { title: 'Email', dataIndex: 'email', render: (v) => v || <Text type="secondary">-</Text>, responsive: ['md'] },
    {
      title: 'List',
      dataIndex: ['list', 'name'],
      width: 180,
      render: (name: string, record) => {
        if (!record.list) return <Text type="secondary">-</Text>;
        return (
          <Tag
            color="blue"
            style={{ cursor: 'pointer' }}
            onClick={() => setFilterListId(record.list!.id)}
          >
            {name}
          </Tag>
        );
      },
    },
    {
      title: 'Added',
      dataIndex: 'createdAt',
      width: 110,
      render: (d) => new Date(d).toLocaleDateString(),
      responsive: ['lg'],
    },
    {
      title: '',
      width: 40,
      render: (_, record) => (
        <Popconfirm title="Remove this contact?" onConfirm={() => handleDeleteEntry(record)}>
          <Button size="small" type="text" danger icon={<DeleteOutlined />} />
        </Popconfirm>
      ),
    },
  ];

  // --- Lists panel columns ---
  const listColumns: ColumnsType<SmsContactList> = [
    {
      title: 'Name',
      dataIndex: 'name',
      render: (name, record) => (
        <a onClick={() => setFilterListId(record.id)}>{name}</a>
      ),
    },
    { title: 'Contacts', dataIndex: 'totalContacts', width: 90 },
    {
      title: 'Source',
      dataIndex: 'originalFilename',
      render: (f) => f || <Text type="secondary">Manual</Text>,
      responsive: ['md'],
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      render: (d) => new Date(d).toLocaleDateString(),
      width: 110,
      responsive: ['lg'],
    },
    {
      title: 'Actions',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<DatabaseOutlined />} onClick={() => openImportDrawer(record.id)}>Import</Button>
          <Popconfirm title="Archive this list?" onConfirm={() => handleArchive(record.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const supportLevelOptions = [
    { value: 'LEVEL_1', label: 'Level 1 (Strong Support)' },
    { value: 'LEVEL_2', label: 'Level 2 (Leaning Support)' },
    { value: 'LEVEL_3', label: 'Level 3 (Undecided)' },
    { value: 'LEVEL_4', label: 'Level 4 (Opposition)' },
  ];

  const responseTypeOptions = [
    { value: 'POSITIVE', label: 'Positive' },
    { value: 'NEGATIVE', label: 'Negative' },
    { value: 'QUESTION', label: 'Question' },
    { value: 'NEUTRAL', label: 'Neutral' },
  ];

  const roleOptions = [
    { value: 'USER', label: 'User' },
    { value: 'TEMP', label: 'Temp' },
    { value: 'SUPER_ADMIN', label: 'Super Admin' },
    { value: 'INFLUENCE_ADMIN', label: 'Influence Admin' },
    { value: 'MAP_ADMIN', label: 'Map Admin' },
  ];

  const importListName = importListId ? lists.find(l => l.id === importListId)?.name : undefined;

  // Either drawer being open shifts content
  const anyDrawerOpen = createOpen || addContactOpen || importOpen;
  const drawerWidth = 480;
  const importDrawerWidth = 560;
  const activeDrawerWidth = importOpen ? importDrawerWidth : drawerWidth;

  return (
    <>
      <div style={{ marginRight: anyDrawerOpen ? activeDrawerWidth : 0, transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)' }}>
        {/* Top toolbar */}
        <Space wrap style={{ marginBottom: 16, width: '100%' }}>
          <Input.Search
            placeholder="Search phone, name, or email..."
            allowClear
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 260 }}
          />
          <Select
            placeholder="All Lists"
            allowClear
            showSearch
            optionFilterProp="label"
            style={{ width: 200 }}
            value={filterListId}
            onChange={(v) => setFilterListId(v)}
            options={lists.map(l => ({ value: l.id, label: `${l.name} (${l.totalContacts})` }))}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>New List</Button>
          <Button icon={<UserAddOutlined />} onClick={openAddContactDrawer}>Add Contact</Button>
          <Button icon={<ImportOutlined />} onClick={() => openImportDrawer()}>Import</Button>
        </Space>

        {/* Lists management panel */}
        <Collapse
          style={{ marginBottom: 16 }}
          items={[{
            key: 'lists',
            label: <span><UnorderedListOutlined /> Manage Lists ({listsTotal})</span>,
            children: (
              <Table
                rowKey="id"
                columns={listColumns}
                dataSource={lists}
                loading={listsLoading}
                pagination={{
                  current: listsPage,
                  total: listsTotal,
                  pageSize: 50,
                  onChange: (p) => fetchLists(p),
                  showSizeChanger: false,
                }}
                size="small"
                scroll={{ x: 'max-content' }}
              />
            ),
          }]}
        />

        {/* Selection action bar */}
        {selectedRowKeys.length > 0 && (
          <div style={{
            marginBottom: 12,
            padding: '8px 16px',
            background: 'rgba(22, 119, 255, 0.08)',
            borderRadius: 8,
            display: 'flex',
            alignItems: 'center',
            gap: 12,
          }}>
            <Text strong>{selectedRowKeys.length} selected</Text>
            <Button
              size="small"
              icon={<PlusOutlined />}
              onClick={() => setAddToListModalOpen(true)}
            >
              Add to List
            </Button>
            <Button size="small" type="link" onClick={() => setSelectedRowKeys([])}>
              Clear
            </Button>
          </div>
        )}

        {/* Main contacts table */}
        <Table
          rowKey="id"
          columns={contactColumns}
          dataSource={entries}
          loading={entriesLoading}
          scroll={{ x: 'max-content' }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            preserveSelectedRowKeys: true,
          }}
          pagination={{
            current: entriesPage,
            total: entriesTotal,
            pageSize: 50,
            onChange: (p) => fetchEntries(p),
            showTotal: (t) => `${t} contacts`,
            showSizeChanger: false,
          }}
          size="middle"
        />
      </div>

      {/* Create List Drawer */}
      <Drawer
        title="New Contact List"
        open={createOpen}
        onClose={closeCreateDrawer}
        destroyOnHidden
        mask={false}
        width={drawerWidth}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Space>
            <Button onClick={closeCreateDrawer}>Cancel</Button>
            <Button type="primary" loading={createSaving} onClick={() => createForm.submit()}>
              Create
            </Button>
          </Space>
        }
      >
        <Form form={createForm} layout="vertical" onFinish={handleCreate}>
          <Form.Item name="name" label="List Name" rules={[{ required: true }]}>
            <Input placeholder="e.g. Ward 6 Supporters" />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Add Single Contact Drawer */}
      <Drawer
        title="Add Contact"
        open={addContactOpen}
        onClose={closeAddContactDrawer}
        destroyOnHidden
        mask={false}
        width={drawerWidth}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Space>
            <Button onClick={closeAddContactDrawer}>Cancel</Button>
            <Button type="primary" loading={addContactSaving} onClick={() => addContactForm.submit()}>
              Add
            </Button>
          </Space>
        }
      >
        <Form form={addContactForm} layout="vertical" onFinish={handleAddContact}>
          <Form.Item name="listId" label="List" rules={[{ required: true, message: 'Select a contact list' }]}>
            <Select
              placeholder="Select a list"
              showSearch
              optionFilterProp="label"
              options={lists.map(l => ({ value: l.id, label: l.name }))}
            />
          </Form.Item>
          <Form.Item name="phone" label="Phone Number" rules={[{ required: true, message: 'Phone number is required' }]}>
            <Input placeholder="e.g. 5551234567" />
          </Form.Item>
          <Form.Item name="name" label="Name">
            <Input placeholder="e.g. Jane Doe" />
          </Form.Item>
          <Form.Item name="email" label="Email">
            <Input placeholder="e.g. jane@example.com" type="email" />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Add to List Drawer */}
      <Drawer
        title={`Add ${selectedRowKeys.length} contact${selectedRowKeys.length !== 1 ? 's' : ''} to list`}
        open={addToListModalOpen}
        onClose={() => { setAddToListModalOpen(false); setAddToListTargetId(undefined); }}
        placement="right"
        width={420}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button type="primary" loading={addToListLoading} disabled={!addToListTargetId} onClick={handleAddToList}>
            Add to List
          </Button>
        }
      >
        <Select
          placeholder="Select target list"
          showSearch
          optionFilterProp="label"
          style={{ width: '100%', marginTop: 8 }}
          value={addToListTargetId}
          onChange={setAddToListTargetId}
          options={lists.map(l => ({ value: l.id, label: `${l.name} (${l.totalContacts})` }))}
        />
      </Drawer>

      {/* Import Contacts Drawer */}
      <Drawer
        title={`Import Contacts${importListName ? ` → ${importListName}` : ''}`}
        open={importOpen}
        onClose={closeImportDrawer}
        destroyOnHidden
        mask={false}
        width={importDrawerWidth}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button onClick={closeImportDrawer}>Close</Button>
        }
      >
        <Tabs
          onChange={() => setPreview(null)}
          items={[
            {
              key: 'csv',
              label: <span><UploadOutlined /> CSV</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Paste CSV text or upload a file. First row = headers. Expected: phone (required), name, email.
                  </Text>
                  <Upload
                    accept=".csv,.tsv,.txt"
                    maxCount={1}
                    beforeUpload={(file) => {
                      const reader = new FileReader();
                      reader.onload = (e) => setCsvText(e.target?.result as string || '');
                      reader.readAsText(file);
                      return false;
                    }}
                    showUploadList={false}
                  >
                    <Button icon={<ImportOutlined />}>Load from file</Button>
                  </Upload>
                  <TextArea
                    rows={8}
                    value={csvText}
                    onChange={(e) => setCsvText(e.target.value)}
                    placeholder="phone,name,email&#10;5551234567,John Doe,john@example.com"
                    style={{ marginTop: 12, fontFamily: 'monospace' }}
                  />
                  <Button
                    type="primary"
                    style={{ marginTop: 12 }}
                    onClick={handleImportCsv}
                    loading={importLoading}
                    disabled={!csvText.trim()}
                  >
                    Import CSV
                  </Button>
                </>
              ),
            },
            {
              key: 'phone',
              label: <span><PhoneOutlined /> Phone Book</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Import contacts from the connected Android phone address book via Termux API.
                  </Text>
                  <Button
                    type="primary"
                    icon={<PhoneOutlined />}
                    onClick={handleImportFromPhone}
                    loading={importLoading}
                  >
                    Import from Phone
                  </Button>
                </>
              ),
            },
            {
              key: 'users',
              label: <span><UserOutlined /> Users</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Import platform users who have phone numbers on file.
                  </Text>
                  <Select
                    placeholder="Filter by role (optional)"
                    allowClear
                    style={{ width: '100%' }}
                    value={userRole}
                    onChange={setUserRole}
                    options={roleOptions}
                  />
                  {renderPreviewSection('users')}
                </>
              ),
            },
            {
              key: 'addresses',
              label: <span><EnvironmentOutlined /> Addresses</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Import from map addresses that have phone numbers.
                  </Text>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Input
                      placeholder="Province code (e.g. AB, ON)"
                      allowClear
                      value={addrProvince}
                      onChange={(e) => setAddrProvince(e.target.value || undefined)}
                    />
                    <Select
                      placeholder="Support level (optional)"
                      allowClear
                      style={{ width: '100%' }}
                      value={addrSupportLevel}
                      onChange={setAddrSupportLevel}
                      options={supportLevelOptions}
                    />
                  </Space>
                  {renderPreviewSection('addresses')}
                </>
              ),
            },
            {
              key: 'signups',
              label: <span><CalendarOutlined /> Shift Signups</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Import from volunteer shift signups with phone numbers.
                  </Text>
                  <Select
                    placeholder="Filter by shift (optional)"
                    allowClear
                    showSearch
                    optionFilterProp="label"
                    style={{ width: '100%' }}
                    value={signupShiftId}
                    onChange={setSignupShiftId}
                    options={shifts.map((s) => ({ value: s.id, label: s.title }))}
                  />
                  {renderPreviewSection('signups')}
                </>
              ),
            },
            {
              key: 'conversations',
              label: <span><MessageOutlined /> Conversations</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Import from SMS conversations (excludes opted-out contacts).
                  </Text>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Select
                      placeholder="Filter by SMS campaign (optional)"
                      allowClear
                      showSearch
                      optionFilterProp="label"
                      style={{ width: '100%' }}
                      value={convCampaignId}
                      onChange={setConvCampaignId}
                      options={smsCampaigns.map((c) => ({ value: c.id, label: c.name }))}
                    />
                    <Select
                      placeholder="Filter by response type (optional)"
                      allowClear
                      style={{ width: '100%' }}
                      value={convResponseType}
                      onChange={setConvResponseType}
                      options={responseTypeOptions}
                    />
                  </Space>
                  {renderPreviewSection('conversations')}
                </>
              ),
            },
            {
              key: 'contacts',
              label: <span><ContactsOutlined /> CRM Contacts</span>,
              children: (
                <>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Import from CRM contacts with phone numbers (respects opt-out / do-not-contact flags).
                  </Text>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Input
                      placeholder="Tag name (optional)"
                      allowClear
                      value={contactTag}
                      onChange={(e) => setContactTag(e.target.value || undefined)}
                    />
                    <Select
                      placeholder="Support level (optional)"
                      allowClear
                      style={{ width: '100%' }}
                      value={contactSupportLevel}
                      onChange={setContactSupportLevel}
                      options={supportLevelOptions}
                    />
                  </Space>
                  {renderPreviewSection('contacts')}
                </>
              ),
            },
          ]}
        />
      </Drawer>
    </>
  );
}
