import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  ActivityIndicator,
  TouchableOpacity,
  Linking,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card } from '../../components/ui';
import { clientsService } from '../../services/clients';
import type { Client } from '../../types/client';
import type { ClientsStackParamList } from './types';

type Props = NativeStackScreenProps<ClientsStackParamList, 'ClientDetail'>;

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

export function ClientDetailScreen({ route }: Props): React.JSX.Element {
  const styles = createStyles();
  const { clientId } = route.params;
  const [client, setClient] = useState<Client | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    clientsService
      .getClient(clientId)
      .then(setClient)
      .catch(() => setClient(null))
      .finally(() => setIsLoading(false));
  }, [clientId]);

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

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  if (!client) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={styles.errorText}>Клиент не найден</Text>
      </View>
    );
  }

  const initials = `${client.firstName[0] || ''}${client.lastName[0] || ''}`;

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <View style={styles.avatarSection}>
        <View style={styles.avatar}>
          <Text style={styles.avatarText}>{initials}</Text>
        </View>
        <Text style={styles.clientName}>
          {client.lastName} {client.firstName}
          {client.patronymic ? ` ${client.patronymic}` : ''}
        </Text>
      </View>

      <Card style={styles.card}>
        <Text style={styles.sectionTitle}>Контакты</Text>
        <TouchableOpacity onPress={() => handlePhonePress(client.phone)}>
          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Телефон</Text>
            <Text style={styles.phoneValue}>{client.phone}</Text>
          </View>
        </TouchableOpacity>
        {client.email && (
          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Email</Text>
            <Text style={styles.infoValue}>{client.email}</Text>
          </View>
        )}
        {client.birthDate && (
          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Дата рождения</Text>
            <Text style={styles.infoValue}>{formatDate(client.birthDate)}</Text>
          </View>
        )}
      </Card>

      <Card style={styles.card}>
        <Text style={styles.sectionTitle}>Активность</Text>
        <View style={styles.infoRow}>
          <Text style={styles.infoLabel}>Последняя активность</Text>
          <Text style={styles.infoValue}>{formatDate(client.lastActivityAt)}</Text>
        </View>
      </Card>

      {client.notes && (
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Заметки</Text>
          <Text style={styles.notesText}>{client.notes}</Text>
        </Card>
      )}
    </ScrollView>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: { flex: 1, backgroundColor: colors.background },
    content: { padding: spacing.lg },
    loadingContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' },
    errorText: { ...typography.body, color: colors.textMuted },
    avatarSection: { alignItems: 'center', marginBottom: spacing.xl },
    avatar: {
      width: 80,
      height: 80,
      borderRadius: 40,
      backgroundColor: colors.primaryLight,
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: spacing.md,
    },
    avatarText: { ...typography.h2, color: colors.white, fontWeight: '700' },
    clientName: { ...typography.h2, color: colors.text, textAlign: 'center' },
    card: { marginBottom: spacing.md },
    sectionTitle: {
      ...typography.subtitle,
      color: colors.text,
      marginBottom: spacing.md,
    },
    infoRow: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      paddingVertical: spacing.sm,
      borderBottomWidth: 1,
      borderBottomColor: colors.border,
    },
    infoLabel: { ...typography.bodySmall, color: colors.textSecondary },
    infoValue: { ...typography.bodySmall, color: colors.text, fontWeight: '500' },
    phoneValue: { ...typography.bodySmall, color: colors.primary, fontWeight: '500' },
    notesText: { ...typography.body, color: colors.textSecondary },
  });
