/**
 * Property detail — full listing view, RealScout-style.
 * Photos, details, map, actions.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Image,
  TouchableOpacity,
  Dimensions,
  FlatList,
} from 'react-native';
import { useTheme } from '../../themes/ThemeProvider';
import { getProperty, Property } from '../../services/api';
import { openNavigationApp } from '../../services/location';

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

export default function PropertyDetail({ route }: any) {
  const { theme } = useTheme();
  const { id } = route.params;
  const [property, setProperty] = useState<Property | null>(null);
  const [photoIndex, setPhotoIndex] = useState(0);

  const load = useCallback(async () => {
    const res = await getProperty(id);
    if (res.success && res.data) {
      setProperty(res.data);
    }
  }, [id]);

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

  const formatPrice = (price: number): string => {
    if (price >= 1_000_000) return `$${(price / 1_000_000).toFixed(price % 100_000 === 0 ? 1 : 2)}M`;
    return `$${price.toLocaleString()}`;
  };

  if (!property) {
    return (
      <View style={[styles.loading, { backgroundColor: theme.colors.background }]}>
        <Text style={{ color: theme.colors.textSecondary }}>Loading...</Text>
      </View>
    );
  }

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* Photo Carousel */}
      {property.photos && property.photos.length > 0 ? (
        <View>
          <FlatList
            data={property.photos}
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            keyExtractor={(_, i) => String(i)}
            onMomentumScrollEnd={(e) => {
              setPhotoIndex(Math.round(e.nativeEvent.contentOffset.x / SCREEN_WIDTH));
            }}
            renderItem={({ item }) => (
              <Image source={{ uri: item }} style={styles.photo} />
            )}
          />
          <View style={styles.photoCounter}>
            <Text style={styles.photoCounterText}>
              {photoIndex + 1}/{property.photos.length}
            </Text>
          </View>
        </View>
      ) : (
        <View style={[styles.noPhoto, { backgroundColor: theme.colors.border }]}>
          <Text style={{ color: theme.colors.textSecondary }}>No Photos</Text>
        </View>
      )}

      {/* Price & Address */}
      <View style={[styles.mainInfo, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.price, { color: theme.colors.primary }]}>
          {formatPrice(property.price)}
        </Text>
        <Text style={[styles.address, { color: theme.colors.text }]}>{property.address}</Text>
        <Text style={[styles.cityLine, { color: theme.colors.textSecondary }]}>
          {property.city}, {property.state} {property.zip}
        </Text>

        <View style={styles.statRow}>
          <View style={styles.stat}>
            <Text style={[styles.statValue, { color: theme.colors.text }]}>{property.bedrooms}</Text>
            <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>Beds</Text>
          </View>
          <View style={[styles.statDivider, { backgroundColor: theme.colors.border }]} />
          <View style={styles.stat}>
            <Text style={[styles.statValue, { color: theme.colors.text }]}>{property.bathrooms}</Text>
            <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>Baths</Text>
          </View>
          <View style={[styles.statDivider, { backgroundColor: theme.colors.border }]} />
          <View style={styles.stat}>
            <Text style={[styles.statValue, { color: theme.colors.text }]}>
              {property.sqft?.toLocaleString()}
            </Text>
            <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>SqFt</Text>
          </View>
          {property.lot_size && (
            <>
              <View style={[styles.statDivider, { backgroundColor: theme.colors.border }]} />
              <View style={styles.stat}>
                <Text style={[styles.statValue, { color: theme.colors.text }]}>{property.lot_size}</Text>
                <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>Lot</Text>
              </View>
            </>
          )}
        </View>

        <View style={styles.metaRow}>
          {property.mls_number && (
            <Text style={[styles.metaText, { color: theme.colors.textSecondary }]}>
              MLS# {property.mls_number}
            </Text>
          )}
          <Text style={[styles.metaText, { color: theme.colors.textSecondary }]}>
            {property.property_type}
          </Text>
          <View style={[styles.statusBadge, {
            backgroundColor: property.status === 'active' ? theme.colors.success :
                             property.status === 'pending' ? theme.colors.warning :
                             theme.colors.error,
          }]}>
            <Text style={styles.statusText}>{property.status.toUpperCase()}</Text>
          </View>
        </View>
      </View>

      {/* Description */}
      {property.description && (
        <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Description</Text>
          <Text style={[styles.description, { color: theme.colors.textSecondary }]}>
            {property.description}
          </Text>
        </View>
      )}

      {/* Actions */}
      <View style={styles.actions}>
        {property.latitude && property.longitude && (
          <TouchableOpacity
            style={[styles.actionBtn, { backgroundColor: theme.colors.info }]}
            onPress={() => openNavigationApp({ latitude: property.latitude!, longitude: property.longitude! }, property.address)}
          >
            <Text style={styles.actionBtnText}>Get Directions</Text>
          </TouchableOpacity>
        )}
        <TouchableOpacity
          style={[styles.actionBtn, { backgroundColor: theme.colors.primary }]}
          onPress={() => {}}
        >
          <Text style={styles.actionBtnText}>Schedule Showing</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.actionBtn, { backgroundColor: theme.colors.accent }]}
          onPress={() => {}}
        >
          <Text style={styles.actionBtnText}>Share with Client</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.bottomPad} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  container: { flex: 1 },
  photo: { width: SCREEN_WIDTH, height: 280 },
  photoCounter: {
    position: 'absolute',
    bottom: 12,
    right: 12,
    backgroundColor: 'rgba(0,0,0,0.6)',
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 12,
  },
  photoCounterText: { color: '#FFF', fontSize: 12, fontWeight: '600' },
  noPhoto: { height: 200, justifyContent: 'center', alignItems: 'center' },
  mainInfo: { padding: 20 },
  price: { fontSize: 30, fontWeight: '800', marginBottom: 4 },
  address: { fontSize: 18, fontWeight: '600', marginBottom: 2 },
  cityLine: { fontSize: 15, marginBottom: 16 },
  statRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginBottom: 16 },
  stat: { alignItems: 'center', paddingHorizontal: 16 },
  statValue: { fontSize: 20, fontWeight: '700' },
  statLabel: { fontSize: 12, marginTop: 2 },
  statDivider: { width: 1, height: 32 },
  metaRow: { flexDirection: 'row', alignItems: 'center', gap: 12 },
  metaText: { fontSize: 13 },
  statusBadge: { paddingHorizontal: 10, paddingVertical: 3, borderRadius: 6 },
  statusText: { color: '#FFF', fontSize: 10, fontWeight: '700' },
  section: { marginTop: 8, padding: 20 },
  sectionTitle: { fontSize: 17, fontWeight: '700', marginBottom: 8 },
  description: { fontSize: 14, lineHeight: 22 },
  actions: { padding: 16, gap: 10 },
  actionBtn: { height: 48, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  actionBtnText: { color: '#FFF', fontSize: 16, fontWeight: '700' },
  bottomPad: { height: 40 },
});
