import { useState, useRef, useCallback } from 'react';
import { Input, Select, Switch, Button, Space, Typography, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { UnifiedPerson, ConnectionType, PeopleListResponse } from '@/types/api';
import { CONNECTION_TYPE_LABELS } from '@/types/api';

const connectionTypeOptions = Object.entries(CONNECTION_TYPE_LABELS).map(([value, label]) => ({
  value: value as ConnectionType,
  label,
}));

interface ConnectionFormProps {
  contactId: string;
  onCreated: () => void;
  onCancel: () => void;
}

export default function ConnectionForm({ contactId, onCreated, onCancel }: ConnectionFormProps) {
  const [searchResults, setSearchResults] = useState<UnifiedPerson[]>([]);
  const [searching, setSearching] = useState(false);
  const [selectedPerson, setSelectedPerson] = useState<UnifiedPerson | null>(null);
  const [connectionType, setConnectionType] = useState<ConnectionType>('HOUSEHOLD');
  const [customLabel, setCustomLabel] = useState('');
  const [notes, setNotes] = useState('');
  const [bidirectional, setBidirectional] = useState(true);
  const [creating, setCreating] = useState(false);
  const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  const handleSearch = useCallback((value: string) => {
    clearTimeout(searchTimerRef.current);
    if (!value.trim()) {
      setSearchResults([]);
      return;
    }
    searchTimerRef.current = setTimeout(async () => {
      setSearching(true);
      try {
        const { data } = await api.get<PeopleListResponse>('/people', {
          params: { search: value, limit: 5 },
        });
        setSearchResults(data.people);
      } catch {
        setSearchResults([]);
      } finally {
        setSearching(false);
      }
    }, 300);
  }, []);

  const handleCreate = async () => {
    if (!selectedPerson) {
      message.warning('Please select a person to connect with');
      return;
    }

    const [toType, toId] = selectedPerson.id.split(':');

    setCreating(true);
    try {
      await api.post(`/people/contacts/${contactId}/connections`, {
        toPersonType: toType,
        toPersonId: toId,
        type: connectionType,
        label: connectionType === 'CUSTOM' ? customLabel || undefined : undefined,
        notes: notes || undefined,
        isBidirectional: bidirectional,
      });
      message.success('Connection created');
      onCreated();
    } catch {
      message.error('Failed to create connection');
    } finally {
      setCreating(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Typography.Text strong style={{ fontSize: 13 }}>
        Add Connection
      </Typography.Text>

      {/* Person search */}
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Find Person
        </Typography.Text>
        <Select
          showSearch
          placeholder="Search by name, email, or phone..."
          filterOption={false}
          onSearch={handleSearch}
          loading={searching}
          notFoundContent={searching ? 'Searching...' : 'No results'}
          style={{ width: '100%' }}
          value={selectedPerson?.id}
          onChange={(value) => {
            const person = searchResults.find((p) => p.id === value);
            setSelectedPerson(person || null);
          }}
          options={searchResults.map((p) => ({
            value: p.id,
            label: (
              <div>
                <span style={{ fontWeight: 500 }}>{p.displayName}</span>
                {p.email && (
                  <span style={{ color: '#888', marginLeft: 8, fontSize: 12 }}>
                    {p.email}
                  </span>
                )}
              </div>
            ),
          }))}
          suffixIcon={<SearchOutlined />}
        />
      </div>

      {/* Connection type */}
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Connection Type
        </Typography.Text>
        <Select
          options={connectionTypeOptions}
          value={connectionType}
          onChange={setConnectionType}
          style={{ width: '100%' }}
        />
      </div>

      {/* Custom label (only when type=CUSTOM) */}
      {connectionType === 'CUSTOM' && (
        <div>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            Custom Label
          </Typography.Text>
          <Input
            value={customLabel}
            onChange={(e) => setCustomLabel(e.target.value)}
            placeholder="e.g., Neighbor, Friend..."
          />
        </div>
      )}

      {/* Notes */}
      <div>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          Notes (optional)
        </Typography.Text>
        <Input.TextArea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={2}
          placeholder="Any context about this connection..."
        />
      </div>

      {/* Bidirectional toggle */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography.Text style={{ fontSize: 13 }}>Bidirectional</Typography.Text>
        <Switch checked={bidirectional} onChange={setBidirectional} size="small" />
      </div>

      {/* Actions */}
      <Space style={{ marginTop: 4 }}>
        <Button type="primary" onClick={handleCreate} loading={creating} size="small">
          Create
        </Button>
        <Button onClick={onCancel} size="small">
          Cancel
        </Button>
      </Space>
    </div>
  );
}
