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

const { width } = Dimensions.get('window');

interface PropertyDetailScreenProps {
  route: {
    params: {
      property: Property;
    };
  };
}

export default function PropertyDetailScreen({ route }: PropertyDetailScreenProps) {
  const { property } = route.params;
  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  const formatPrice = (price: string) => {
    const numPrice = parseFloat(price);
    return `$${numPrice.toLocaleString()}`;
  };

  const handleCall = () => {
    Linking.openURL('tel:+252612345678');
  };

  const handleWhatsApp = () => {
    const message = `Hi, I'm interested in the property: ${property.title}`;
    const url = `whatsapp://send?phone=252612345678&text=${encodeURIComponent(message)}`;
    Linking.openURL(url).catch(() => {
      Alert.alert('Error', 'WhatsApp is not installed on this device');
    });
  };

  const handleEmail = () => {
    const subject = `Inquiry about ${property.title}`;
    const body = `Hi,\n\nI'm interested in the property: ${property.title}\n\nLocation: ${property.location}\nPrice: ${formatPrice(property.price)}\n\nPlease provide more details.\n\nThank you.`;
    const url = `mailto:support@kiroservices.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    Linking.openURL(url);
  };

  const getPropertyTypeColor = (type: string) => {
    return type === 'buy' ? '#0091B9' : '#FF6500';
  };

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
      {/* Image Gallery */}
      <View style={styles.imageContainer}>
        <ScrollView
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={(event) => {
            const index = Math.round(event.nativeEvent.contentOffset.x / width);
            setCurrentImageIndex(index);
          }}
        >
          {property.images && property.images.length > 0 ? (
            property.images.map((image, index) => (
              <Image
                key={index}
                source={{ uri: image }}
                style={styles.propertyImage}
                resizeMode="cover"
              />
            ))
          ) : (
            <Image
              source={{
                uri: 'https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&h=600'
              }}
              style={styles.propertyImage}
              resizeMode="cover"
            />
          )}
        </ScrollView>

        {/* Image Indicators */}
        {property.images && property.images.length > 1 && (
          <View style={styles.imageIndicators}>
            {property.images.map((_, index) => (
              <View
                key={index}
                style={[
                  styles.indicator,
                  index === currentImageIndex && styles.activeIndicator,
                ]}
              />
            ))}
          </View>
        )}

        {/* Property Type Badge */}
        <View style={[styles.typeBadge, { backgroundColor: getPropertyTypeColor(property.type) }]}>
          <Text style={styles.typeBadgeText}>
            {property.type === 'buy' ? 'FOR SALE' : 'FOR RENT'}
          </Text>
        </View>
      </View>

      {/* Property Details */}
      <View style={styles.content}>
        {/* Price and Title */}
        <View style={styles.priceSection}>
          <Text style={styles.price}>
            {formatPrice(property.price)}
            {property.type === 'rent' && <Text style={styles.period}>/month</Text>}
          </Text>
        </View>

        <Text style={styles.title}>{property.title}</Text>

        {/* Location */}
        <View style={styles.locationRow}>
          <Icon name="location" size={20} color="#0091B9" />
          <Text style={styles.location}>{property.location}</Text>
        </View>

        {/* Property Features */}
        {(property.bedrooms || property.bathrooms || property.sqft) && (
          <View style={styles.featuresContainer}>
            {property.bedrooms && (
              <View style={styles.feature}>
                <Icon name="bed" size={18} color="#0091B9" />
                <Text style={styles.featureText}>
                  {property.bedrooms} Bedroom{property.bedrooms > 1 ? 's' : ''}
                </Text>
              </View>
            )}
            {property.bathrooms && (
              <View style={styles.feature}>
                <Icon name="water" size={18} color="#0091B9" />
                <Text style={styles.featureText}>
                  {property.bathrooms} Bathroom{property.bathrooms > 1 ? 's' : ''}
                </Text>
              </View>
            )}
            {property.sqft && (
              <View style={styles.feature}>
                <Icon name="expand" size={18} color="#0091B9" />
                <Text style={styles.featureText}>{property.sqft} sqft</Text>
              </View>
            )}
          </View>
        )}

        {/* Property Type */}
        <View style={styles.propertyTypeRow}>
          <Icon name="business" size={18} color="#004F9B" />
          <Text style={styles.propertyType}>
            {property.propertyType.charAt(0).toUpperCase() + property.propertyType.slice(1)}
          </Text>
        </View>

        {/* Description */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Description</Text>
          <Text style={styles.description}>{property.description}</Text>
        </View>

        {/* Property Features List */}
        {property.features && property.features.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Features & Amenities</Text>
            <View style={styles.featuresList}>
              {property.features.map((feature, index) => (
                <View key={index} style={styles.featureItem}>
                  <Icon name="checkmark-circle" size={16} color="#0091B9" />
                  <Text style={styles.featureItemText}>{feature}</Text>
                </View>
              ))}
            </View>
          </View>
        )}

        {/* Contact Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Contact Property Owner</Text>
          <Text style={styles.contactSubtitle}>
            Interested in this property? Get in touch with us!
          </Text>
          
          <View style={styles.contactButtons}>
            <TouchableOpacity style={[styles.contactButton, styles.callButton]} onPress={handleCall}>
              <Icon name="call" size={20} color="#fff" />
              <Text style={styles.contactButtonText}>Call Now</Text>
            </TouchableOpacity>
            
            <TouchableOpacity style={[styles.contactButton, styles.whatsappButton]} onPress={handleWhatsApp}>
              <Icon name="logo-whatsapp" size={20} color="#fff" />
              <Text style={styles.contactButtonText}>WhatsApp</Text>
            </TouchableOpacity>
            
            <TouchableOpacity style={[styles.contactButton, styles.emailButton]} onPress={handleEmail}>
              <Icon name="mail" size={20} color="#fff" />
              <Text style={styles.contactButtonText}>Email</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Property Information */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Property Information</Text>
          <View style={styles.infoGrid}>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Property ID</Text>
              <Text style={styles.infoValue}>#{property.id.slice(-8).toUpperCase()}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Status</Text>
              <Text style={[styles.infoValue, { color: property.isActive ? '#0091B9' : '#666' }]}>
                {property.isActive ? 'Available' : 'Not Available'}
              </Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Type</Text>
              <Text style={styles.infoValue}>For {property.type === 'buy' ? 'Sale' : 'Rent'}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Category</Text>
              <Text style={styles.infoValue}>
                {property.propertyType.charAt(0).toUpperCase() + property.propertyType.slice(1)}
              </Text>
            </View>
          </View>
        </View>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  imageContainer: {
    position: 'relative',
    height: 300,
  },
  propertyImage: {
    width: width,
    height: 300,
  },
  imageIndicators: {
    position: 'absolute',
    bottom: 15,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 8,
  },
  indicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
  activeIndicator: {
    backgroundColor: '#fff',
  },
  typeBadge: {
    position: 'absolute',
    top: 15,
    left: 15,
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 6,
  },
  typeBadgeText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: 'bold',
  },
  content: {
    padding: 20,
  },
  priceSection: {
    marginBottom: 10,
  },
  price: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#004F9B',
  },
  period: {
    fontSize: 18,
    fontWeight: 'normal',
    color: '#666',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#004F9B',
    marginBottom: 15,
    lineHeight: 32,
  },
  locationRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  location: {
    fontSize: 16,
    color: '#666',
    marginLeft: 8,
    flex: 1,
  },
  featuresContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 15,
    marginBottom: 20,
  },
  feature: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
  },
  featureText: {
    fontSize: 14,
    color: '#0091B9',
    marginLeft: 8,
    fontWeight: '500',
  },
  propertyTypeRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 25,
  },
  propertyType: {
    fontSize: 16,
    color: '#004F9B',
    marginLeft: 8,
    fontWeight: '500',
  },
  section: {
    marginBottom: 25,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#004F9B',
    marginBottom: 12,
  },
  description: {
    fontSize: 16,
    color: '#333',
    lineHeight: 24,
  },
  featuresList: {
    gap: 10,
  },
  featureItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  featureItemText: {
    fontSize: 16,
    color: '#333',
    marginLeft: 10,
  },
  contactSubtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 20,
  },
  contactButtons: {
    flexDirection: 'row',
    gap: 10,
  },
  contactButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 8,
    gap: 8,
  },
  callButton: {
    backgroundColor: '#0091B9',
  },
  whatsappButton: {
    backgroundColor: '#25D366',
  },
  emailButton: {
    backgroundColor: '#FF6500',
  },
  contactButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
  },
  infoGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 15,
  },
  infoItem: {
    flex: 1,
    minWidth: '45%',
    backgroundColor: '#f8f9fa',
    padding: 15,
    borderRadius: 8,
  },
  infoLabel: {
    fontSize: 12,
    color: '#666',
    marginBottom: 5,
    textTransform: 'uppercase',
    fontWeight: '500',
  },
  infoValue: {
    fontSize: 16,
    color: '#004F9B',
    fontWeight: '600',
  },
});