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

interface FunnelCardProps {
  entry: FunnelEntry;
  onPress: (entry: FunnelEntry) => void;
}

const STAGE_LABELS: Record<FunnelStage, string> = {
  NEW: 'Новый',
  ASSIGNED: 'Назначен',
  APPOINTMENT_SET: 'Запланирован',
  COMPLETED: 'Проведён',
  REGULAR: 'Постоянный',
  REFUSED: 'Отказ',
  TRANSFERRED: 'Перенесён',
};

const STAGE_COLORS: Record<FunnelStage, { bg: string; text: string }> = {
  NEW: { bg: '#E3F2FD', text: '#1565C0' },
  ASSIGNED: { bg: '#FFF3E0', text: '#E65100' },
  APPOINTMENT_SET: { bg: '#FFF8E1', text: '#F57F17' },
  COMPLETED: { bg: '#E8F5E9', text: '#2E7D32' },
  REGULAR: { bg: '#E8F5E9', text: '#2E7D32' },
  REFUSED: { bg: '#FFEBEE', text: '#C62828' },
  TRANSFERRED: { bg: '#FFF3E0', text: '#E65100' },
};

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('ru-RU', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });
}

function getInitials(firstName: string, lastName: string): string {
  return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
}

export function FunnelCard({ entry, onPress }: FunnelCardProps): React.JSX.Element {
  const styles = createStyles();
  const stageColor = STAGE_COLORS[entry.stage];
  const stageLabel = STAGE_LABELS[entry.stage];
  const clientName = `${entry.client.lastName} ${entry.client.firstName}`;
  const trainerName = entry.trainer?.firstName && entry.trainer?.lastName
    ? `${entry.trainer.firstName} ${entry.trainer.lastName}`
    : entry.trainerFirstName && entry.trainerLastName
      ? `${entry.trainerFirstName} ${entry.trainerLastName}`
      : null;

  return (
    <TouchableOpacity
      style={styles.container}
      onPress={() => onPress(entry)}
      activeOpacity={0.7}
    >
      <View style={styles.row}>
        <View style={styles.avatar}>
          <Text style={styles.avatarText}>
            {getInitials(entry.client.firstName, entry.client.lastName)}
          </Text>
        </View>

        <View style={styles.info}>
          <Text style={styles.name} numberOfLines={1}>
            {clientName}
          </Text>
          <Text style={styles.phone}>{entry.client.phone}</Text>
          {trainerName && (
            <Text style={styles.trainer} numberOfLines={1}>
              {trainerName}
            </Text>
          )}
        </View>

        <View style={styles.rightColumn}>
          <View style={[styles.badge, { backgroundColor: stageColor.bg }]}>
            <Text style={[styles.badgeText, { color: stageColor.text }]}>
              {stageLabel}
            </Text>
          </View>
          <Text style={styles.date}>{formatDate(entry.updatedAt)}</Text>
        </View>
      </View>
    </TouchableOpacity>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    backgroundColor: colors.card,
    borderRadius: 12,
    padding: spacing.lg,
    marginBottom: spacing.md,
    shadowColor: colors.black,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.08,
    shadowRadius: 8,
    elevation: 3,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  avatarText: {
    ...typography.bodySmall,
    fontWeight: '700',
    color: colors.white,
  },
  info: {
    flex: 1,
    marginRight: spacing.sm,
  },
  name: {
    ...typography.body,
    fontWeight: '600',
    color: colors.text,
  },
  phone: {
    ...typography.caption,
    color: colors.textSecondary,
    marginTop: 2,
  },
  trainer: {
    ...typography.caption,
    color: colors.textMuted,
    marginTop: 2,
  },
  rightColumn: {
    alignItems: 'flex-end',
  },
  badge: {
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    borderRadius: 8,
    marginBottom: spacing.xs,
  },
  badgeText: {
    ...typography.caption,
    fontWeight: '600',
  },
  date: {
    ...typography.caption,
    color: colors.textMuted,
  },
});
