'use client';

import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ── Types ───────────────────────────────────────────────────────────────────

type ChannelType = 'push' | 'sms' | 'voice_call' | 'email' | 'telegram' | 'wechat_work' | 'voice_service';

interface Channel {
  id: string;
  name: string;
  type: ChannelType;
  enabled: boolean;
  configured: boolean;
  config: Record<string, string>;
}

interface Contact {
  id: string;
  name: string;
  email: string;
  phone: string;
  role: string;
  channels: ChannelType[];
}

interface EscalationStep {
  stepNumber: number;
  channels: ChannelType[];
  delayMinutes: number;
  contactIds: string[];
}

interface EscalationPolicy {
  id: string;
  name: string;
  severity: string;
  isDefault: boolean;
  steps: EscalationStep[];
}

// ── Channel config field definitions ────────────────────────────────────────

const CHANNEL_CONFIG_FIELDS: Record<ChannelType, { key: string; labelKey: string; type?: string }[]> = {
  email: [
    { key: 'smtpHost', labelKey: 'channels.fields.smtpHost' },
    { key: 'smtpPort', labelKey: 'channels.fields.smtpPort' },
    { key: 'smtpUser', labelKey: 'channels.fields.username' },
    { key: 'smtpPass', labelKey: 'channels.fields.password', type: 'password' },
    { key: 'fromAddress', labelKey: 'channels.fields.fromAddress' },
  ],
  telegram: [
    { key: 'botToken', labelKey: 'channels.fields.botToken', type: 'password' },
    { key: 'chatId', labelKey: 'channels.fields.chatId' },
  ],
  sms: [
    { key: 'provider', labelKey: 'channels.fields.provider' },
    { key: 'apiKey', labelKey: 'channels.fields.apiKey', type: 'password' },
    { key: 'fromNumber', labelKey: 'channels.fields.fromNumber' },
  ],
  push: [
    { key: 'provider', labelKey: 'channels.fields.provider' },
    { key: 'apiKey', labelKey: 'channels.fields.apiKey', type: 'password' },
    { key: 'appId', labelKey: 'channels.fields.appId' },
  ],
  voice_call: [
    { key: 'provider', labelKey: 'channels.fields.provider' },
    { key: 'apiKey', labelKey: 'channels.fields.apiKey', type: 'password' },
    { key: 'fromNumber', labelKey: 'channels.fields.fromNumber' },
  ],
  wechat_work: [
    { key: 'corpId', labelKey: 'channels.fields.corpId' },
    { key: 'agentId', labelKey: 'channels.fields.agentId' },
    { key: 'secret', labelKey: 'channels.fields.secret', type: 'password' },
  ],
  voice_service: [
    { key: 'provider', labelKey: 'channels.fields.provider' },
    { key: 'apiKey', labelKey: 'channels.fields.apiKey', type: 'password' },
    { key: 'endpoint', labelKey: 'channels.fields.endpoint' },
  ],
};

const ALL_CHANNEL_TYPES: ChannelType[] = ['push', 'sms', 'voice_call', 'email', 'telegram', 'wechat_work', 'voice_service'];

const CHANNEL_LABEL_KEYS: Record<ChannelType, string> = {
  push: 'channels.types.push',
  sms: 'channels.types.sms',
  voice_call: 'channels.types.voice',
  email: 'channels.types.email',
  telegram: 'channels.types.telegram',
  wechat_work: 'channels.types.wechatWork',
  voice_service: 'channels.types.voiceService',
};

const SEVERITY_OPTIONS = ['critical', 'high', 'medium', 'low', 'info'];

const TABS = ['channels', 'contacts', 'escalationPolicies'] as const;
type Tab = (typeof TABS)[number];

const TAB_LABEL_KEYS: Record<Tab, string> = {
  channels: 'tabs.channels',
  contacts: 'tabs.contacts',
  escalationPolicies: 'tabs.escalationPolicies',
};

// ── Main Component ──────────────────────────────────────────────────────────

export default function CommunicationPage() {
  const { t } = useTranslation('communication');
  const [activeTab, setActiveTab] = useState<Tab>('channels');

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">{t('title')}</h1>
      {/* Tab bar */}
      <div className="flex border-b mb-6">
        {TABS.map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={cn(
              'px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors',
              activeTab === tab
                ? 'border-primary text-primary'
                : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/30'
            )}
          >
            {t(TAB_LABEL_KEYS[tab])}
          </button>
        ))}
      </div>
      {/* Tab content */}
      {activeTab === 'channels' && <ChannelsTab />}
      {activeTab === 'contacts' && <ContactsTab />}
      {activeTab === 'escalationPolicies' && <EscalationPoliciesTab />}
    </div>
  );
}

// ── Tab 1: Channels ─────────────────────────────────────────────────────────

function ChannelsTab() {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const { data, isLoading, error } = useQuery({
    queryKey: queryKeys.channels.list(),
    queryFn: () => apiClient<Channel[]>('/api/v1/comm/channels'),
  });

  const toggleMutation = useMutation({
    mutationFn: (channel: Channel) =>
      apiClient<Channel>(`/api/v1/comm/channels/${channel.id}`, {
        method: 'PATCH',
        body: { enabled: !channel.enabled },
      }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.channels.all }),
  });

  const updateConfigMutation = useMutation({
    mutationFn: ({ id, config }: { id: string; config: Record<string, string> }) =>
      apiClient<Channel>(`/api/v1/comm/channels/${id}`, {
        method: 'PATCH',
        body: { config },
      }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.channels.all }),
  });

  const channels = Array.isArray(data) ? data : [];

  if (isLoading) return <p className="text-muted-foreground">{tc('loading')}</p>;
  if (error) return <p className="text-red-500">{tc('error')}: {(error as Error).message}</p>;

  return (
    <div className="space-y-3">
      {channels.length === 0 && <p className="text-muted-foreground">{tc('noData')}</p>}
      {channels.map((ch) => (
        <div key={ch.id} className="border rounded-lg bg-card">
          <div className="flex items-center justify-between p-4">
            <div className="flex items-center gap-4">
              <div>
                <p className="font-medium">{ch.name}</p>
                <p className="text-xs text-muted-foreground">{CHANNEL_LABEL_KEYS[ch.type] ? t(CHANNEL_LABEL_KEYS[ch.type]) : ch.type}</p>
              </div>
              <span
                className={cn(
                  'text-xs px-2 py-0.5 rounded-full',
                  ch.configured ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                )}
              >
                {ch.configured ? t('channels.configured') : t('channels.notConfigured')}
              </span>
            </div>
            <div className="flex items-center gap-3">
              {/* Toggle switch */}
              <button
                onClick={() => toggleMutation.mutate(ch)}
                disabled={toggleMutation.isPending}
                className={cn(
                  'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
                  ch.enabled ? 'bg-primary' : 'bg-muted'
                )}
                title={ch.enabled ? tc('disabled') : tc('enabled')}
              >
                <span
                  className={cn(
                    'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                    ch.enabled ? 'translate-x-6' : 'translate-x-1'
                  )}
                />
              </button>
              <button
                onClick={() => setExpandedId(expandedId === ch.id ? null : ch.id)}
                className="text-sm text-primary hover:underline"
              >
                {expandedId === ch.id ? t('channels.hideConfig') : t('channels.showConfig')}
              </button>
            </div>
          </div>
          {/* Expanded config */}
          {expandedId === ch.id && (
            <ChannelConfigEditor
              channel={ch}
              onSave={(config) => updateConfigMutation.mutate({ id: ch.id, config })}
              isSaving={updateConfigMutation.isPending}
            />
          )}
        </div>
      ))}
    </div>
  );
}

function ChannelConfigEditor({
  channel,
  onSave,
  isSaving,
}: {
  channel: Channel;
  onSave: (config: Record<string, string>) => void;
  isSaving: boolean;
}) {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const fields = CHANNEL_CONFIG_FIELDS[channel.type] ?? [];
  const [localConfig, setLocalConfig] = useState<Record<string, string>>({ ...channel.config });

  return (
    <div className="border-t p-4 space-y-3">
      {fields.map((field) => (
        <div key={field.key}>
          <label className="block text-sm font-medium mb-1">{t(field.labelKey)}</label>
          <input
            type={field.type ?? 'text'}
            value={localConfig[field.key] ?? ''}
            onChange={(e) => setLocalConfig((prev) => ({ ...prev, [field.key]: e.target.value }))}
            className="w-full max-w-md px-3 py-2 bg-input border rounded-md text-sm"
          />
        </div>
      ))}
      <button
        onClick={() => onSave(localConfig)}
        disabled={isSaving}
        className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm hover:opacity-90 disabled:opacity-50"
      >
        {isSaving ? tc('saving') : t('channels.saveConfiguration')}
      </button>
    </div>
  );
}

// ── Tab 2: Contacts ─────────────────────────────────────────────────────────

function ContactsTab() {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();
  const [showDialog, setShowDialog] = useState(false);
  const [editingContact, setEditingContact] = useState<Contact | null>(null);

  const { data, isLoading, error } = useQuery({
    queryKey: queryKeys.contacts.list(),
    queryFn: () => apiClient<Contact[]>('/api/v1/comm/contacts'),
  });

  const createMutation = useMutation({
    mutationFn: (body: Omit<Contact, 'id'>) =>
      apiClient<Contact>('/api/v1/comm/contacts', { method: 'POST', body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.contacts.all });
      setShowDialog(false);
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, ...body }: Contact) =>
      apiClient<Contact>(`/api/v1/comm/contacts/${id}`, { method: 'PUT', body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.contacts.all });
      setEditingContact(null);
      setShowDialog(false);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      apiClient<void>(`/api/v1/comm/contacts/${id}`, { method: 'DELETE' }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.contacts.all }),
  });

  const contacts = Array.isArray(data) ? data : [];

  const handleOpenAdd = () => {
    setEditingContact(null);
    setShowDialog(true);
  };

  const handleOpenEdit = (contact: Contact) => {
    setEditingContact(contact);
    setShowDialog(true);
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <p className="text-sm text-muted-foreground">{t('contacts.count', { count: contacts.length })}</p>
        <button
          onClick={handleOpenAdd}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm"
        >
          {t('contacts.addContact')}
        </button>
      </div>

      {isLoading && <p className="text-muted-foreground">{tc('loading')}</p>}
      {error && <p className="text-red-500">{tc('error')}: {(error as Error).message}</p>}

      {!isLoading && !error && (
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b text-left">
                <th className="py-2 pr-4 font-medium">{t('contacts.table.name')}</th>
                <th className="py-2 pr-4 font-medium">{t('contacts.table.email')}</th>
                <th className="py-2 pr-4 font-medium">{t('contacts.table.phone')}</th>
                <th className="py-2 pr-4 font-medium">{t('contacts.table.role')}</th>
                <th className="py-2 pr-4 font-medium">{t('contacts.table.channels')}</th>
                <th className="py-2 font-medium">{t('contacts.table.actions')}</th>
              </tr>
            </thead>
            <tbody>
              {contacts.map((c) => (
                <tr key={c.id} className="border-b hover:bg-accent/50">
                  <td className="py-2 pr-4">{c.name}</td>
                  <td className="py-2 pr-4 text-muted-foreground">{c.email}</td>
                  <td className="py-2 pr-4 text-muted-foreground">{c.phone}</td>
                  <td className="py-2 pr-4">
                    <span className="text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-700">{c.role}</span>
                  </td>
                  <td className="py-2 pr-4">
                    <div className="flex flex-wrap gap-1">
                      {c.channels.map((ch) => (
                        <span key={ch} className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
                          {ch}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td className="py-2">
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleOpenEdit(c)}
                        className="text-xs text-primary hover:underline"
                      >
                        {tc('edit')}
                      </button>
                      <button
                        onClick={() => {
                          if (confirm(tc('confirmDelete'))) deleteMutation.mutate(c.id);
                        }}
                        className="text-xs text-red-500 hover:underline"
                        disabled={deleteMutation.isPending}
                      >
                        {tc('delete')}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {contacts.length === 0 && (
                <tr>
                  <td colSpan={6} className="py-8 text-center text-muted-foreground">
                    {t('contacts.empty')}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* Add/Edit Dialog */}
      {showDialog && (
        <ContactDialog
          contact={editingContact}
          onClose={() => {
            setShowDialog(false);
            setEditingContact(null);
          }}
          onSave={(c) => {
            if (editingContact) {
              updateMutation.mutate({ ...c, id: editingContact.id });
            } else {
              createMutation.mutate(c);
            }
          }}
          isSaving={createMutation.isPending || updateMutation.isPending}
        />
      )}
    </div>
  );
}

function ContactDialog({
  contact,
  onClose,
  onSave,
  isSaving,
}: {
  contact: Contact | null;
  onClose: () => void;
  onSave: (data: Omit<Contact, 'id'>) => void;
  isSaving: boolean;
}) {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const [name, setName] = useState(contact?.name ?? '');
  const [email, setEmail] = useState(contact?.email ?? '');
  const [phone, setPhone] = useState(contact?.phone ?? '');
  const [role, setRole] = useState(contact?.role ?? '');
  const [channels, setChannels] = useState<ChannelType[]>(contact?.channels ?? []);

  const toggleChannel = (ch: ChannelType) => {
    setChannels((prev) => (prev.includes(ch) ? prev.filter((c) => c !== ch) : [...prev, ch]));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({ name, email, phone, role, channels });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-card border rounded-lg shadow-lg w-full max-w-lg p-6">
        <h2 className="text-lg font-semibold mb-4">{contact ? t('contacts.editContact') : t('contacts.addContact')}</h2>
        <form onSubmit={handleSubmit} className="space-y-3">
          <div>
            <label className="block text-sm font-medium mb-1">{t('contacts.form.name')}</label>
            <input value={name} onChange={(e) => setName(e.target.value)} required className="w-full px-3 py-2 bg-input border rounded-md text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">{t('contacts.form.email')}</label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required className="w-full px-3 py-2 bg-input border rounded-md text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">{t('contacts.form.phone')}</label>
            <input value={phone} onChange={(e) => setPhone(e.target.value)} className="w-full px-3 py-2 bg-input border rounded-md text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">{t('contacts.form.role')}</label>
            <input value={role} onChange={(e) => setRole(e.target.value)} required className="w-full px-3 py-2 bg-input border rounded-md text-sm" placeholder="e.g. admin, on-call, manager" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">{t('contacts.form.channels')}</label>
            <div className="flex flex-wrap gap-2">
              {ALL_CHANNEL_TYPES.map((ch) => (
                <button
                  key={ch}
                  type="button"
                  onClick={() => toggleChannel(ch)}
                  className={cn(
                    'text-xs px-2 py-1 rounded border transition-colors',
                    channels.includes(ch) ? 'bg-primary text-primary-foreground border-primary' : 'bg-card text-muted-foreground border-muted hover:border-foreground'
                  )}
                >
                  {ch}
                </button>
              ))}
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="px-4 py-2 border rounded-md text-sm hover:bg-accent">
              {tc('cancel')}
            </button>
            <button type="submit" disabled={isSaving} className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm hover:opacity-90 disabled:opacity-50">
              {isSaving ? tc('saving') : contact ? tc('save') : tc('create')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Tab 3: Escalation Policies ──────────────────────────────────────────────

function EscalationPoliciesTab() {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();
  const [showDialog, setShowDialog] = useState(false);
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const { data, isLoading, error } = useQuery({
    queryKey: queryKeys.escalationPolicies.list(),
    queryFn: () => apiClient<EscalationPolicy[]>('/api/v1/comm/escalation-policies'),
  });

  const { data: contactsData } = useQuery({
    queryKey: queryKeys.contacts.list(),
    queryFn: () => apiClient<Contact[]>('/api/v1/comm/contacts'),
  });

  const contacts = Array.isArray(contactsData) ? contactsData : [];

  const createMutation = useMutation({
    mutationFn: (body: Omit<EscalationPolicy, 'id'>) =>
      apiClient<EscalationPolicy>('/api/v1/comm/escalation-policies', { method: 'POST', body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.escalationPolicies.all });
      setShowDialog(false);
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, ...body }: EscalationPolicy) =>
      apiClient<EscalationPolicy>(`/api/v1/comm/escalation-policies/${id}`, { method: 'PUT', body }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.escalationPolicies.all }),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      apiClient<void>(`/api/v1/comm/escalation-policies/${id}`, { method: 'DELETE' }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.escalationPolicies.all }),
  });

  const policies = Array.isArray(data) ? data : [];

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <p className="text-sm text-muted-foreground">{t('escalationPolicies.count', { count: policies.length })}</p>
        <button onClick={() => setShowDialog(true)} className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm">
          {t('escalationPolicies.addPolicy')}
        </button>
      </div>

      {isLoading && <p className="text-muted-foreground">{tc('loading')}</p>}
      {error && <p className="text-red-500">{tc('error')}: {(error as Error).message}</p>}

      <div className="space-y-3">
        {policies.map((policy) => (
          <div key={policy.id} className="border rounded-lg bg-card">
            <div className="flex items-center justify-between p-4">
              <div className="flex items-center gap-3">
                <div>
                  <p className="font-medium">{policy.name}</p>
                  <p className="text-xs text-muted-foreground">{tc('severity')}: {policy.severity}</p>
                </div>
                {policy.isDefault && (
                  <span className="text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-700">{t('escalationPolicies.default')}</span>
                )}
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setExpandedId(expandedId === policy.id ? null : policy.id)}
                  className="text-sm text-primary hover:underline"
                >
                  {expandedId === policy.id ? t('escalationPolicies.collapseSteps') : t('escalationPolicies.editSteps')}
                </button>
                <button
                  onClick={() => {
                    if (confirm(tc('confirmDelete'))) deleteMutation.mutate(policy.id);
                  }}
                  className="text-sm text-red-500 hover:underline"
                  disabled={deleteMutation.isPending}
                >
                  {tc('delete')}
                </button>
              </div>
            </div>
            {expandedId === policy.id && (
              <PolicyStepEditor
                policy={policy}
                contacts={contacts}
                onSave={(updated) => updateMutation.mutate(updated)}
                isSaving={updateMutation.isPending}
              />
            )}
          </div>
        ))}
        {!isLoading && policies.length === 0 && (
          <p className="text-center text-muted-foreground py-8">{t('escalationPolicies.empty')}</p>
        )}
      </div>

      {/* Add Policy Dialog */}
      {showDialog && (
        <PolicyDialog
          onClose={() => setShowDialog(false)}
          onSave={(p) => createMutation.mutate(p)}
          isSaving={createMutation.isPending}
        />
      )}
    </div>
  );
}

function PolicyStepEditor({
  policy,
  contacts,
  onSave,
  isSaving,
}: {
  policy: EscalationPolicy;
  contacts: Contact[];
  onSave: (policy: EscalationPolicy) => void;
  isSaving: boolean;
}) {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const [steps, setSteps] = useState<EscalationStep[]>(policy.steps);

  const addStep = () => {
    setSteps((prev) => [
      ...prev,
      { stepNumber: prev.length + 1, channels: [], delayMinutes: 5, contactIds: [] },
    ]);
  };

  const removeStep = (idx: number) => {
    setSteps((prev) => prev.filter((_, i) => i !== idx).map((s, i) => ({ ...s, stepNumber: i + 1 })));
  };

  const updateStep = (idx: number, updates: Partial<EscalationStep>) => {
    setSteps((prev) => prev.map((s, i) => (i === idx ? { ...s, ...updates } : s)));
  };

  const toggleStepChannel = (idx: number, ch: ChannelType) => {
    setSteps((prev) =>
      prev.map((s, i) =>
        i === idx
          ? { ...s, channels: s.channels.includes(ch) ? s.channels.filter((c) => c !== ch) : [...s.channels, ch] }
          : s
      )
    );
  };

  const toggleStepContact = (idx: number, contactId: string) => {
    setSteps((prev) =>
      prev.map((s, i) =>
        i === idx
          ? {
              ...s,
              contactIds: s.contactIds.includes(contactId)
                ? s.contactIds.filter((c) => c !== contactId)
                : [...s.contactIds, contactId],
            }
          : s
      )
    );
  };

  return (
    <div className="border-t p-4 space-y-4">
      <p className="text-sm font-medium">{t('escalationPolicies.form.steps')}</p>
      {steps.map((step, idx) => (
        <div key={idx} className="border rounded-md p-3 space-y-2 bg-background">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">{t('escalationPolicies.step.title', { number: step.stepNumber })}</span>
            <button onClick={() => removeStep(idx)} className="text-xs text-red-500 hover:underline">
              {tc('remove')}
            </button>
          </div>
          <div>
            <label className="block text-xs text-muted-foreground mb-1">{t('escalationPolicies.step.delay')} ({t('escalationPolicies.step.delayMinutes')})</label>
            <input
              type="number"
              min={0}
              value={step.delayMinutes}
              onChange={(e) => updateStep(idx, { delayMinutes: parseInt(e.target.value) || 0 })}
              className="w-24 px-2 py-1 bg-input border rounded text-sm"
            />
          </div>
          <div>
            <label className="block text-xs text-muted-foreground mb-1">{t('escalationPolicies.step.channels')}</label>
            <div className="flex flex-wrap gap-1">
              {ALL_CHANNEL_TYPES.map((ch) => (
                <button
                  key={ch}
                  type="button"
                  onClick={() => toggleStepChannel(idx, ch)}
                  className={cn(
                    'text-xs px-2 py-0.5 rounded border transition-colors',
                    step.channels.includes(ch) ? 'bg-primary text-primary-foreground border-primary' : 'bg-card text-muted-foreground border-muted'
                  )}
                >
                  {ch}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className="block text-xs text-muted-foreground mb-1">{t('escalationPolicies.step.contacts')}</label>
            {contacts.length === 0 ? (
              <p className="text-xs text-muted-foreground">{t('contacts.empty')}</p>
            ) : (
              <div className="flex flex-wrap gap-1">
                {contacts.map((c) => (
                  <button
                    key={c.id}
                    type="button"
                    onClick={() => toggleStepContact(idx, c.id)}
                    className={cn(
                      'text-xs px-2 py-0.5 rounded border transition-colors',
                      step.contactIds.includes(c.id) ? 'bg-primary text-primary-foreground border-primary' : 'bg-card text-muted-foreground border-muted'
                    )}
                  >
                    {c.name}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      ))}
      <div className="flex gap-2">
        <button onClick={addStep} className="px-3 py-1.5 border rounded-md text-sm hover:bg-accent">
          + {t('escalationPolicies.step.addStep')}
        </button>
        <button
          onClick={() => onSave({ ...policy, steps })}
          disabled={isSaving}
          className="px-4 py-1.5 bg-primary text-primary-foreground rounded-md text-sm hover:opacity-90 disabled:opacity-50"
        >
          {isSaving ? tc('saving') : tc('save')}
        </button>
      </div>
    </div>
  );
}

function PolicyDialog({
  onClose,
  onSave,
  isSaving,
}: {
  onClose: () => void;
  onSave: (data: Omit<EscalationPolicy, 'id'>) => void;
  isSaving: boolean;
}) {
  const { t } = useTranslation('communication');
  const { t: tc } = useTranslation('common');
  const [name, setName] = useState('');
  const [severity, setSeverity] = useState('critical');
  const [isDefault, setIsDefault] = useState(false);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({ name, severity, isDefault, steps: [] });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-card border rounded-lg shadow-lg w-full max-w-md p-6">
        <h2 className="text-lg font-semibold mb-4">{t('escalationPolicies.addPolicy')}</h2>
        <form onSubmit={handleSubmit} className="space-y-3">
          <div>
            <label className="block text-sm font-medium mb-1">{t('escalationPolicies.form.name')}</label>
            <input value={name} onChange={(e) => setName(e.target.value)} required className="w-full px-3 py-2 bg-input border rounded-md text-sm" placeholder="e.g. Critical Alert Policy" />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">{t('escalationPolicies.form.severity')}</label>
            <select value={severity} onChange={(e) => setSeverity(e.target.value)} className="w-full px-3 py-2 bg-input border rounded-md text-sm">
              {SEVERITY_OPTIONS.map((s) => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>
          <div className="flex items-center gap-2">
            <input type="checkbox" id="isDefault" checked={isDefault} onChange={(e) => setIsDefault(e.target.checked)} className="rounded" />
            <label htmlFor="isDefault" className="text-sm">{t('escalationPolicies.form.setAsDefault')}</label>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="px-4 py-2 border rounded-md text-sm hover:bg-accent">
              {tc('cancel')}
            </button>
            <button type="submit" disabled={isSaving} className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm hover:opacity-90 disabled:opacity-50">
              {isSaving ? tc('creating') : tc('create')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
