import { useState, useEffect } from 'react';
import { Drawer, Input, List, Tag, Typography, Space, Button, App } from 'antd';
import { SendOutlined, PhoneOutlined, UserOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { useDebounce } from '@/hooks/useDebounce';
import type { SmsContactSearchResult, SmsConversation } from '@/types/sms';
import { getErrorMessage } from '@/utils/getErrorMessage';

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

const SOURCE_LABELS: Record<string, { label: string; color: string }> = {
  sms_contact: { label: 'SMS List', color: 'purple' },
  crm_contact: { label: 'CRM', color: 'blue' },
  conversation: { label: 'Previous', color: 'default' },
};

interface Props {
  open: boolean;
  onClose: () => void;
  onCreated: (conv: SmsConversation) => void;
}

export default function NewConversationModal({ open, onClose, onCreated }: Props) {
  const { message } = App.useApp();

  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SmsContactSearchResult[]>([]);
  const [searching, setSearching] = useState(false);
  const [selectedContact, setSelectedContact] = useState<SmsContactSearchResult | null>(null);
  const [msgText, setMsgText] = useState('');
  const [sending, setSending] = useState(false);

  const debouncedQuery = useDebounce(query, 300);

  // Search contacts when debounced query changes
  useEffect(() => {
    if (!debouncedQuery || debouncedQuery.length < 2) {
      setResults([]);
      return;
    }
    let cancelled = false;
    setSearching(true);
    api.get<{ results: SmsContactSearchResult[] }>('/sms/conversations/contact-search', {
      params: { q: debouncedQuery },
    }).then(({ data }) => {
      if (!cancelled) setResults(data.results);
    }).catch(() => {
      if (!cancelled) setResults([]);
    }).finally(() => {
      if (!cancelled) setSearching(false);
    });
    return () => { cancelled = true; };
  }, [debouncedQuery]);

  // Check if query looks like a phone number (mostly digits, 7+)
  const digitsOnly = query.replace(/\D/g, '');
  const isPhoneQuery = digitsOnly.length >= 7;
  const phoneAlreadyInResults = isPhoneQuery && results.some((r) => r.phone.includes(digitsOnly));

  const handleSelect = (contact: SmsContactSearchResult) => {
    setSelectedContact(contact);
  };

  const handleManualPhone = () => {
    setSelectedContact({
      phone: digitsOnly,
      name: null,
      source: 'sms_contact',
      sourceId: '',
    });
  };

  const handleSend = async () => {
    if (!selectedContact || !msgText.trim()) return;
    setSending(true);
    try {
      const { data } = await api.post<SmsConversation>('/sms/conversations', {
        phone: selectedContact.phone,
        message: msgText.trim(),
        contactName: selectedContact.name || undefined,
        contactId: selectedContact.contactId || undefined,
      });
      message.success('Message queued');
      onCreated(data);
      handleReset();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to send message'));
    } finally {
      setSending(false);
    }
  };

  const handleReset = () => {
    setQuery('');
    setResults([]);
    setSelectedContact(null);
    setMsgText('');
    onClose();
  };

  const handleBack = () => {
    setSelectedContact(null);
    setMsgText('');
  };

  return (
    <Drawer
      title="New Conversation"
      open={open}
      onClose={handleReset}
      destroyOnHidden
      placement="right"
      width={480}
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
    >
      {!selectedContact ? (
        // Step 1: Contact Search
        <div>
          <Input
            placeholder="Search by name or phone number..."
            prefix={<PhoneOutlined />}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            allowClear
            autoFocus
          />

          <div style={{ marginTop: 12, maxHeight: 320, overflowY: 'auto' }}>
            {/* Manual phone entry option */}
            {isPhoneQuery && !phoneAlreadyInResults && (
              <div
                onClick={handleManualPhone}
                style={{
                  padding: '8px 12px',
                  cursor: 'pointer',
                  borderRadius: 6,
                  marginBottom: 4,
                  border: '1px dashed rgba(255,255,255,0.15)',
                }}
                onMouseEnter={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,0.06)')}
                onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
              >
                <Space>
                  <PhoneOutlined />
                  <Text>Use number: {digitsOnly}</Text>
                  <Tag color="green">Manual</Tag>
                </Space>
              </div>
            )}

            <List
              loading={searching}
              dataSource={results}
              locale={{ emptyText: query.length >= 2 ? 'No contacts found' : 'Type to search...' }}
              renderItem={(item) => (
                <List.Item
                  onClick={() => handleSelect(item)}
                  style={{ cursor: 'pointer', padding: '8px 12px', borderRadius: 6 }}
                  onMouseEnter={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,0.06)')}
                  onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center' }}>
                    <Space>
                      <UserOutlined />
                      <div>
                        <Text strong>{item.name || item.phone}</Text>
                        {item.name && <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>{item.phone}</Text>}
                      </div>
                    </Space>
                    <Tag color={SOURCE_LABELS[item.source]?.color}>
                      {SOURCE_LABELS[item.source]?.label}
                    </Tag>
                  </div>
                </List.Item>
              )}
            />
          </div>
        </div>
      ) : (
        // Step 2: Compose Message
        <div>
          <Button type="link" onClick={handleBack} style={{ padding: 0, marginBottom: 8 }}>
            &larr; Change contact
          </Button>

          <div style={{
            padding: '10px 14px',
            background: 'rgba(255,255,255,0.04)',
            borderRadius: 8,
            marginBottom: 12,
          }}>
            <Space>
              <UserOutlined />
              <div>
                {selectedContact.name && <Text strong>{selectedContact.name}</Text>}
                <Text type="secondary" style={{ marginLeft: selectedContact.name ? 8 : 0 }}>
                  {selectedContact.phone}
                </Text>
              </div>
            </Space>
          </div>

          <TextArea
            rows={4}
            value={msgText}
            onChange={(e) => setMsgText(e.target.value)}
            placeholder="Type your message..."
            maxLength={1600}
            showCount
            autoFocus
          />

          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
            <Space>
              <Button onClick={handleReset}>Cancel</Button>
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSend}
                loading={sending}
                disabled={!msgText.trim()}
              >
                Send
              </Button>
            </Space>
          </div>
        </div>
      )}
    </Drawer>
  );
}
