import {
  Drawer,
  Tabs,
  Descriptions,
  Tag,
  Button,
  Input,
  Select,
  Switch,
  Space,
  Typography,
  message,
  Spin,
  Avatar,
  Grid,
  List,
  Popconfirm,
  Tooltip,
  Divider,
  Alert,
} from 'antd';
import { useState, useEffect, useCallback } from 'react';
import {
  StarFilled,
  StarOutlined,
  UserOutlined,
  EnvironmentOutlined,
  MailOutlined,
  ScheduleOutlined,
  DollarOutlined,
  PhoneOutlined,
  LinkOutlined,
  DeleteOutlined,
  MergeCellsOutlined,
  EyeOutlined,
  UserAddOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type {
  PersonDetail,
  UpdateContactPayload,
  ContactConnection,
  ContactSource,
  SupportLevel,
  CrmTag,
} from '@/types/api';
import {
  CONTACT_SOURCE_LABELS,
  CONTACT_SOURCE_COLORS,
  SUPPORT_LEVEL_LABELS,
  SUPPORT_LEVEL_COLORS,
  CONNECTION_TYPE_LABELS,
  CONNECTION_TYPE_COLORS,
} from '@/types/api';
import PersonActivityTimeline from './PersonActivityTimeline';
import EngagementSummaryPanel from './EngagementSummaryPanel';
import HouseholdPanel from './HouseholdPanel';
import ConnectionForm from './ConnectionForm';
import MergeContactModal from './MergeContactModal';
import ProfileLinkActions from './ProfileLinkActions';
import ProfilePreviewModal from './ProfilePreviewModal';
import CreateUserFromContactModal from './CreateUserFromContactModal';
import UserAccountStatusPanel from './UserAccountStatusPanel';
import ContactAddressPanel from './ContactAddressPanel';
import ContactEmailPanel from './ContactEmailPanel';
import ContactPhonePanel from './ContactPhonePanel';
import VideoCallModal from './VideoCallModal';
import { useSettingsStore } from '@/stores/settings.store';
import { useAuthStore } from '@/stores/auth.store';

const supportLevelOptions: { value: SupportLevel; label: string }[] = Object.entries(SUPPORT_LEVEL_LABELS).map(
  ([value, label]) => ({ value: value as SupportLevel, label }),
);

const SOURCE_AVATAR_COLORS: Record<ContactSource, string> = {
  USER: '#1890ff',
  ADDRESS_OCCUPANT: '#52c41a',
  CAMPAIGN_SENDER: '#722ed1',
  SHIFT_SIGNUP: '#13c2c2',
  SMS_CONTACT: '#fa8c16',
  DONATION: '#fadb14',
  MANUAL: '#8c8c8c',
};

function getInitials(name: string): string {
  if (!name) return '?';
  const parts = name.trim().split(/\s+/);
  const first = parts[0];
  const last = parts[parts.length - 1];
  if (parts.length >= 2 && first && last) {
    return ((first[0] || '') + (last[0] || '')).toUpperCase();
  }
  return (name[0] || '?').toUpperCase();
}

interface PersonDetailDrawerProps {
  open: boolean;
  personId: string | null;
  onClose: () => void;
  onRefresh: () => void;
}

export default function PersonDetailDrawer({ open, personId, onClose, onRefresh }: PersonDetailDrawerProps) {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [detail, setDetail] = useState<PersonDetail | null>(null);
  const [connections, setConnections] = useState<ContactConnection[]>([]);
  const [registeredTags, setRegisteredTags] = useState<CrmTag[]>([]);
  const [showConnectionForm, setShowConnectionForm] = useState(false);
  const [showMergeModal, setShowMergeModal] = useState(false);
  const [showProfilePreview, setShowProfilePreview] = useState(false);
  const [showCreateUserModal, setShowCreateUserModal] = useState(false);
  const [showVideoCallModal, setShowVideoCallModal] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');
  const { settings: siteSettings } = useSettingsStore();
  const { user: authUser } = useAuthStore();
  const canStartCall = siteSettings?.enableMeet && authUser?.role !== 'TEMP';

  // Editable fields (for managed contacts)
  const [editDisplayName, setEditDisplayName] = useState('');
  const [editFirstName, setEditFirstName] = useState('');
  const [editLastName, setEditLastName] = useState('');
  const [editTags, setEditTags] = useState<string[]>([]);
  const [editNotes, setEditNotes] = useState('');
  const [editSupportLevel, setEditSupportLevel] = useState<SupportLevel | null>(null);
  const [editEmailOptOut, setEditEmailOptOut] = useState(false);
  const [editSmsOptOut, setEditSmsOptOut] = useState(false);
  const [editDoNotContact, setEditDoNotContact] = useState(false);
  const [editSignRequested, setEditSignRequested] = useState(false);

  const isNew = personId === 'new';

  const parsePersonId = (id: string): { type: string; sourceId: string } => {
    const colonIdx = id.indexOf(':');
    if (colonIdx === -1) return { type: 'contact', sourceId: id };
    return { type: id.substring(0, colonIdx), sourceId: id.substring(colonIdx + 1) };
  };

  const fetchDetail = useCallback(async () => {
    if (!personId || isNew) return;
    setLoading(true);
    try {
      const { type, sourceId } = parsePersonId(personId);
      const { data } = await api.get<PersonDetail>(`/people/${type}/${sourceId}`);
      setDetail(data);

      // Populate editable fields
      const c = data.contact;
      if (c) {
        setEditDisplayName(c.displayName || '');
        setEditFirstName(c.firstName || '');
        setEditLastName(c.lastName || '');
        setEditTags(c.tags || []);
        setEditNotes(c.notes || '');
        setEditSupportLevel(c.supportLevel);
        setEditEmailOptOut(c.emailOptOut);
        setEditSmsOptOut(c.smsOptOut);
        setEditDoNotContact(c.doNotContact);
        setEditSignRequested(c.signRequested);
      } else {
        setEditDisplayName(data.person.displayName || '');
        setEditTags(data.person.tags || []);
        setEditSupportLevel(data.person.supportLevel);
        setEditFirstName('');
        setEditLastName('');
        setEditNotes('');
        setEditEmailOptOut(false);
        setEditSmsOptOut(false);
        setEditDoNotContact(false);
        setEditSignRequested(false);
      }
    } catch {
      message.error('Failed to load person details');
    } finally {
      setLoading(false);
    }
  }, [personId, isNew]);

  const fetchConnections = useCallback(async () => {
    if (!personId || isNew || !detail?.contact?.id) return;
    try {
      const { data } = await api.get<{ connections: ContactConnection[] }>(
        `/people/contacts/${detail.contact.id}/connections`,
      );
      setConnections(data.connections);
    } catch {
      setConnections([]);
    }
  }, [personId, isNew, detail?.contact?.id]);

  useEffect(() => {
    if (open) {
      // Fetch registered tags for autocomplete
      api.get<{ tags: CrmTag[] }>('/people/tags')
        .then(({ data }) => setRegisteredTags(data.tags))
        .catch(() => { /* non-critical */ });
    }
    if (open && personId && !isNew) {
      setActiveTab('overview');
      fetchDetail();
    }
  }, [open, personId]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (activeTab === 'connections' && detail?.contact?.id) {
      fetchConnections();
    }
  }, [activeTab, detail?.contact?.id]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleManage = async () => {
    if (!personId || !detail) return;
    try {
      const { type, sourceId } = parsePersonId(personId);
      await api.post('/people/manage', {
        sourceType: type,
        sourceId,
        displayName: detail.person.displayName,
        email: detail.person.email,
        phone: detail.person.phone,
      });
      message.success('Contact is now managed');
      fetchDetail();
      onRefresh();
    } catch {
      message.error('Failed to manage contact');
    }
  };

  const handleSave = async () => {
    if (!detail?.contact?.id) return;
    setSaving(true);
    try {
      const payload: UpdateContactPayload = {
        displayName: editDisplayName,
        firstName: editFirstName || undefined,
        lastName: editLastName || undefined,
        tags: editTags,
        notes: editNotes || undefined,
        supportLevel: editSupportLevel,
        signRequested: editSignRequested,
        emailOptOut: editEmailOptOut,
        smsOptOut: editSmsOptOut,
        doNotContact: editDoNotContact,
      };
      await api.put(`/people/contacts/${detail.contact.id}`, payload);
      message.success('Contact updated');
      fetchDetail();
      onRefresh();
    } catch {
      message.error('Failed to update contact');
    } finally {
      setSaving(false);
    }
  };

  const handleRemoveConnection = async (connectionId: string) => {
    if (!detail?.contact?.id) return;
    try {
      await api.delete(`/people/contacts/${detail.contact.id}/connections/${connectionId}`);
      message.success('Connection removed');
      fetchConnections();
    } catch {
      message.error('Failed to remove connection');
    }
  };

  const person = detail?.person;
  const contact = detail?.contact;
  const isManaged = person?.isManaged ?? false;

  // Navigate tab items
  const navigateLinks = [];
  if (person?.userId) {
    navigateLinks.push({ label: 'View User Profile', icon: <UserOutlined />, path: '/app/users' });
  }
  if (person?.addressId) {
    navigateLinks.push({ label: 'View on Map', icon: <EnvironmentOutlined />, path: '/map' });
  }
  if (person?.email) {
    navigateLinks.push({ label: 'View Campaign Emails', icon: <MailOutlined />, path: '/app/campaigns' });
    navigateLinks.push({ label: 'View Shift Signups', icon: <ScheduleOutlined />, path: '/app/map/shifts' });
    navigateLinks.push({ label: 'View Donations', icon: <DollarOutlined />, path: '/app/payments/donations' });
  }
  if (person?.phone) {
    navigateLinks.push({ label: 'View SMS Conversations', icon: <PhoneOutlined />, path: '/app/sms/conversations' });
  }

  const tabItems = [
    {
      key: 'overview',
      label: 'Overview',
      children: loading ? (
        <div style={{ textAlign: 'center', padding: 32 }}>
          <Spin />
        </div>
      ) : !person ? (
        <Typography.Text type="secondary">No data available</Typography.Text>
      ) : (
        <div>
          {/* Header */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 16,
              marginBottom: 20,
            }}
          >
            <Avatar
              size={56}
              style={{ backgroundColor: SOURCE_AVATAR_COLORS[person.source], fontWeight: 600, fontSize: 20 }}
            >
              {getInitials(person.displayName)}
            </Avatar>
            <div style={{ flex: 1 }}>
              <Typography.Title level={4} style={{ margin: 0 }}>
                {person.displayName}
              </Typography.Title>
              <Space size={6} style={{ marginTop: 4 }}>
                <Tag color={CONTACT_SOURCE_COLORS[person.source]}>
                  {CONTACT_SOURCE_LABELS[person.source]}
                </Tag>
                {!isManaged && (
                  <Button size="small" icon={<StarOutlined />} onClick={handleManage}>
                    Manage
                  </Button>
                )}
                {isManaged && <StarFilled style={{ color: '#faad14' }} />}
              </Space>
            </div>
            <Space>
              {canStartCall && person && (
                <Button
                  icon={<VideoCameraOutlined />}
                  size="small"
                  type="primary"
                  ghost
                  onClick={() => setShowVideoCallModal(true)}
                >
                  Video Call
                </Button>
              )}
              {isManaged && contact && (
                <>
                  <Button
                    icon={<EyeOutlined />}
                    size="small"
                    onClick={() => setShowProfilePreview(true)}
                  >
                    Preview
                  </Button>
                  <Button
                    icon={<MergeCellsOutlined />}
                    size="small"
                    onClick={() => setShowMergeModal(true)}
                  >
                    Merge
                  </Button>
                </>
              )}
            </Space>
          </div>

          {/* Engagement Summary */}
          {detail?.engagement && (
            <div style={{ marginBottom: 20 }}>
              <EngagementSummaryPanel engagement={detail.engagement} />
            </div>
          )}

          {/* Profile Link Actions (managed contacts only) */}
          {isManaged && contact && (
            <div style={{ marginBottom: 16 }}>
              <ProfileLinkActions contact={contact} onRefresh={() => { fetchDetail(); onRefresh(); }} />
            </div>
          )}

          <Divider style={{ margin: '16px 0' }} />

          {/* Editable fields for managed contacts */}
          {isManaged && contact ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                  Display Name
                </Typography.Text>
                <Input value={editDisplayName} onChange={(e) => setEditDisplayName(e.target.value)} />
              </div>
              <div style={{ display: 'flex', gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                    First Name
                  </Typography.Text>
                  <Input value={editFirstName} onChange={(e) => setEditFirstName(e.target.value)} />
                </div>
                <div style={{ flex: 1 }}>
                  <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                    Last Name
                  </Typography.Text>
                  <Input value={editLastName} onChange={(e) => setEditLastName(e.target.value)} />
                </div>
              </div>
              <Divider style={{ margin: '8px 0' }}>Emails</Divider>
              <ContactEmailPanel contactId={contact.id} />

              <Divider style={{ margin: '8px 0' }}>Phones</Divider>
              <ContactPhonePanel contactId={contact.id} />

              <div>
                <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                  Tags
                </Typography.Text>
                <Select
                  mode="tags"
                  value={editTags}
                  onChange={setEditTags}
                  style={{ width: '100%' }}
                  placeholder="Add tags..."
                  tokenSeparators={[',']}
                  options={registeredTags.map((t) => ({
                    value: t.name,
                    label: (
                      <Space size={6}>
                        {t.color && <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: t.color }} />}
                        <span>{t.name}</span>
                        {t.contactCount > 0 && <span style={{ fontSize: 11, opacity: 0.5 }}>({t.contactCount})</span>}
                      </Space>
                    ),
                  }))}
                />
              </div>
              <div>
                <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                  Notes
                </Typography.Text>
                <Input.TextArea
                  value={editNotes}
                  onChange={(e) => setEditNotes(e.target.value)}
                  rows={3}
                  placeholder="Notes about this contact..."
                />
              </div>
              <div>
                <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                  Support Level
                </Typography.Text>
                <Select
                  options={supportLevelOptions}
                  value={editSupportLevel}
                  onChange={setEditSupportLevel}
                  allowClear
                  style={{ width: '100%' }}
                  placeholder="Not set"
                />
              </div>

              <Divider style={{ margin: '8px 0' }}>Addresses</Divider>
              <ContactAddressPanel contactId={contact.id} />

              <Divider style={{ margin: '8px 0' }}>Consent & Preferences</Divider>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Text style={{ fontSize: 13 }}>Email Opt-Out</Typography.Text>
                <Switch checked={editEmailOptOut} onChange={setEditEmailOptOut} size="small" />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Text style={{ fontSize: 13 }}>SMS Opt-Out</Typography.Text>
                <Switch checked={editSmsOptOut} onChange={setEditSmsOptOut} size="small" />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Text style={{ fontSize: 13 }}>Do Not Contact</Typography.Text>
                <Switch checked={editDoNotContact} onChange={setEditDoNotContact} size="small" />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Text style={{ fontSize: 13 }}>Sign Requested</Typography.Text>
                <Switch checked={editSignRequested} onChange={setEditSignRequested} size="small" />
              </div>

              {/* User Account Section */}
              <Divider style={{ margin: '8px 0' }}>User Account</Divider>

              {person?.userStatus && person.userStatus !== 'ACTIVE' && (
                <Alert
                  type="warning"
                  message={`User account is ${person.userStatus.replace(/_/g, ' ')}`}
                  style={{ marginBottom: 8 }}
                  showIcon
                />
              )}

              {contact?.userId ? (
                <UserAccountStatusPanel userId={contact.userId} />
              ) : (
                <div style={{ textAlign: 'center', padding: '8px 0' }}>
                  <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 13 }}>
                    This contact does not have a user account.
                  </Typography.Text>
                  <Button
                    icon={<UserAddOutlined />}
                    disabled={!contact?.email}
                    onClick={() => setShowCreateUserModal(true)}
                  >
                    Create User Account
                  </Button>
                  {!contact?.email && (
                    <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)', marginTop: 4 }}>
                      An email address is required to create a user account
                    </div>
                  )}
                </div>
              )}

              <Button type="primary" onClick={handleSave} loading={saving} style={{ marginTop: 12 }}>
                Save Changes
              </Button>
            </div>
          ) : (
            /* Read-only display for unmanaged */
            <Descriptions column={1} size="small" labelStyle={{ width: 120 }}>
              <Descriptions.Item label="Email">{person?.email || '--'}</Descriptions.Item>
              <Descriptions.Item label="Phone">{person?.phone || '--'}</Descriptions.Item>
              <Descriptions.Item label="Support Level">
                {person?.supportLevel ? (
                  <Tag color={SUPPORT_LEVEL_COLORS[person.supportLevel]}>
                    {SUPPORT_LEVEL_LABELS[person.supportLevel]}
                  </Tag>
                ) : (
                  '--'
                )}
              </Descriptions.Item>
              <Descriptions.Item label="Tags">
                {person?.tags && person.tags.length > 0 ? (
                  <Space size={2} wrap>
                    {person.tags.map((t) => (
                      <Tag key={t}>{t}</Tag>
                    ))}
                  </Space>
                ) : (
                  '--'
                )}
              </Descriptions.Item>
              <Descriptions.Item label="Engagement Score">
                {person?.engagementScore != null ? `${person.engagementScore}%` : '--'}
              </Descriptions.Item>
            </Descriptions>
          )}
        </div>
      ),
    },
    {
      key: 'activity',
      label: 'Activity',
      children: personId && !isNew ? <PersonActivityTimeline personId={personId} /> : null,
    },
    {
      key: 'connections',
      label: 'Connections',
      children: (
        <div>
          {!isManaged ? (
            <Typography.Text type="secondary">
              Manage this contact to add connections.
            </Typography.Text>
          ) : (
            <>
              <div style={{ marginBottom: 16 }}>
                <Button
                  icon={<LinkOutlined />}
                  onClick={() => setShowConnectionForm(true)}
                  disabled={showConnectionForm}
                >
                  Add Connection
                </Button>
              </div>

              {showConnectionForm && contact && (
                <div
                  style={{
                    marginBottom: 16,
                    padding: 12,
                    background: 'rgba(255,255,255,0.04)',
                    borderRadius: 8,
                    border: '1px solid rgba(255,255,255,0.08)',
                  }}
                >
                  <ConnectionForm
                    contactId={contact.id}
                    onCreated={() => {
                      setShowConnectionForm(false);
                      fetchConnections();
                    }}
                    onCancel={() => setShowConnectionForm(false)}
                  />
                </div>
              )}

              {connections.length === 0 ? (
                <Typography.Text type="secondary">No connections yet.</Typography.Text>
              ) : (
                <List
                  dataSource={connections}
                  renderItem={(conn) => {
                    const isFrom = conn.fromContactId === contact?.id;
                    const otherContact = isFrom ? conn.toContact : conn.fromContact;
                    return (
                      <List.Item
                        actions={[
                          <Popconfirm
                            key="remove"
                            title="Remove this connection?"
                            onConfirm={() => handleRemoveConnection(conn.id)}
                          >
                            <Button type="text" size="small" danger icon={<DeleteOutlined />} />
                          </Popconfirm>,
                        ]}
                      >
                        <List.Item.Meta
                          avatar={
                            <Avatar size={32} style={{ backgroundColor: '#722ed1' }}>
                              {otherContact ? getInitials(otherContact.displayName) : '?'}
                            </Avatar>
                          }
                          title={
                            <Space size={6}>
                              <span>{otherContact?.displayName || 'Unknown'}</span>
                              <Tag color={CONNECTION_TYPE_COLORS[conn.type]} style={{ margin: 0, fontSize: 11 }}>
                                {conn.label || CONNECTION_TYPE_LABELS[conn.type]}
                              </Tag>
                              {conn.isBidirectional && (
                                <Tooltip title="Bidirectional">
                                  <LinkOutlined style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)' }} />
                                </Tooltip>
                              )}
                            </Space>
                          }
                          description={conn.notes || undefined}
                        />
                      </List.Item>
                    );
                  }}
                />
              )}
            </>
          )}
        </div>
      ),
    },
    {
      key: 'household',
      label: 'Household',
      children: personId && !isNew ? <HouseholdPanel personId={personId} /> : null,
    },
    {
      key: 'navigate',
      label: 'Navigate',
      children: (
        <div>
          {navigateLinks.length === 0 ? (
            <Typography.Text type="secondary">No related modules found.</Typography.Text>
          ) : (
            <List
              dataSource={navigateLinks}
              renderItem={(item) => (
                <List.Item>
                  <Button
                    type="link"
                    icon={item.icon}
                    onClick={() => {
                      window.location.href = item.path;
                    }}
                    style={{ padding: 0 }}
                  >
                    {item.label}
                  </Button>
                </List.Item>
              )}
            />
          )}
        </div>
      ),
    },
  ];

  return (
    <>
      <Drawer
        title={
          isNew
            ? 'Add Contact'
            : person
              ? person.displayName
              : 'Person Details'
        }
        open={open}
        placement="right"
        width={isMobile ? '100%' : 640}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        onClose={onClose}
      >
        {isNew ? (
          <NewContactForm
            registeredTags={registeredTags}
            onCreated={() => {
              onClose();
              onRefresh();
            }}
          />
        ) : (
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={tabItems}
            size="small"
          />
        )}
      </Drawer>

      {/* Merge Modal */}
      {contact && (
        <MergeContactModal
          open={showMergeModal}
          targetContact={contact}
          onClose={() => setShowMergeModal(false)}
          onMerged={() => {
            setShowMergeModal(false);
            fetchDetail();
            onRefresh();
          }}
        />
      )}

      {/* Profile Preview Modal */}
      {contact && (
        <ProfilePreviewModal
          open={showProfilePreview}
          contactId={contact.id}
          profileToken={contact.profileToken}
          onClose={() => setShowProfilePreview(false)}
        />
      )}

      {/* Create User from Contact Modal */}
      {contact && contact.email && (
        <CreateUserFromContactModal
          open={showCreateUserModal}
          contactId={contact.id}
          contactEmail={contact.email}
          contactName={contact.displayName}
          onClose={() => setShowCreateUserModal(false)}
          onCreated={() => {
            setShowCreateUserModal(false);
            fetchDetail();
            onRefresh();
          }}
        />
      )}

      {/* Video Call Modal */}
      <VideoCallModal
        open={showVideoCallModal}
        onClose={() => setShowVideoCallModal(false)}
        personName={person?.displayName || 'Contact'}
      />
    </>
  );
}

/** Inline new contact form */
function NewContactForm({ onCreated, registeredTags }: { onCreated: () => void; registeredTags: CrmTag[] }) {
  const [displayName, setDisplayName] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [tags, setTags] = useState<string[]>([]);
  const [notes, setNotes] = useState('');
  const [supportLevel, setSupportLevel] = useState<SupportLevel | undefined>();
  const [saving, setSaving] = useState(false);

  const handleCreate = async () => {
    if (!displayName.trim()) {
      message.warning('Display name is required');
      return;
    }
    setSaving(true);
    try {
      await api.post('/people/contacts', {
        displayName: displayName.trim(),
        firstName: firstName || undefined,
        lastName: lastName || undefined,
        email: email || undefined,
        phone: phone || undefined,
        tags,
        notes: notes || undefined,
        supportLevel,
      });
      message.success('Contact created');
      onCreated();
    } catch {
      message.error('Failed to create contact');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Display Name *
        </Typography.Text>
        <Input
          value={displayName}
          onChange={(e) => setDisplayName(e.target.value)}
          placeholder="Jane Doe"
        />
      </div>
      <div style={{ display: 'flex', gap: 12 }}>
        <div style={{ flex: 1 }}>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            First Name
          </Typography.Text>
          <Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
        </div>
        <div style={{ flex: 1 }}>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            Last Name
          </Typography.Text>
          <Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
        </div>
      </div>
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Email
        </Typography.Text>
        <Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="jane@example.com" />
      </div>
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Phone
        </Typography.Text>
        <Input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+1 555 000 0000" />
      </div>
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Tags
        </Typography.Text>
        <Select
          mode="tags"
          value={tags}
          onChange={setTags}
          style={{ width: '100%' }}
          placeholder="Add tags..."
          tokenSeparators={[',']}
          options={registeredTags.map((t) => ({
            value: t.name,
            label: (
              <Space size={6}>
                {t.color && <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: t.color }} />}
                <span>{t.name}</span>
              </Space>
            ),
          }))}
        />
      </div>
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Notes
        </Typography.Text>
        <Input.TextArea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={3}
        />
      </div>
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Support Level
        </Typography.Text>
        <Select
          options={Object.entries(SUPPORT_LEVEL_LABELS).map(([v, l]) => ({
            value: v as SupportLevel,
            label: l,
          }))}
          value={supportLevel}
          onChange={setSupportLevel}
          allowClear
          style={{ width: '100%' }}
          placeholder="Not set"
        />
      </div>
      <Button type="primary" onClick={handleCreate} loading={saving} style={{ marginTop: 8 }}>
        Create Contact
      </Button>
    </div>
  );
}
