import type { ReactNode } from 'react';
import { Image, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { useTranslation } from 'react-i18next';
import type { LucideIcon } from 'lucide-react-native';
import {
  ChevronLeft,
  Heart,
  Info,
  Languages,
  Settings,
  Share2,
  ShoppingCart,
  SlidersHorizontal,
  UserRound,
} from 'lucide-react-native';
import { naviAssets } from '../../assets/naviAssets';
import { naviTheme } from '../../theme';
import { useLocale } from '../../state/locale';

type HeaderVariant = 'brand' | 'center' | 'transparentImage' | 'planner';
type HeaderActionKind = 'profile' | 'settings' | 'cart' | 'filter' | 'info' | 'avatar' | 'share' | 'heart';

interface HeaderAction {
  kind: HeaderActionKind;
  label: string;
  onPress: () => void | Promise<void>;
  active?: boolean;
}

interface Props {
  variant: HeaderVariant;
  title?: string;
  subtitle?: string;
  stepText?: string;
  progress?: number;
  showBack?: boolean;
  backLabel?: string;
  onBack?: () => void;
  includeSafeArea?: boolean;
  actions?: HeaderAction[];
  rightSlot?: ReactNode;
}

export function NaviHeader({
  variant,
  title,
  subtitle,
  stepText,
  progress = 0,
  showBack,
  backLabel,
  onBack,
  includeSafeArea = false,
  actions = [],
  rightSlot,
}: Props) {
  const { t } = useTranslation();
  const locale = useLocale((s) => s.locale);
  const isTransparent = variant === 'transparentImage';
  const resolvedBackLabel = backLabel ?? t('actions.back');
  const shellStyle = [
    styles.shell,
    isTransparent ? styles.transparentShell : styles.solidShell,
    variant === 'planner' ? styles.plannerShell : null,
  ];

  const content = (
    <>
      <View style={styles.row}>
        {variant === 'brand' ? (
          <View style={styles.brandBlock}>
            <Image source={naviAssets.logos.mark} style={styles.logoMark} resizeMode="cover" />
            <View>
              <Text style={styles.brandName}>{t('app.name')}</Text>
              <Text style={styles.brandTagline}>{t('app.tagline')}</Text>
            </View>
          </View>
        ) : showBack ? (
          <IconButton
            label={resolvedBackLabel}
            icon={ChevronLeft}
            onPress={onBack ?? (() => router.back())}
            floating={isTransparent}
          />
        ) : (
          <View style={styles.sideSpace} />
        )}

        {variant === 'center' ? (
          <View style={styles.centerTitleBlock}>
            <Text style={styles.centerTitle} numberOfLines={1}>
              {title}
            </Text>
            {subtitle ? (
              <Text style={styles.subtitle} numberOfLines={1}>
                {subtitle}
              </Text>
            ) : null}
          </View>
        ) : null}

        {variant === 'planner' ? (
          <View style={styles.plannerTitleBlock}>
            <Text style={styles.plannerBrand}>{t('app.name')}</Text>
            {title ? (
              <Text style={styles.subtitle} numberOfLines={1}>
                {title}
              </Text>
            ) : null}
          </View>
        ) : null}

        {variant === 'brand' ? (
          <View style={styles.brandActions}>
            <Pressable style={styles.translatePill} onPress={() => router.push('/translator/')} accessibilityRole="button">
              <Languages size={16} color={naviTheme.colors.primaryBlue} strokeWidth={2.4} />
              <Text style={styles.translateText}>{t('home.translate')}</Text>
            </Pressable>
            <View style={styles.languagePill}>
              <Text style={styles.languageText}>{locale.toUpperCase()}</Text>
            </View>
          </View>
        ) : rightSlot ? (
          <View style={styles.actionRow}>{rightSlot}</View>
        ) : (
          <View style={styles.actionRow}>
            {variant === 'planner' && stepText ? <Text style={styles.stepText}>{stepText}</Text> : null}
            {actions.map((action) => (
              <IconButton
                key={`${action.kind}-${action.label}`}
                label={action.label}
                icon={iconForAction(action.kind)}
                onPress={action.onPress}
                active={!!action.active}
                floating={isTransparent}
              />
            ))}
          </View>
        )}
      </View>
      {variant === 'planner' ? (
        <View style={styles.progressTrack}>
          <View style={[styles.progressFill, { width: `${Math.min(100, Math.max(0, progress * 100))}%` }]} />
        </View>
      ) : null}
    </>
  );

  if (includeSafeArea) {
    return (
      <SafeAreaView edges={['top', 'left', 'right']} style={shellStyle}>
        {content}
      </SafeAreaView>
    );
  }

  return (
    <View style={shellStyle}>
      {content}
    </View>
  );
}

function IconButton({
  label,
  icon: Icon,
  onPress,
  active,
  floating,
}: {
  label: string;
  icon: LucideIcon;
  onPress: () => void | Promise<void>;
  active?: boolean;
  floating?: boolean;
}) {
  function handlePress() {
    try {
      const result = onPress();
      if (result && typeof result.catch === 'function') {
        void result.catch(() => undefined);
      }
    } catch {
      // Header actions route or open native UI; failures should not surface
      // as unhandled promise rejection toasts.
    }
  }

  return (
    <Pressable
      accessibilityLabel={label}
      accessibilityRole="button"
      onPress={handlePress}
      style={[styles.iconButton, floating ? styles.floatingIconButton : null]}
    >
      <Icon
        color={active ? naviTheme.colors.danger : naviTheme.colors.darkNavy}
        size={21}
        strokeWidth={2.35}
      />
    </Pressable>
  );
}

function iconForAction(kind: HeaderActionKind): LucideIcon {
  switch (kind) {
    case 'profile':
    case 'avatar':
      return UserRound;
    case 'settings':
      return Settings;
    case 'cart':
      return ShoppingCart;
    case 'filter':
      return SlidersHorizontal;
    case 'info':
      return Info;
    case 'share':
      return Share2;
    case 'heart':
      return Heart;
  }
}

const styles = StyleSheet.create({
  shell: {
    minHeight: 58,
    paddingHorizontal: naviTheme.spacing.xl,
    paddingVertical: naviTheme.spacing.sm,
  },
  solidShell: {
    backgroundColor: naviTheme.colors.background,
  },
  transparentShell: {
    backgroundColor: 'transparent',
    left: 0,
    position: 'absolute',
    right: 0,
    top: 0,
    zIndex: 10,
  },
  plannerShell: {
    gap: naviTheme.spacing.sm,
  },
  row: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: naviTheme.spacing.md,
    minHeight: 48,
  },
  brandBlock: {
    alignItems: 'center',
    flex: 1,
    flexDirection: 'row',
    gap: naviTheme.spacing.sm,
    minWidth: 0,
  },
  logoMark: {
    borderRadius: 16,
    height: 40,
    width: 40,
  },
  brandName: {
    color: naviTheme.colors.darkNavy,
    fontSize: 22,
    fontWeight: '900',
  },
  brandTagline: {
    color: naviTheme.colors.mutedText,
    fontSize: 11,
    fontWeight: '700',
  },
  brandActions: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: naviTheme.spacing.sm,
  },
  translatePill: {
    alignItems: 'center',
    backgroundColor: naviTheme.colors.softBlue,
    borderRadius: naviTheme.radius.pill,
    flexDirection: 'row',
    gap: 5,
    minHeight: 36,
    paddingHorizontal: naviTheme.spacing.md,
  },
  translateText: {
    color: naviTheme.colors.primaryBlue,
    fontSize: 12,
    fontWeight: '900',
  },
  languagePill: {
    alignItems: 'center',
    backgroundColor: naviTheme.colors.surface,
    borderColor: naviTheme.colors.border,
    borderRadius: naviTheme.radius.pill,
    borderWidth: 1,
    minHeight: 36,
    paddingHorizontal: naviTheme.spacing.md,
  },
  languageText: {
    color: naviTheme.colors.darkNavy,
    fontSize: 12,
    fontWeight: '900',
    lineHeight: 34,
  },
  sideSpace: {
    width: 44,
  },
  centerTitleBlock: {
    alignItems: 'center',
    flex: 1,
    minWidth: 0,
  },
  centerTitle: {
    color: naviTheme.colors.darkNavy,
    fontSize: 20,
    fontWeight: '900',
  },
  subtitle: {
    color: naviTheme.colors.mutedText,
    fontSize: 12,
    fontWeight: '700',
  },
  plannerTitleBlock: {
    alignItems: 'center',
    flex: 1,
  },
  plannerBrand: {
    color: naviTheme.colors.darkNavy,
    fontSize: 20,
    fontWeight: '900',
  },
  actionRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: naviTheme.spacing.sm,
    justifyContent: 'flex-end',
    minWidth: 44,
  },
  iconButton: {
    alignItems: 'center',
    backgroundColor: naviTheme.colors.surface,
    borderColor: naviTheme.colors.border,
    borderRadius: naviTheme.radius.pill,
    borderWidth: 1,
    height: 42,
    justifyContent: 'center',
    width: 42,
  },
  floatingIconButton: {
    backgroundColor: 'rgba(255,255,255,0.92)',
    borderColor: 'rgba(255,255,255,0.75)',
  },
  stepText: {
    color: naviTheme.colors.primaryBlue,
    fontSize: 12,
    fontWeight: '900',
  },
  progressTrack: {
    backgroundColor: naviTheme.colors.border,
    borderRadius: naviTheme.radius.pill,
    height: 5,
    overflow: 'hidden',
  },
  progressFill: {
    backgroundColor: naviTheme.colors.primaryBlue,
    borderRadius: naviTheme.radius.pill,
    height: '100%',
  },
});
