import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  Image,
  Linking,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { MovingService } from '../types';
import { apiService } from '../services/apiService';

export default function MovingServicesScreen() {
  const [services, setServices] = useState<MovingService[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');

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

  const loadServices = async () => {
    try {
      setLoading(true);
      const data = await apiService.getMovingServices();
      setServices(data);
    } catch (error) {
      console.error('Failed to load moving services:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredServices = selectedCategory === 'all' 
    ? services 
    : services.filter(service => service.category === selectedCategory);

  const handleCall = (phone: string) => {
    Linking.openURL(`tel:${phone}`);
  };

  const handleWhatsApp = (phone: string, serviceName: string) => {
    const message = `Hi, I'm interested in your moving service: ${serviceName}`;
    const url = `whatsapp://send?phone=${phone.replace(/\D/g, '')}&text=${encodeURIComponent(message)}`;
    Linking.openURL(url).catch(() => {
      Alert.alert('Error', 'WhatsApp is not installed on this device');
    });
  };

  const handleEmail = (email: string, serviceName: string) => {
    const subject = `Inquiry about ${serviceName}`;
    const body = `Hi,\n\nI'm interested in your moving service: ${serviceName}\n\nPlease provide more details about your services and pricing.\n\nThank you.`;
    const url = `mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    Linking.openURL(url);
  };

  const getCategoryColor = (category: string) => {
    const colors = {
      residential: '#0091B9',
      commercial: '#004F9B',
      packing: '#FF6500',
      storage: '#FFD500',
    };
    return colors[category as keyof typeof colors] || '#666';
  };

  const getCategoryIcon = (category: string) => {
    const icons = {
      residential: 'home',
      commercial: 'business',
      packing: 'cube',
      storage: 'archive',
    };
    return icons[category as keyof typeof icons] || 'car';
  };

  const CategoryFilter = ({ category, title, isActive, onPress }: any) => (
    <TouchableOpacity
      style={[styles.categoryButton, isActive && styles.activeCategoryButton]}
      onPress={onPress}
    >
      <Icon 
        name={getCategoryIcon(category)} 
        size={16} 
        color={isActive ? '#fff' : getCategoryColor(category)} 
      />
      <Text style={[
        styles.categoryButtonText, 
        isActive && styles.activeCategoryButtonText
      ]}>
        {title}
      </Text>
    </TouchableOpacity>
  );

  const ServiceCard = ({ service }: { service: MovingService }) => (
    <View style={styles.serviceCard}>
      {/* Service Image */}
      <View style={styles.serviceImageContainer}>
        <Image
          source={{
            uri: service.images && service.images.length > 0
              ? service.images[0]
              : 'https://images.unsplash.com/photo-1586796676456-a4af9fd8cc45?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&h=400'
          }}
          style={styles.serviceImage}
          resizeMode="cover"
        />
        <View style={[styles.categoryBadge, { backgroundColor: getCategoryColor(service.category) }]}>
          <Icon name={getCategoryIcon(service.category)} size={12} color="#fff" />
          <Text style={styles.categoryBadgeText}>
            {service.category.toUpperCase()}
          </Text>
        </View>
      </View>

      {/* Service Details */}
      <View style={styles.serviceContent}>
        <Text style={styles.serviceName}>{service.name}</Text>
        
        <View style={styles.locationRow}>
          <Icon name="location-outline" size={14} color="#666" />
          <Text style={styles.serviceLocation}>{service.location}</Text>
        </View>

        <Text style={styles.serviceDescription} numberOfLines={2}>
          {service.description}
        </Text>

        {/* Price */}
        <Text style={styles.servicePrice}>
          Starting from ${parseFloat(service.price).toLocaleString()}
        </Text>

        {/* Rating */}
        {service.rating && (
          <View style={styles.ratingRow}>
            <View style={styles.stars}>
              {[1, 2, 3, 4, 5].map((star) => (
                <Icon
                  key={star}
                  name={star <= service.rating! ? 'star' : 'star-outline'}
                  size={14}
                  color="#FFD500"
                />
              ))}
            </View>
            <Text style={styles.ratingText}>({service.rating}/5)</Text>
          </View>
        )}

        {/* Features */}
        {service.features && service.features.length > 0 && (
          <View style={styles.featuresContainer}>
            {service.features.slice(0, 3).map((feature, index) => (
              <View key={index} style={styles.featureTag}>
                <Text style={styles.featureText}>{feature}</Text>
              </View>
            ))}
          </View>
        )}

        {/* Contact Buttons */}
        <View style={styles.contactButtons}>
          <TouchableOpacity
            style={[styles.contactButton, styles.callButton]}
            onPress={() => handleCall(service.phone)}
          >
            <Icon name="call" size={16} color="#fff" />
            <Text style={styles.contactButtonText}>Call</Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            style={[styles.contactButton, styles.whatsappButton]}
            onPress={() => handleWhatsApp(service.phone, service.name)}
          >
            <Icon name="logo-whatsapp" size={16} color="#fff" />
            <Text style={styles.contactButtonText}>WhatsApp</Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            style={[styles.contactButton, styles.emailButton]}
            onPress={() => handleEmail(service.email, service.name)}
          >
            <Icon name="mail" size={16} color="#fff" />
            <Text style={styles.contactButtonText}>Email</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Moving Services</Text>
        <Text style={styles.headerSubtitle}>
          Professional moving and relocation services in Mogadishu
        </Text>
      </View>

      {/* Category Filter */}
      <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.categoriesContainer}>
        <View style={styles.categories}>
          <CategoryFilter
            category="all"
            title="All Services"
            isActive={selectedCategory === 'all'}
            onPress={() => setSelectedCategory('all')}
          />
          <CategoryFilter
            category="residential"
            title="Residential"
            isActive={selectedCategory === 'residential'}
            onPress={() => setSelectedCategory('residential')}
          />
          <CategoryFilter
            category="commercial"
            title="Commercial"
            isActive={selectedCategory === 'commercial'}
            onPress={() => setSelectedCategory('commercial')}
          />
          <CategoryFilter
            category="packing"
            title="Packing"
            isActive={selectedCategory === 'packing'}
            onPress={() => setSelectedCategory('packing')}
          />
          <CategoryFilter
            category="storage"
            title="Storage"
            isActive={selectedCategory === 'storage'}
            onPress={() => setSelectedCategory('storage')}
          />
        </View>
      </ScrollView>

      {/* Services List */}
      <ScrollView 
        style={styles.servicesContainer} 
        showsVerticalScrollIndicator={false}
        refreshing={loading}
        onRefresh={loadServices}
      >
        {filteredServices.length > 0 ? (
          filteredServices.map((service) => (
            <ServiceCard key={service.id} service={service} />
          ))
        ) : (
          <View style={styles.emptyState}>
            <Icon name="car-outline" size={60} color="#ccc" />
            <Text style={styles.emptyStateText}>
              {loading ? 'Loading moving services...' : 'No services found'}
            </Text>
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  header: {
    backgroundColor: '#0091B9',
    paddingHorizontal: 20,
    paddingVertical: 20,
    borderBottomLeftRadius: 20,
    borderBottomRightRadius: 20,
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 5,
  },
  headerSubtitle: {
    fontSize: 14,
    color: '#BAF4F0',
    lineHeight: 20,
  },
  categoriesContainer: {
    backgroundColor: '#fff',
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  categories: {
    flexDirection: 'row',
    paddingHorizontal: 15,
    gap: 10,
  },
  categoryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: '#e0e0e0',
    backgroundColor: '#fff',
    gap: 6,
  },
  activeCategoryButton: {
    backgroundColor: '#0091B9',
    borderColor: '#0091B9',
  },
  categoryButtonText: {
    fontSize: 14,
    color: '#666',
    fontWeight: '500',
  },
  activeCategoryButtonText: {
    color: '#fff',
  },
  servicesContainer: {
    flex: 1,
    padding: 15,
  },
  serviceCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    marginBottom: 15,
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    overflow: 'hidden',
  },
  serviceImageContainer: {
    position: 'relative',
    height: 150,
  },
  serviceImage: {
    width: '100%',
    height: '100%',
  },
  categoryBadge: {
    position: 'absolute',
    top: 10,
    left: 10,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
    gap: 4,
  },
  categoryBadgeText: {
    color: '#fff',
    fontSize: 10,
    fontWeight: 'bold',
  },
  serviceContent: {
    padding: 15,
  },
  serviceName: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#004F9B',
    marginBottom: 8,
  },
  locationRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  serviceLocation: {
    fontSize: 14,
    color: '#666',
    marginLeft: 4,
  },
  serviceDescription: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
    marginBottom: 12,
  },
  servicePrice: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#0091B9',
    marginBottom: 8,
  },
  ratingRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  stars: {
    flexDirection: 'row',
    marginRight: 8,
  },
  ratingText: {
    fontSize: 12,
    color: '#666',
  },
  featuresContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 6,
    marginBottom: 15,
  },
  featureTag: {
    backgroundColor: '#BAF4F0',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
  },
  featureText: {
    fontSize: 12,
    color: '#0091B9',
    fontWeight: '500',
  },
  contactButtons: {
    flexDirection: 'row',
    gap: 8,
  },
  contactButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 10,
    borderRadius: 6,
    gap: 6,
  },
  callButton: {
    backgroundColor: '#0091B9',
  },
  whatsappButton: {
    backgroundColor: '#25D366',
  },
  emailButton: {
    backgroundColor: '#FF6500',
  },
  contactButtonText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '600',
  },
  emptyState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 50,
  },
  emptyStateText: {
    fontSize: 16,
    color: '#666',
    marginTop: 15,
    textAlign: 'center',
  },
});