import React from 'react';
import { View } from 'react-native';
import Svg, { Path } from 'react-native-svg';
import { useTheme } from '../../theme/ThemeProvider';
import svgIcons from '../../theme/brands/svg-icons.json';

const getIconData = (iconName: string, brand: string = 'lloyds'): IconData => {
  const brandIcons = svgIcons[brand as keyof typeof svgIcons];
  const sharedIcons = svgIcons.shared;

  let iconData: any;

  if (brandIcons && brandIcons[iconName as keyof typeof brandIcons]) {
    iconData = brandIcons[iconName as keyof typeof brandIcons];
  } else if (sharedIcons[iconName as keyof typeof sharedIcons]) {
    iconData = sharedIcons[iconName as keyof typeof sharedIcons];
  } else {
    throw new Error(`Icon "${iconName}" not found in brand "${brand}" or shared icons`);
  }

  // Type guard to ensure we have the correct structure
  if (typeof iconData === 'object' && iconData.paths) {
    return iconData as IconData;
  }

  throw new Error(`Invalid icon data structure for "${iconName}"`);
};

interface PathData {
  d: string;
  strokeWidth?: number;
  strokeLinecap?: "round" | "butt" | "square";
  strokeLinejoin?: "round" | "miter" | "bevel";
}

interface IconData {
  paths: PathData[];
}

interface IconProps {
  name?: string;
  d?: string;
  size?: number;
  color?: string;
  brand?: string;
}

export const Icon: React.FC<IconProps> = ({
  name,
  d,
  size = 24,
  color,
  brand = 'lloyds'
}) => {
  const { theme } = useTheme();

  const iconData = name ? getIconData(name, brand) : null;
  const pathData: PathData[] = iconData ? iconData.paths : (d ? [{ d }] : []);

  if (pathData.length === 0) {
    throw new Error('Icon component requires either "name" or "d" prop');
  }

  return (
    <Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      {pathData.map((path: PathData, index: number) => (
        <Path
          key={index}
          d={path.d}
          stroke={color || theme.colors.text}
          strokeWidth={path.strokeWidth || 1.5}
          strokeLinecap={path.strokeLinecap || "round"}
          strokeLinejoin={path.strokeLinejoin || "round"}
        />
      ))}
    </Svg>
  );
};