import React, { useCallback, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  Alert,
  FlatList,
  Modal,
  Pressable,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card, Button, Input } from '../../components/ui';
import { useSalesStore } from '../../stores/sales.store';
import { clientsService } from '../../services/clients';
import type { Client } from '../../types/client';
import type { CreateSaleDto } from '../../types/sale';

export function CreateSaleScreen(): React.JSX.Element {
  const styles = createStyles();
  const navigation = useNavigation();
  const { createSale, isSubmitting } = useSalesStore();

  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [clientSearch, setClientSearch] = useState('');
  const [clientResults, setClientResults] = useState<Client[]>([]);
  const [showClientSearch, setShowClientSearch] = useState(false);
  const [isSearching, setIsSearching] = useState(false);

  const [amount, setAmount] = useState('');
  const [description, setDescription] = useState('');

  const handleClientSearch = useCallback(async (query: string) => {
    setClientSearch(query);
    if (query.length < 2) {
      setClientResults([]);
      return;
    }
    setIsSearching(true);
    try {
      const results = await clientsService.searchClients(query);
      setClientResults(results);
    } catch {
      setClientResults([]);
    } finally {
      setIsSearching(false);
    }
  }, []);

  const handleSelectClient = useCallback((client: Client) => {
    setSelectedClient(client);
    setShowClientSearch(false);
    setClientSearch('');
    setClientResults([]);
  }, []);

  const handleAmountChange = useCallback((text: string) => {
    const cleaned = text.replace(/[^0-9.,]/g, '').replace(',', '.');
    setAmount(cleaned);
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!selectedClient) {
      Alert.alert('Ошибка', 'Выберите клиента');
      return;
    }

    const parsedAmount = parseFloat(amount);
    if (!amount || isNaN(parsedAmount) || parsedAmount <= 0) {
      Alert.alert('Ошибка', 'Введите корректную сумму');
      return;
    }

    const dto: CreateSaleDto = {
      clientId: selectedClient.id,
      amount: parsedAmount,
      description: description.trim() || undefined,
    };

    try {
      await createSale(dto);
      Alert.alert('Готово', 'Продажа создана', [
        { text: 'OK', onPress: () => navigation.goBack() },
      ]);
    } catch {
      Alert.alert('Ошибка', 'Не удалось создать продажу');
    }
  }, [selectedClient, amount, description, createSale, navigation]);

  const renderClientItem = useCallback(
    ({ item }: { item: Client }) => (
      <TouchableOpacity
        style={styles.searchResultItem}
        onPress={() => handleSelectClient(item)}
        activeOpacity={0.7}
      >
        <View style={styles.searchResultAvatar}>
          <Text style={styles.searchResultAvatarText}>
            {item.firstName[0]}
            {item.lastName[0]}
          </Text>
        </View>
        <View style={styles.searchResultInfo}>
          <Text style={styles.searchResultName}>
            {item.lastName} {item.firstName}
          </Text>
          <Text style={styles.searchResultPhone}>{item.phone}</Text>
        </View>
      </TouchableOpacity>
    ),
    [handleSelectClient],
  );

  const isValid = selectedClient !== null && amount !== '' && parseFloat(amount) > 0;

  return (
    <View style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        {/* Client selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Клиент</Text>
          {selectedClient ? (
            <View style={styles.selectedRow}>
              <View style={styles.selectedAvatar}>
                <Text style={styles.selectedAvatarText}>
                  {selectedClient.firstName[0]}
                  {selectedClient.lastName[0]}
                </Text>
              </View>
              <View style={styles.selectedInfo}>
                <Text style={styles.selectedName}>
                  {selectedClient.lastName} {selectedClient.firstName}
                </Text>
                <Text style={styles.selectedPhone}>
                  {selectedClient.phone}
                </Text>
              </View>
              <TouchableOpacity
                onPress={() => {
                  setSelectedClient(null);
                  setShowClientSearch(true);
                }}
              >
                <Text style={styles.changeLink}>Изменить</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <TouchableOpacity
              style={styles.selectorButton}
              onPress={() => setShowClientSearch(true)}
              activeOpacity={0.7}
            >
              <Text style={styles.selectorPlaceholder}>Выбрать клиента</Text>
            </TouchableOpacity>
          )}
        </Card>

        {/* Amount */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Сумма</Text>
          <Input
            placeholder="0"
            value={amount}
            onChangeText={handleAmountChange}
            keyboardType="numeric"
          />
          {amount !== '' && parseFloat(amount) > 0 && (
            <Text style={styles.amountPreview}>
              {parseFloat(amount).toLocaleString('ru-RU')} {'\u20BD'}
            </Text>
          )}
        </Card>

        {/* Description */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Описание (опционально)</Text>
          <Input
            placeholder="Комментарий к продаже"
            value={description}
            onChangeText={setDescription}
            multiline
            numberOfLines={3}
          />
        </Card>

        <Button
          title="Создать продажу"
          onPress={handleSubmit}
          loading={isSubmitting}
          disabled={!isValid}
          style={styles.submitButton}
        />
      </ScrollView>

      {/* Client search modal */}
      <Modal
        visible={showClientSearch}
        transparent
        animationType="slide"
        onRequestClose={() => setShowClientSearch(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowClientSearch(false)}
        >
          <Pressable style={styles.searchSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.sheetTitle}>Поиск клиента</Text>
            <Input
              placeholder="Имя или телефон"
              value={clientSearch}
              onChangeText={handleClientSearch}
              autoFocus
            />
            <FlatList
              data={clientResults}
              renderItem={renderClientItem}
              keyExtractor={(item) => item.id}
              style={styles.searchResultsList}
              ListEmptyComponent={
                clientSearch.length >= 2 && !isSearching ? (
                  <Text style={styles.noResults}>Ничего не найдено</Text>
                ) : null
              }
            />
          </Pressable>
        </Pressable>
      </Modal>
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: spacing.lg,
    paddingBottom: spacing.xxxl * 2,
  },
  card: {
    marginBottom: spacing.lg,
  },
  sectionTitle: {
    ...typography.subtitle,
    color: colors.text,
    marginBottom: spacing.md,
  },
  selectorButton: {
    height: 48,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: 12,
    justifyContent: 'center',
    paddingHorizontal: spacing.lg,
    backgroundColor: colors.white,
  },
  selectorPlaceholder: {
    ...typography.body,
    color: colors.textMuted,
  },
  selectedRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectedAvatar: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  selectedAvatarText: {
    ...typography.bodySmall,
    color: colors.white,
    fontWeight: '700',
  },
  selectedInfo: {
    flex: 1,
  },
  selectedName: {
    ...typography.body,
    fontWeight: '600',
    color: colors.text,
  },
  selectedPhone: {
    ...typography.bodySmall,
    color: colors.textSecondary,
    marginTop: 2,
  },
  changeLink: {
    ...typography.bodySmall,
    color: colors.primary,
    fontWeight: '600',
  },
  amountPreview: {
    ...typography.bodySmall,
    color: colors.success,
    marginTop: spacing.sm,
  },
  submitButton: {
    marginTop: spacing.lg,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  searchSheet: {
    backgroundColor: colors.white,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: spacing.xl,
    paddingBottom: spacing.xxxl,
    maxHeight: '80%',
  },
  bottomSheetHandle: {
    width: 40,
    height: 4,
    borderRadius: 2,
    backgroundColor: colors.border,
    alignSelf: 'center',
    marginBottom: spacing.xl,
  },
  sheetTitle: {
    ...typography.h3,
    color: colors.text,
    marginBottom: spacing.lg,
  },
  searchResultsList: {
    maxHeight: 300,
  },
  searchResultItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  searchResultAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  searchResultAvatarText: {
    ...typography.caption,
    color: colors.white,
    fontWeight: '700',
  },
  searchResultInfo: {
    flex: 1,
  },
  searchResultName: {
    ...typography.body,
    fontWeight: '500',
    color: colors.text,
  },
  searchResultPhone: {
    ...typography.caption,
    color: colors.textSecondary,
    marginTop: 2,
  },
  noResults: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    paddingVertical: spacing.xl,
  },
});
