import { useState, useEffect, useCallback } from 'react';
import { List, Avatar, Typography, Tag, Button, Spin, Empty, Space, message } from 'antd';
import { HomeOutlined, StarFilled, TeamOutlined } from '@ant-design/icons';
import type { HouseholdMember } from '@/types/api';
import { SUPPORT_LEVEL_LABELS, SUPPORT_LEVEL_COLORS } from '@/types/api';
import { api } from '@/lib/api';

interface HouseholdPanelProps {
  personId: string;
  addressId?: string;
}

interface HouseholdResponse {
  locationId: string;
  address: string;
  members: HouseholdMember[];
}

export default function HouseholdPanel({ personId }: HouseholdPanelProps) {
  const [loading, setLoading] = useState(true);
  const [households, setHouseholds] = useState<HouseholdResponse[]>([]);
  const [detectingHousehold, setDetectingHousehold] = useState(false);

  const parsePersonId = (id: string): { type: string; sourceId: string } => {
    const colonIdx = id.indexOf(':');
    if (colonIdx === -1) return { type: 'contact', sourceId: id };
    return { type: id.substring(0, colonIdx), sourceId: id.substring(colonIdx + 1) };
  };

  const fetchHousehold = useCallback(async () => {
    setLoading(true);
    try {
      const { type, sourceId } = parsePersonId(personId);
      const { data } = await api.get<{ households: HouseholdResponse[] }>(
        `/people/${type}/${sourceId}/household`,
      );
      setHouseholds(data.households || []);
    } catch {
      setHouseholds([]);
    } finally {
      setLoading(false);
    }
  }, [personId]);

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

  const handleDetectHousehold = async (locationId: string) => {
    setDetectingHousehold(true);
    try {
      await api.post(`/people/household/${locationId}/detect`);
      message.success('Household connections created');
      fetchHousehold();
    } catch {
      message.error('Failed to detect household connections');
    } finally {
      setDetectingHousehold(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 32 }}>
        <Spin />
      </div>
    );
  }

  if (households.length === 0) {
    return (
      <Empty
        description="No address data associated with this person."
        image={Empty.PRESENTED_IMAGE_SIMPLE}
      />
    );
  }

  return (
    <div>
      {households.map((household) => (
        <div key={household.locationId} style={{ marginBottom: 20 }}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: 12,
              padding: '8px 12px',
              background: 'rgba(255,255,255,0.04)',
              borderRadius: 6,
              border: '1px solid rgba(255,255,255,0.08)',
            }}
          >
            <Space>
              <HomeOutlined style={{ color: '#52c41a' }} />
              <Typography.Text strong>{household.address}</Typography.Text>
            </Space>
            <Button
              size="small"
              icon={<TeamOutlined />}
              onClick={() => handleDetectHousehold(household.locationId)}
              loading={detectingHousehold}
            >
              Detect Connections
            </Button>
          </div>

          {household.members.length === 0 ? (
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              No other members found at this address.
            </Typography.Text>
          ) : (
            <List
              size="small"
              dataSource={household.members}
              renderItem={(member) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Avatar size={28} style={{ backgroundColor: '#722ed1', fontSize: 11 }}>
                        {member.person.displayName?.[0]?.toUpperCase() || '?'}
                      </Avatar>
                    }
                    title={
                      <Space size={6}>
                        <span style={{ fontSize: 13 }}>{member.person.displayName}</span>
                        {member.unitNumber && (
                          <Tag style={{ fontSize: 10, margin: 0 }}>Unit {member.unitNumber}</Tag>
                        )}
                        {member.person.supportLevel && (
                          <Tag
                            color={SUPPORT_LEVEL_COLORS[member.person.supportLevel]}
                            style={{ fontSize: 10, margin: 0 }}
                          >
                            {SUPPORT_LEVEL_LABELS[member.person.supportLevel]}
                          </Tag>
                        )}
                        {member.person.isManaged && (
                          <StarFilled style={{ color: '#faad14', fontSize: 12 }} />
                        )}
                        {member.isPrimary && (
                          <Tag color="blue" style={{ fontSize: 10, margin: 0 }}>
                            Primary
                          </Tag>
                        )}
                      </Space>
                    }
                    description={
                      <Typography.Text type="secondary" style={{ fontSize: 11 }}>
                        {member.person.email || member.person.phone || 'No contact info'}
                      </Typography.Text>
                    }
                  />
                </List.Item>
              )}
            />
          )}
        </div>
      ))}
    </div>
  );
}
