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

interface ContactEmailPanelProps {
  contactId: string;
}

const LABEL_OPTIONS = [
  { value: 'Personal', label: 'Personal' },
  { value: 'Work', label: 'Work' },
  { value: 'Campaign', label: 'Campaign' },
  { value: 'Other', label: 'Other' },
];

export default function ContactEmailPanel({ contactId }: ContactEmailPanelProps) {
  const [emails, setEmails] = useState<ContactEmailLink[]>([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);

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

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

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

  const handleAdd = async () => {
    if (!formEmail.trim()) {
      message.warning('Email address is required');
      return;
    }
    setSaving(true);
    try {
      await api.post(`/people/contacts/${contactId}/emails`, {
        email: formEmail.trim(),
        label: formLabel || undefined,
        isPrimary: formPrimary,
      });
      message.success('Email added');
      setFormEmail('');
      setFormLabel(undefined);
      setFormPrimary(false);
      setShowForm(false);
      fetchEmails();
    } catch {
      message.error('Failed to add email');
    } finally {
      setSaving(false);
    }
  };

  const handleRemove = async (emailId: string) => {
    try {
      await api.delete(`/people/contacts/${contactId}/emails/${emailId}`);
      message.success('Email removed');
      fetchEmails();
    } catch {
      message.error('Failed to remove email');
    }
  };

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

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

  return (
    <div>
      {/* Email list */}
      {emails.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 12 }}>
          {emails.map((ce) => (
            <div
              key={ce.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,
              }}
            >
              <MailOutlined style={{ color: 'rgba(255,255,255,0.45)', fontSize: 14 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13 }}>{ce.email}</div>
                <Space size={4} style={{ marginTop: 2 }}>
                  {ce.isPrimary && (
                    <Tag color="gold" style={{ margin: 0, fontSize: 10, lineHeight: '16px' }}>
                      <StarFilled style={{ marginRight: 2 }} />Primary
                    </Tag>
                  )}
                  {ce.label && (
                    <Tag style={{ margin: 0, fontSize: 10, lineHeight: '16px' }}>{ce.label}</Tag>
                  )}
                </Space>
              </div>
              <Space size={4}>
                {!ce.isPrimary && (
                  <Tooltip title="Set as Primary">
                    <Button
                      type="text"
                      size="small"
                      icon={<StarOutlined />}
                      onClick={() => handleSetPrimary(ce.id)}
                    />
                  </Tooltip>
                )}
                <Popconfirm
                  title="Remove this email?"
                  onConfirm={() => handleRemove(ce.id)}
                >
                  <Button type="text" size="small" danger icon={<DeleteOutlined />} />
                </Popconfirm>
              </Space>
            </div>
          ))}
        </div>
      )}

      {/* Add email 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 }}>
              Email Address *
            </Typography.Text>
            <Input
              value={formEmail}
              onChange={(e) => setFormEmail(e.target.value)}
              placeholder="jane@example.com"
              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 email</Typography.Text>
            </Checkbox>
          </div>
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={handleAdd}
              loading={saving}
            >
              Add
            </Button>
            <Button
              size="small"
              onClick={() => {
                setShowForm(false);
                setFormEmail('');
                setFormLabel(undefined);
                setFormPrimary(false);
              }}
            >
              Cancel
            </Button>
          </Space>
        </div>
      ) : (
        <Button
          size="small"
          icon={<PlusOutlined />}
          onClick={() => setShowForm(true)}
        >
          Add Email
        </Button>
      )}
    </div>
  );
}
