import React, { useCallback, useEffect, useState } from 'react';
import {
  View, Text, FlatList, StyleSheet,
  ActivityIndicator, RefreshControl, Linking,
} from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card } from '../../components/ui';
import { api } from '../../services/api';

interface Membership {
  name: string;
  endDate: string;
  isActive: boolean;
}

interface SleepingClient {
  id: string;
  firstName: string;
  lastName: string;
  phone: string;
  email?: string;
  lastActivityAt: string;
  assignedTrainer: { id: string; firstName: string; lastName: string };
  memberships: Membership[];
}

interface SleepingClientsResponse {
  data: SleepingClient[];
  nextCursor: string | null;
  hasMore: boolean;
}

function calcDaysInactive(lastActivityAt: string): number {
  const last = new Date(lastActivityAt).getTime();
  return Math.floor((Date.now() - last) / (1000 * 60 * 60 * 24));
}

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

function pluralizeDays(count: number): string {
  const mod10 = count % 10;
  const mod100 = count % 100;
  if (mod100 >= 11 && mod100 <= 19) return `${count} дней`;
  if (mod10 === 1) return `${count} день`;
  if (mod10 >= 2 && mod10 <= 4) return `${count} дня`;
  return `${count} дней`;
}

const PAGE_LIMIT = 20;

export function SleepingClientsScreen(): React.JSX.Element {
  const styles = createStyles();
  const [clients, setClients] = useState<SleepingClient[]>([]);
  const [cursor, setCursor] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  const fetchClients = useCallback(async (nextCursor?: string) => {
    const params: Record<string, string | number> = { limit: PAGE_LIMIT };
    if (nextCursor) params.cursor = nextCursor;
    return api.get<SleepingClientsResponse>('/clients/sleeping', { params });
  }, []);

  const applyResponse = (response: SleepingClientsResponse) => {
    setCursor(response.nextCursor);
    setHasMore(response.hasMore);
  };

  const loadInitial = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await fetchClients();
      setClients(response.data);
      applyResponse(response);
    } catch {
      setClients([]);
      setCursor(null);
      setHasMore(false);
    } finally {
      setIsLoading(false);
    }
  }, [fetchClients]);

  useEffect(() => {
    loadInitial();
  }, [loadInitial]);

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    try {
      const response = await fetchClients();
      setClients(response.data);
      applyResponse(response);
    } catch {
      // Keep existing data on refresh failure
    } finally {
      setIsRefreshing(false);
    }
  }, [fetchClients]);

  const handleLoadMore = useCallback(async () => {
    if (!hasMore || isLoadingMore || !cursor) return;
    setIsLoadingMore(true);
    try {
      const response = await fetchClients(cursor);
      setClients((prev) => [...prev, ...response.data]);
      applyResponse(response);
    } catch {
      // User can scroll again to retry
    } finally {
      setIsLoadingMore(false);
    }
  }, [hasMore, isLoadingMore, cursor, fetchClients]);

  const handlePhonePress = useCallback((phone: string) => {
    Linking.openURL(`tel:${phone}`);
  }, []);

  const renderItem = useCallback(
    ({ item }: { item: SleepingClient }) => {
      const daysInactive = calcDaysInactive(item.lastActivityAt);
      const activeMembership = item.memberships.find((m) => m.isActive);

      return (
        <Card style={styles.card}>
          <View style={styles.cardHeader}>
            <Text style={styles.clientName} numberOfLines={1}>
              {item.lastName} {item.firstName}
            </Text>
            <View style={styles.daysInactiveBadge}>
              <Text style={styles.daysInactiveText}>
                {pluralizeDays(daysInactive)}
              </Text>
            </View>
          </View>
          <Text
            style={styles.phoneText}
            onPress={() => handlePhonePress(item.phone)}
          >
            {item.phone}
          </Text>
          <View style={styles.detailRow}>
            <Text style={styles.detailLabel}>Последняя активность:</Text>
            <Text style={styles.detailValue}>
              {formatDate(item.lastActivityAt)}
            </Text>
          </View>
          {activeMembership && (
            <View style={styles.membershipBadge}>
              <Text style={styles.membershipText}>
                {activeMembership.name}
              </Text>
            </View>
          )}
        </Card>
      );
    },
    [handlePhonePress],
  );

  const renderFooter = useCallback(() => {
    if (!isLoadingMore) return null;
    return (
      <View style={styles.footer}>
        <ActivityIndicator size="small" color={colors.primary} />
      </View>
    );
  }, [isLoadingMore]);

  const renderEmpty = useCallback(() => {
    if (isLoading) return null;
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyTitle}>Нет спящих клиентов</Text>
        <Text style={styles.emptySubtitle}>
          Клиенты без активности более 30 дней появятся здесь
        </Text>
      </View>
    );
  }, [isLoading]);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Спящие клиенты</Text>
      {isLoading && clients.length === 0 ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <FlatList
          data={clients}
          keyExtractor={(item) => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.listContent}
          ListEmptyComponent={renderEmpty}
          ListFooterComponent={renderFooter}
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.3}
          refreshControl={
            <RefreshControl
              refreshing={isRefreshing}
              onRefresh={handleRefresh}
              colors={[colors.primary]}
              tintColor={colors.primary}
            />
          }
        />
      )}
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  title: {
    ...typography.h2,
    color: colors.text,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.md,
  },
  listContent: { padding: spacing.lg, paddingTop: spacing.sm, flexGrow: 1 },
  loadingContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  card: { marginBottom: spacing.md },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.sm,
  },
  clientName: {
    ...typography.subtitle,
    color: colors.text,
    flex: 1,
    marginRight: spacing.sm,
  },
  daysInactiveBadge: {
    backgroundColor: colors.error,
    borderRadius: 12,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
  },
  daysInactiveText: { ...typography.caption, fontWeight: '700', color: colors.white },
  phoneText: { ...typography.bodySmall, color: colors.textSecondary, marginBottom: spacing.sm },
  detailRow: { flexDirection: 'row', alignItems: 'center', marginBottom: spacing.sm },
  detailLabel: { ...typography.caption, color: colors.textMuted, marginRight: spacing.xs },
  detailValue: { ...typography.caption, color: colors.textMuted },
  membershipBadge: {
    alignSelf: 'flex-start',
    backgroundColor: colors.background,
    borderRadius: 8,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
    marginTop: spacing.xs,
  },
  membershipText: { ...typography.caption, fontWeight: '600', color: colors.primary },
  emptyContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: spacing.xxxl * 2,
    paddingHorizontal: spacing.xl,
  },
  emptyTitle: { ...typography.subtitle, color: colors.textSecondary, marginBottom: spacing.sm },
  emptySubtitle: { ...typography.body, color: colors.textMuted, textAlign: 'center' },
  footer: { paddingVertical: spacing.lg, alignItems: 'center' },
});
