import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import type { FunnelConversionStats } from '../../types/funnel';

interface FunnelChartProps {
  stats: FunnelConversionStats;
}

function getFunnelLevels() {
  return [
    { key: 'totalNew' as const, label: 'Новые', color: '#1565C0' },
    { key: 'totalAssigned' as const, label: 'Назначенные', color: colors.primary },
    { key: 'totalCompleted' as const, label: 'Проведённые', color: '#FFB300' },
    { key: 'totalRegular' as const, label: 'Постоянные', color: colors.success },
  ];
}

const CONVERSION_KEYS: Array<{
  key: keyof FunnelConversionStats;
  from: string;
  to: string;
}> = [
  { key: 'newToAssigned', from: 'Новые', to: 'Назначенные' },
  { key: 'assignedToCompleted', from: 'Назначенные', to: 'Проведённые' },
  { key: 'completedToRegular', from: 'Проведённые', to: 'Постоянные' },
];

function formatPercent(value: number): string {
  return `${Math.round(value)}%`;
}

export function FunnelChart({ stats }: FunnelChartProps): React.JSX.Element {
  const styles = createStyles();
  const maxValue = Math.max(
    stats.totalNew,
    stats.totalAssigned,
    stats.totalCompleted,
    stats.totalRegular,
    1,
  );

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Воронка конверсии</Text>

      {getFunnelLevels().map((level, index) => {
        const value = stats[level.key];
        const barWidth = Math.max((value / maxValue) * 100, 8);
        const conversion = CONVERSION_KEYS[index];

        return (
          <View key={level.key}>
            <View style={styles.barRow}>
              <Text style={styles.barLabel}>{level.label}</Text>
              <View style={styles.barTrack}>
                <View
                  style={[
                    styles.barFill,
                    {
                      width: `${barWidth}%`,
                      backgroundColor: level.color,
                    },
                  ]}
                />
              </View>
              <Text style={styles.barValue}>{value}</Text>
            </View>

            {conversion && (
              <View style={styles.conversionRow}>
                <View style={styles.conversionLine} />
                <Text style={styles.conversionText}>
                  {formatPercent(stats[conversion.key] as number)}
                </Text>
                <View style={styles.conversionLine} />
              </View>
            )}
          </View>
        );
      })}

      <View style={styles.legendContainer}>
        {CONVERSION_KEYS.map((conv) => (
          <View key={conv.key} style={styles.legendItem}>
            <Text style={styles.legendLabel}>
              {conv.from} {'->'} {conv.to}
            </Text>
            <Text style={styles.legendValue}>
              {formatPercent(stats[conv.key] as number)}
            </Text>
          </View>
        ))}
      </View>
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    backgroundColor: colors.card,
    borderRadius: 12,
    padding: spacing.lg,
    shadowColor: colors.black,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.08,
    shadowRadius: 8,
    elevation: 3,
  },
  title: {
    ...typography.subtitle,
    color: colors.text,
    marginBottom: spacing.xl,
  },
  barRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: spacing.xs,
  },
  barLabel: {
    ...typography.caption,
    color: colors.textSecondary,
    width: 100,
  },
  barTrack: {
    flex: 1,
    height: 24,
    backgroundColor: colors.background,
    borderRadius: 6,
    overflow: 'hidden',
    marginHorizontal: spacing.sm,
  },
  barFill: {
    height: '100%',
    borderRadius: 6,
    minWidth: 24,
  },
  barValue: {
    ...typography.bodySmall,
    fontWeight: '600',
    color: colors.text,
    width: 40,
    textAlign: 'right',
  },
  conversionRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: spacing.xs,
    paddingLeft: 100,
    paddingRight: 40,
  },
  conversionLine: {
    flex: 1,
    height: 1,
    backgroundColor: colors.border,
  },
  conversionText: {
    ...typography.caption,
    fontWeight: '600',
    color: colors.primary,
    paddingHorizontal: spacing.sm,
  },
  legendContainer: {
    marginTop: spacing.lg,
    paddingTop: spacing.lg,
    borderTopWidth: 1,
    borderTopColor: colors.border,
  },
  legendItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.sm,
  },
  legendLabel: {
    ...typography.caption,
    color: colors.textSecondary,
  },
  legendValue: {
    ...typography.bodySmall,
    fontWeight: '600',
    color: colors.primary,
  },
});
