import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { useTheme } from '@theme';
import { getStyles } from './leadDetailHeader.styles';
import { LeadDetailHeaderProps } from './leadDetailHeader.props';
import { getInitials, toRgba } from '@utils';
import { useAppSelector, RootState } from '@store';

export const LeadDetailHeader: React.FC<LeadDetailHeaderProps> = ({
  name,
  company,
  email,
  phonenumber,
  statusId,
  statusName,
  statusColor,
  avatarColor,
  onEmailPress,
  onPhonePress,
  onStatusChange,
}) => {
  const { theme: colors, isDark } = useTheme();
  const styles = getStyles(colors);

  const { items: statusList } = useAppSelector((state: RootState) => state.statusList);

  const [selectedStatusId, setSelectedStatusId] = useState(statusId);
  const [menuVisible, setMenuVisible] = useState(false);

  const currentStatus = statusList.find(s => s.id === selectedStatusId) || {
    name: statusName,
    color: statusColor,
  };

  const accent = currentStatus.color || avatarColor || '#5B4CF5';
  const badgeBg = toRgba(accent, isDark ? 0.20 : 0.12);

  const handleSelectStatus = (newStatusId: string) => {
    setSelectedStatusId(newStatusId);
    setMenuVisible(false);
    if (onStatusChange) {
      onStatusChange(newStatusId);
    }
  };

  return (
    <View style={[styles.card, menuVisible && { zIndex: 100, elevation: 10 }]}>
      {/* Top Row: Avatar + Info + Status */}
      <View style={styles.topRow}>
        <View style={[styles.avatar, { backgroundColor: accent }]}>
          <Text style={styles.avatarText}>{getInitials(name)}</Text>
        </View>

        <View style={styles.info}>
          <Text style={styles.name} numberOfLines={1}>{name || 'No Name'}</Text>
          {company ? (
            <Text style={styles.company} numberOfLines={1}>{company}</Text>
          ) : null}
          <Text style={styles.contact} numberOfLines={1}>
            <Icon name="call-outline" size={10} color={colors.textMuted} />
            {' '}{phonenumber || 'N/A'}{'   '}
            <Icon name="mail-outline" size={10} color={colors.textMuted} />
            {' '}{email || 'N/A'}
          </Text>
        </View>

        <View style={{ position: 'relative' }}>
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => setMenuVisible(!menuVisible)}
            style={[
              styles.statusDropdownButton,
              {
                backgroundColor: badgeBg,
                borderColor: toRgba(accent, 0.3),
              },
            ]}>
            <View style={[styles.statusDot, { backgroundColor: accent }]} />
            <Text style={[styles.statusDropdownText, { color: accent }]}>
              {currentStatus.name || 'No Status'}
            </Text>
            <Icon name={menuVisible ? 'chevron-up' : 'chevron-down'} size={10} color={accent} />
          </TouchableOpacity>

          {menuVisible && (
            <View style={styles.menuOverlay}>
              {statusList.map(statusItem => {
                const isActive = statusItem.id === selectedStatusId;
                const statusItemColor = statusItem.color?.startsWith('#') ? statusItem.color : colors.icon;
                return (
                  <TouchableOpacity
                    key={statusItem.id}
                    style={[styles.menuItem, isActive && styles.menuItemActive]}
                    onPress={() => handleSelectStatus(statusItem.id)}>
                    <View style={[styles.menuItemDot, { backgroundColor: statusItemColor }]} />
                    <Text
                      style={[
                        styles.menuItemText,
                        isActive && styles.menuItemTextActive,
                      ]}
                      numberOfLines={1}>
                      {statusItem.name}
                    </Text>
                    {isActive && (
                      <Icon name="checkmark" size={12} color={colors.text} />
                    )}
                  </TouchableOpacity>
                );
              })}
            </View>
          )}
        </View>
      </View>

      {/* Bottom Row: Call + Email Buttons */}
      <View style={styles.actionRow}>
        <TouchableOpacity
          style={[styles.actionBtn, { backgroundColor: `${accent}12`, borderColor: `${accent}30` }]}
          onPress={onPhonePress}>
          <Icon name="call" size={14} color={accent} />
          <Text style={[styles.btnText, { color: accent }]}>Call</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.actionBtn, styles.secondaryBtn]}
          onPress={onEmailPress}>
          <Icon name="mail" size={14} color={colors.textSecondary} />
          <Text style={[styles.btnText, { color: colors.textSecondary }]}>Email</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};
