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

interface ContactAddressPanelProps {
  contactId: string;
}

export default function ContactAddressPanel({ contactId }: ContactAddressPanelProps) {
  const [addresses, setAddresses] = useState<ContactAddressLink[]>([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);

  // Form state
  const [formAddress, setFormAddress] = useState('');
  const [formUnit, setFormUnit] = useState('');
  const [formPrimary, setFormPrimary] = useState(false);

  const fetchAddresses = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<{ addresses: ContactAddressLink[] }>(
        `/people/contacts/${contactId}/addresses`,
      );
      setAddresses(data.addresses);
    } catch {
      // Silently fail — addresses section is supplementary
      setAddresses([]);
    } finally {
      setLoading(false);
    }
  }, [contactId]);

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

  const handleAdd = async () => {
    if (!formAddress.trim()) {
      message.warning('Street address is required');
      return;
    }
    setSaving(true);
    try {
      const payload: AddContactAddressPayload = {
        address: formAddress.trim(),
        unitNumber: formUnit.trim() || undefined,
        isPrimary: formPrimary,
        addToMap: true,
      };
      await api.post(`/people/contacts/${contactId}/addresses`, payload);
      message.success('Address added');
      setFormAddress('');
      setFormUnit('');
      setFormPrimary(false);
      setShowForm(false);
      fetchAddresses();
    } catch {
      message.error('Failed to add address');
    } finally {
      setSaving(false);
    }
  };

  const handleRemove = async (linkId: string) => {
    try {
      await api.delete(`/people/contacts/${contactId}/addresses/${linkId}`);
      message.success('Address unlinked');
      fetchAddresses();
    } catch {
      message.error('Failed to remove address');
    }
  };

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

  return (
    <div>
      {/* Address list */}
      {addresses.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 12 }}>
          {addresses.map((ca) => (
            <div
              key={ca.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,
              }}
            >
              <EnvironmentOutlined style={{ color: 'rgba(255,255,255,0.45)', fontSize: 14 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13 }}>
                  {ca.address.location.address}
                  {ca.address.unitNumber && (
                    <span style={{ color: 'rgba(255,255,255,0.45)' }}>
                      {' '}Unit {ca.address.unitNumber}
                    </span>
                  )}
                </div>
                <Space size={4} style={{ marginTop: 2 }}>
                  {ca.isPrimary && (
                    <Tag color="gold" style={{ margin: 0, fontSize: 10, lineHeight: '16px' }}>
                      <StarFilled style={{ marginRight: 2 }} />Primary
                    </Tag>
                  )}
                  {ca.address.location.geocodeConfidence != null && (
                    <Typography.Text
                      type="secondary"
                      style={{ fontSize: 11 }}
                    >
                      {ca.address.location.geocodeConfidence}% geocoded
                    </Typography.Text>
                  )}
                </Space>
              </div>
              <Space size={4}>
                <Tooltip title="View on Map">
                  <Button
                    type="text"
                    size="small"
                    icon={<EnvironmentOutlined />}
                    onClick={() => {
                      window.open(`/app/map/locations`, '_blank');
                    }}
                  />
                </Tooltip>
                <Popconfirm
                  title="Unlink this address?"
                  description="The location will remain on the map."
                  onConfirm={() => handleRemove(ca.id)}
                >
                  <Button type="text" size="small" danger icon={<DeleteOutlined />} />
                </Popconfirm>
              </Space>
            </div>
          ))}
        </div>
      )}

      {/* Add address 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 }}>
              Street Address *
            </Typography.Text>
            <Input
              value={formAddress}
              onChange={(e) => setFormAddress(e.target.value)}
              placeholder="123 Main St, City, Province"
              onPressEnter={handleAdd}
            />
          </div>
          <div style={{ marginBottom: 8 }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              Unit / Apt #
            </Typography.Text>
            <Input
              value={formUnit}
              onChange={(e) => setFormUnit(e.target.value)}
              placeholder="e.g. 4B"
              style={{ width: 120 }}
            />
          </div>
          <div style={{ marginBottom: 12 }}>
            <Checkbox
              checked={formPrimary}
              onChange={(e) => setFormPrimary(e.target.checked)}
            >
              <Typography.Text style={{ fontSize: 13 }}>Set as primary address</Typography.Text>
            </Checkbox>
          </div>
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={handleAdd}
              loading={saving}
            >
              Add
            </Button>
            <Button
              size="small"
              onClick={() => {
                setShowForm(false);
                setFormAddress('');
                setFormUnit('');
                setFormPrimary(false);
              }}
            >
              Cancel
            </Button>
          </Space>
        </div>
      ) : (
        <Button
          size="small"
          icon={<PlusOutlined />}
          onClick={() => setShowForm(true)}
        >
          Add Address
        </Button>
      )}
    </div>
  );
}
