/**
 * Products Screen
 *
 * Product catalog list
 */

import { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { productsApi } from '@/services/api';
import { Product } from '@/types';

export default function ProductsScreen() {
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const fetchProducts = async () => {
    try {
      const params: any = { limit: 50 };
      if (searchQuery) params.search = searchQuery;

      const response = await productsApi.list(params);
      setProducts(response.data || []);
    } catch (error) {
      console.error('Error fetching products:', error);
      // Use mock data for demo
      setProducts([
        { id: '1', code: 'PROD-001', name: 'Laptop HP ProBook', productType: 'product', unitPrice: 15999.00, costPrice: 12000.00, isActive: true, categoryName: 'Electrónica' },
        { id: '2', code: 'PROD-002', name: 'Monitor Dell 24"', productType: 'product', unitPrice: 4599.00, costPrice: 3500.00, isActive: true, categoryName: 'Electrónica' },
        { id: '3', code: 'SERV-001', name: 'Soporte Técnico', productType: 'service', unitPrice: 500.00, costPrice: 0, isActive: true, categoryName: 'Servicios' },
        { id: '4', code: 'PROD-003', name: 'Teclado Mecánico', productType: 'product', unitPrice: 1299.00, costPrice: 850.00, isActive: true, categoryName: 'Accesorios' },
      ]);
    } finally {
      setIsLoading(false);
      setRefreshing(false);
    }
  };

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

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (!isLoading) fetchProducts();
    }, 500);
    return () => clearTimeout(timeoutId);
  }, [searchQuery]);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchProducts();
  }, [searchQuery]);

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('es-MX', {
      style: 'currency',
      currency: 'MXN',
    }).format(amount);
  };

  const renderProduct = ({ item }: { item: Product }) => (
    <TouchableOpacity style={styles.productCard}>
      <View style={styles.productIcon}>
        <Ionicons
          name={item.productType === 'service' ? 'construct-outline' : 'cube-outline'}
          size={24}
          color="#1e40af"
        />
      </View>
      <View style={styles.productInfo}>
        <Text style={styles.productCode}>{item.code}</Text>
        <Text style={styles.productName}>{item.name}</Text>
        {item.categoryName && (
          <Text style={styles.productCategory}>{item.categoryName}</Text>
        )}
      </View>
      <View style={styles.productPrice}>
        <Text style={styles.priceAmount}>{formatCurrency(item.unitPrice)}</Text>
        <Text style={styles.priceLabel}>Precio</Text>
      </View>
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>
      {/* Search */}
      <View style={styles.searchContainer}>
        <Ionicons name="search" size={20} color="#9ca3af" style={styles.searchIcon} />
        <TextInput
          style={styles.searchInput}
          placeholder="Buscar productos..."
          placeholderTextColor="#9ca3af"
          value={searchQuery}
          onChangeText={setSearchQuery}
        />
      </View>

      {/* List */}
      {isLoading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#1e40af" />
        </View>
      ) : (
        <FlatList
          data={products}
          renderItem={renderProduct}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.listContent}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor="#1e40af" />
          }
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Ionicons name="cube-outline" size={48} color="#d1d5db" />
              <Text style={styles.emptyText}>No se encontraron productos</Text>
            </View>
          }
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8fafc',
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#ffffff',
    margin: 16,
    borderRadius: 10,
    paddingHorizontal: 12,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    paddingVertical: 12,
    fontSize: 16,
    color: '#1f2937',
  },
  listContent: {
    padding: 16,
    paddingTop: 0,
  },
  productCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  productIcon: {
    width: 48,
    height: 48,
    borderRadius: 10,
    backgroundColor: '#eff6ff',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  productInfo: {
    flex: 1,
  },
  productCode: {
    fontSize: 12,
    color: '#64748b',
    fontWeight: '500',
  },
  productName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1f2937',
    marginTop: 2,
  },
  productCategory: {
    fontSize: 13,
    color: '#9ca3af',
    marginTop: 2,
  },
  productPrice: {
    alignItems: 'flex-end',
  },
  priceAmount: {
    fontSize: 16,
    fontWeight: '700',
    color: '#1e40af',
  },
  priceLabel: {
    fontSize: 12,
    color: '#9ca3af',
    marginTop: 2,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyContainer: {
    alignItems: 'center',
    paddingVertical: 48,
  },
  emptyText: {
    fontSize: 16,
    color: '#9ca3af',
    marginTop: 12,
  },
});
