import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { BoardingHouseAPI, ReservationAPI, InquiryAPI } from '@/services/api';
import { useAuth } from '@/context/AuthContext';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { ScreenHeader } from '@/components/ui/ScreenHeader';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';

export default function BoardingHouseDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const { user } = useAuth();
  const router = useRouter();
  const [house, setHouse] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [reserving, setReserving] = useState(false);

  useEffect(() => {
    BoardingHouseAPI.getById(Number(id))
      .then((d: any) => setHouse(d.data))
      .catch(() => Alert.alert('Error', 'Failed to load details'))
      .finally(() => setLoading(false));
  }, [id]);

  async function handleReserve() {
    setReserving(true);
    try {
      await ReservationAPI.create({ tenant_id: user!.id, boarding_house_id: house.id });
      Alert.alert('Success', 'Reservation request sent! Waiting for landlord approval.', [
        { text: 'OK', onPress: () => router.push('/(tenant)/reservations') },
      ]);
    } catch (err: any) {
      Alert.alert('Error', err.message);
    } finally {
      setReserving(false);
    }
  }

  async function handleInquiry() {
    router.push({ pathname: '/(tenant)/inquiries', params: { boarding_house_id: house.id, landlord_id: house.landlord_id } });
  }

  if (loading) return <View style={styles.center}><ActivityIndicator color={Colors.primary} size="large" /></View>;
  if (!house) return null;

  const utilities = [
    { icon: 'flash-outline', label: 'Electricity', value: house.electricity_billing === 'metered' ? 'Metered' : `₱${parseFloat(house.electricity_rate || 0).toLocaleString()}/mo` },
    { icon: 'water-outline', label: 'Water', value: house.water_billing === 'metered' ? 'Metered' : `₱${parseFloat(house.water_rate || 0).toLocaleString()}/mo` },
  ];

  return (
    <SafeAreaView style={styles.safe} edges={['top']}>
      <ScreenHeader title="Boarding House" showBack />
      <ScrollView contentContainerStyle={styles.content}>
        {/* Hero */}
        <View style={styles.hero}>
          <Ionicons name="home" size={64} color={Colors.primary} />
          <Text style={styles.heroName}>{house.name}</Text>
          <Text style={styles.heroAddress}>{house.address}</Text>
          <Badge label={house.available_rooms > 0 ? `${house.available_rooms} rooms available` : 'No rooms available'} variant={house.available_rooms > 0 ? 'approved' : 'rejected'} />
        </View>

        {/* Price */}
        <Card style={styles.priceCard}>
          <Text style={styles.priceLabel}>Monthly Rent</Text>
          <Text style={styles.priceValue}>₱{parseFloat(house.rent_price).toLocaleString()}</Text>
        </Card>

        {/* Utilities */}
        <Card style={styles.section}>
          <Text style={styles.sectionTitle}>Utilities</Text>
          {utilities.map(u => (
            <View key={u.label} style={styles.utilRow}>
              <Ionicons name={u.icon as any} size={20} color={Colors.primary} />
              <Text style={styles.utilLabel}>{u.label}</Text>
              <Text style={styles.utilValue}>{u.value}</Text>
            </View>
          ))}
        </Card>

        {/* Description */}
        {house.description && (
          <Card style={styles.section}>
            <Text style={styles.sectionTitle}>About</Text>
            <Text style={styles.description}>{house.description}</Text>
          </Card>
        )}

        {/* Landlord */}
        <Card style={styles.section}>
          <Text style={styles.sectionTitle}>Landlord</Text>
          <View style={styles.landlordRow}>
            <View style={styles.landlordAvatar}>
              <Ionicons name="person" size={24} color={Colors.primary} />
            </View>
            <View>
              <Text style={styles.landlordName}>{house.landlord_name}</Text>
              <Text style={styles.landlordPhone}>{house.landlord_phone}</Text>
            </View>
          </View>
        </Card>

        {/* Actions */}
        <View style={styles.actions}>
          <Button title="Send Inquiry" variant="outline" onPress={handleInquiry} style={styles.actionBtn} />
          <Button
            title="Reserve Now"
            onPress={handleReserve}
            loading={reserving}
            disabled={house.available_rooms === 0}
            style={styles.actionBtn}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: Colors.background },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  content: { padding: Spacing.md, gap: Spacing.md, paddingBottom: Spacing.xl },
  hero: { alignItems: 'center', backgroundColor: Colors.surface, borderRadius: Radius.xl, padding: Spacing.xl, gap: Spacing.sm },
  heroName: { fontSize: FontSize.xxl, fontWeight: '800', color: Colors.text, textAlign: 'center' },
  heroAddress: { fontSize: FontSize.md, color: Colors.textSecondary, textAlign: 'center' },
  priceCard: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  priceLabel: { fontSize: FontSize.md, color: Colors.textSecondary, fontWeight: '600' },
  priceValue: { fontSize: FontSize.xxl, fontWeight: '800', color: Colors.primary },
  section: { gap: Spacing.sm },
  sectionTitle: { fontSize: FontSize.lg, fontWeight: '700', color: Colors.text, marginBottom: Spacing.xs },
  utilRow: { flexDirection: 'row', alignItems: 'center', gap: Spacing.sm, paddingVertical: Spacing.xs },
  utilLabel: { flex: 1, fontSize: FontSize.md, color: Colors.text },
  utilValue: { fontSize: FontSize.md, fontWeight: '600', color: Colors.primary },
  description: { fontSize: FontSize.md, color: Colors.textSecondary, lineHeight: 22 },
  landlordRow: { flexDirection: 'row', alignItems: 'center', gap: Spacing.md },
  landlordAvatar: { width: 48, height: 48, borderRadius: 24, backgroundColor: Colors.borderLight, alignItems: 'center', justifyContent: 'center' },
  landlordName: { fontSize: FontSize.md, fontWeight: '700', color: Colors.text },
  landlordPhone: { fontSize: FontSize.sm, color: Colors.textSecondary },
  actions: { flexDirection: 'row', gap: Spacing.sm },
  actionBtn: { flex: 1 },
});
