import { useState, useEffect, useCallback } from 'react';
import {
  Button,
  Input,
  Select,
  Checkbox,
  Tag,
  Space,
  Typography,
  message,
  Popconfirm,
  Spin,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  PhoneOutlined,
  StarFilled,
  StarOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { ContactPhoneLink } from '@/types/api';

interface ContactPhonePanelProps {
  contactId: string;
}

const LABEL_OPTIONS = [
  { value: 'Mobile', label: 'Mobile' },
  { value: 'Home', label: 'Home' },
  { value: 'Work', label: 'Work' },
  { value: 'Other', label: 'Other' },
];

export default function ContactPhonePanel({ contactId }: ContactPhonePanelProps) {
  const [phones, setPhones] = useState<ContactPhoneLink[]>([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);

  // Form state
  const [formPhone, setFormPhone] = useState('');
  const [formLabel, setFormLabel] = useState<string | undefined>(undefined);
  const [formPrimary, setFormPrimary] = useState(false);

  const fetchPhones = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<{ phones: ContactPhoneLink[] }>(
        `/people/contacts/${contactId}/phones`,
      );
      setPhones(data.phones);
    } catch {
      setPhones([]);
    } finally {
      setLoading(false);
    }
  }, [contactId]);

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

  const handleAdd = async () => {
    if (!formPhone.trim()) {
      message.warning('Phone number is required');
      return;
    }
    setSaving(true);
    try {
      await api.post(`/people/contacts/${contactId}/phones`, {
        phone: formPhone.trim(),
        label: formLabel || undefined,
        isPrimary: formPrimary,
      });
      message.success('Phone added');
      setFormPhone('');
      setFormLabel(undefined);
      setFormPrimary(false);
      setShowForm(false);
      fetchPhones();
    } catch {
      message.error('Failed to add phone');
    } finally {
      setSaving(false);
    }
  };

  const handleRemove = async (phoneId: string) => {
    try {
      await api.delete(`/people/contacts/${contactId}/phones/${phoneId}`);
      message.success('Phone removed');
      fetchPhones();
    } catch {
      message.error('Failed to remove phone');
    }
  };

  const handleSetPrimary = async (phoneId: string) => {
    try {
      await api.put(`/people/contacts/${contactId}/phones/${phoneId}/primary`);
      message.success('Primary phone updated');
      fetchPhones();
    } catch {
      message.error('Failed to set primary phone');
    }
  };

  if (loading && phones.length === 0) {
    return (
      <div style={{ textAlign: 'center', padding: 12 }}>
        <Spin size="small" />
      </div>
    );
  }

  return (
    <div>
      {/* Phone list */}
      {phones.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 12 }}>
          {phones.map((cp) => (
            <div
              key={cp.id}
              style={{
                padding: '8px 12px',
                background: 'rgba(255,255,255,0.04)',
                borderRadius: 6,
                border: '1px solid rgba(255,255,255,0.08)',
                display: 'flex',
                alignItems: 'center',
                gap: 8,
              }}
            >
              <PhoneOutlined style={{ color: 'rgba(255,255,255,0.45)', fontSize: 14 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13 }}>{cp.phone}</div>
                <Space size={4} style={{ marginTop: 2 }}>
                  {cp.isPrimary && (
                    <Tag color="gold" style={{ margin: 0, fontSize: 10, lineHeight: '16px' }}>
                      <StarFilled style={{ marginRight: 2 }} />Primary
                    </Tag>
                  )}
                  {cp.label && (
                    <Tag style={{ margin: 0, fontSize: 10, lineHeight: '16px' }}>{cp.label}</Tag>
                  )}
                </Space>
              </div>
              <Space size={4}>
                {!cp.isPrimary && (
                  <Tooltip title="Set as Primary">
                    <Button
                      type="text"
                      size="small"
                      icon={<StarOutlined />}
                      onClick={() => handleSetPrimary(cp.id)}
                    />
                  </Tooltip>
                )}
                <Popconfirm
                  title="Remove this phone?"
                  onConfirm={() => handleRemove(cp.id)}
                >
                  <Button type="text" size="small" danger icon={<DeleteOutlined />} />
                </Popconfirm>
              </Space>
            </div>
          ))}
        </div>
      )}

      {/* Add phone form */}
      {showForm ? (
        <div
          style={{
            padding: 12,
            background: 'rgba(255,255,255,0.04)',
            borderRadius: 8,
            border: '1px solid rgba(255,255,255,0.08)',
          }}
        >
          <div style={{ marginBottom: 8 }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              Phone Number *
            </Typography.Text>
            <Input
              value={formPhone}
              onChange={(e) => setFormPhone(e.target.value)}
              placeholder="+1 555 000 0000"
              onPressEnter={handleAdd}
            />
          </div>
          <div style={{ marginBottom: 8 }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              Label
            </Typography.Text>
            <Select
              value={formLabel}
              onChange={setFormLabel}
              options={LABEL_OPTIONS}
              allowClear
              placeholder="Select label..."
              style={{ width: '100%' }}
            />
          </div>
          <div style={{ marginBottom: 12 }}>
            <Checkbox
              checked={formPrimary}
              onChange={(e) => setFormPrimary(e.target.checked)}
            >
              <Typography.Text style={{ fontSize: 13 }}>Set as primary phone</Typography.Text>
            </Checkbox>
          </div>
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={handleAdd}
              loading={saving}
            >
              Add
            </Button>
            <Button
              size="small"
              onClick={() => {
                setShowForm(false);
                setFormPhone('');
                setFormLabel(undefined);
                setFormPrimary(false);
              }}
            >
              Cancel
            </Button>
          </Space>
        </div>
      ) : (
        <Button
          size="small"
          icon={<PlusOutlined />}
          onClick={() => setShowForm(true)}
        >
          Add Phone
        </Button>
      )}
    </div>
  );
}
