import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, RefreshControl, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '@/context/AuthContext';
import { ReservationAPI, PaymentAPI } from '@/services/api';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';
import { useAppShell } from '@/components/ui/AppShell';
import { Logo } from '@/components/ui/Logo';

export default function TenantDashboard() {
  const { user } = useAuth();
  const router = useRouter();
  const { openSidebar } = useAppShell();
  const [reservations, setReservations] = useState<any[]>([]);
  const [payments, setPayments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    try {
      const [resData, payData] = await Promise.all([
        ReservationAPI.getByTenant(user!.id),
        PaymentAPI.getByTenant(user!.id),
      ]);
      setReservations(resData.data ?? []);
      setPayments(payData.data ?? []);
    } catch (_) {}
    setLoading(false);
    setRefreshing(false);
  }, [user]);

  useEffect(() => { load(); }, [load]);

  const activeReservation = reservations.find(r => r.status === 'approved' || r.status === 'leave_requested');

  // Group unpaid payments by month_year for the current active reservation
  const unpaidByMonth: Record<string, any[]> = {};
  payments
    .filter(p => p.status !== 'paid')
    .forEach(p => {
      const key = p.month_year ?? 'Unknown';
      if (!unpaidByMonth[key]) unpaidByMonth[key] = [];
      unpaidByMonth[key].push(p);
    });
  const monthKeys = Object.keys(unpaidByMonth).sort().reverse();
  const totalDue = payments.filter(p => p.status !== 'paid').reduce((s: number, p: any) => s + parseFloat(p.amount || 0), 0);

  if (loading) return <View style={styles.center}><ActivityIndicator color={Colors.primary} size="large" /></View>;

  return (
    <SafeAreaView style={styles.safe} edges={['top']}>
      <View style={styles.header}>
        <TouchableOpacity onPress={openSidebar} style={styles.menuBtn}>
          <Ionicons name="menu" size={26} color={Colors.textInverse} />
        </TouchableOpacity>
        <Logo size={32} showName light style={styles.headerLogo} />
        <TouchableOpacity onPress={() => router.push('/(tenant)/notifications')} style={styles.notifBtn}>
          <Ionicons name="notifications-outline" size={24} color={Colors.textInverse} />
        </TouchableOpacity>
      </View>

      <ScrollView
        style={styles.scroll}
        contentContainerStyle={styles.content}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); load(); }} />}
      >
        {/* Summary Cards */}
        <View style={styles.summaryRow}>
          <Card style={styles.summaryCard}>
            <Ionicons name="home" size={24} color={Colors.primary} />
            <Text style={styles.summaryValue}>{activeReservation ? '1' : '0'}</Text>
            <Text style={styles.summaryLabel}>Active Room</Text>
          </Card>
          <Card style={styles.summaryCard}>
            <Ionicons name="card" size={24} color={Colors.danger} />
            <Text style={[styles.summaryValue, { color: Colors.danger }]}>₱{totalDue.toLocaleString()}</Text>
            <Text style={styles.summaryLabel}>Total Due</Text>
          </Card>
          <Card style={styles.summaryCard}>
            <Ionicons name="calendar" size={24} color={Colors.warning} />
            <Text style={styles.summaryValue}>{monthKeys.length}</Text>
            <Text style={styles.summaryLabel}>Unpaid Months</Text>
          </Card>
        </View>

        {/* Active Reservation */}
        {activeReservation && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Current Room</Text>
            <Card>
              <View style={styles.reservationRow}>
                <View style={styles.reservationIcon}>
                  <Ionicons name="home" size={28} color={Colors.primary} />
                </View>
                <View style={styles.reservationInfo}>
                  <Text style={styles.bhName}>{activeReservation.boarding_house_name}</Text>
                  <Text style={styles.bhAddress}>{activeReservation.address}</Text>
                  <Text style={styles.bhPrice}>₱{parseFloat(activeReservation.rent_price).toLocaleString()}/month</Text>
                </View>
                <Badge
                  label={activeReservation.status === 'leave_requested' ? 'Leaving' : 'Active'}
                  variant={activeReservation.status === 'leave_requested' ? 'pending' : 'approved'}
                />
              </View>
            </Card>
          </View>
        )}

        {/* Monthly Bills */}
        {monthKeys.length > 0 && (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>Monthly Bills</Text>
              <TouchableOpacity onPress={() => router.push('/(tenant)/payments')}>
                <Text style={styles.seeAll}>See all</Text>
              </TouchableOpacity>
            </View>
            {monthKeys.slice(0, 2).map(month => {
              const bills = unpaidByMonth[month];
              const rent = bills.find((b: any) => b.type === 'rent');
              const elec = bills.find((b: any) => b.type === 'electricity');
              const water = bills.find((b: any) => b.type === 'water');
              const total = bills.reduce((s: number, b: any) => s + parseFloat(b.amount || 0), 0);
              return (
                <Card key={month} style={styles.billCard}>
                  <View style={styles.billHeader}>
                    <Text style={styles.billMonth}>{formatMonth(month)}</Text>
                    <Badge label="Unpaid" variant="unpaid" />
                  </View>
                  <View style={styles.billRows}>
                    <BillRow icon="home-outline" label="Boarding House" amount={rent?.amount} />
                    <BillRow icon="flash-outline" label="Electricity" amount={elec?.amount} />
                    <BillRow icon="water-outline" label="Water" amount={water?.amount} />
                  </View>
                  <View style={styles.billTotal}>
                    <Text style={styles.billTotalLabel}>Total Due</Text>
                    <Text style={styles.billTotalAmount}>₱{total.toLocaleString()}</Text>
                  </View>
                  <Text style={styles.billNote}>Pay personally to your landlord. They will confirm once received.</Text>
                </Card>
              );
            })}
          </View>
        )}

        {/* No active room prompt */}
        {!activeReservation && (
          <Card style={styles.emptyCard}>
            <Ionicons name="home-outline" size={40} color={Colors.textLight} />
            <Text style={styles.emptyTitle}>No active room</Text>
            <Text style={styles.emptyText}>Browse boarding houses and send a reservation request.</Text>
            <TouchableOpacity style={styles.browseBtn} onPress={() => router.push('/(tenant)/map')}>
              <Text style={styles.browseBtnText}>Browse Boarding Houses</Text>
            </TouchableOpacity>
          </Card>
        )}

        {/* Quick Actions */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Quick Actions</Text>
          <View style={styles.actionsGrid}>
            {[
              { icon: 'map-outline', label: 'Find Rooms', route: '/(tenant)/map' },
              { icon: 'calendar-outline', label: 'Reservations', route: '/(tenant)/reservations' },
              { icon: 'card-outline', label: 'Payments', route: '/(tenant)/payments' },
              { icon: 'chatbubble-outline', label: 'Inquiries', route: '/(tenant)/inquiries' },
            ].map((action) => (
              <TouchableOpacity key={action.label} style={styles.actionBtn} onPress={() => router.push(action.route as any)}>
                <View style={styles.actionIcon}>
                  <Ionicons name={action.icon as any} size={24} color={Colors.primary} />
                </View>
                <Text style={styles.actionLabel}>{action.label}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

function BillRow({ icon, label, amount }: { icon: any; label: string; amount?: string }) {
  return (
    <View style={styles.billRow}>
      <Ionicons name={icon} size={16} color={Colors.textSecondary} />
      <Text style={styles.billRowLabel}>{label}</Text>
      <Text style={styles.billRowAmount}>
        {amount !== undefined ? `₱${parseFloat(amount).toLocaleString()}` : '—'}
      </Text>
    </View>
  );
}

function formatMonth(monthYear: string) {
  try {
    const [y, m] = monthYear.split('-');
    return new Date(parseInt(y), parseInt(m) - 1).toLocaleString('default', { month: 'long', year: 'numeric' });
  } catch { return monthYear; }
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: Colors.background },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  header: {
    backgroundColor: Colors.primary,
    paddingHorizontal: Spacing.lg,
    paddingVertical: Spacing.sm,
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.sm,
  },
  menuBtn: { padding: Spacing.xs },
  headerLogo: { flex: 1, alignItems: 'flex-start', flexDirection: 'row' },
  notifBtn: { padding: Spacing.xs },
  scroll: { flex: 1 },
  content: { padding: Spacing.md, paddingBottom: Spacing.xl },
  summaryRow: { flexDirection: 'row', gap: Spacing.sm, marginBottom: Spacing.md },
  summaryCard: { flex: 1, alignItems: 'center', gap: 4, padding: Spacing.md },
  summaryValue: { fontSize: FontSize.xl, fontWeight: '700', color: Colors.text },
  summaryLabel: { fontSize: FontSize.xs, color: Colors.textSecondary, textAlign: 'center' },
  section: { marginBottom: Spacing.lg },
  sectionHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: Spacing.sm },
  sectionTitle: { fontSize: FontSize.lg, fontWeight: '700', color: Colors.text, marginBottom: Spacing.sm },
  seeAll: { fontSize: FontSize.sm, color: Colors.primary, fontWeight: '600' },
  reservationRow: { flexDirection: 'row', alignItems: 'center', gap: Spacing.md },
  reservationIcon: { width: 52, height: 52, borderRadius: Radius.md, backgroundColor: Colors.borderLight, alignItems: 'center', justifyContent: 'center' },
  reservationInfo: { flex: 1 },
  bhName: { fontSize: FontSize.md, fontWeight: '700', color: Colors.text },
  bhAddress: { fontSize: FontSize.sm, color: Colors.textSecondary, marginTop: 2 },
  bhPrice: { fontSize: FontSize.sm, color: Colors.primary, fontWeight: '600', marginTop: 4 },
  billCard: { padding: Spacing.md, marginBottom: Spacing.sm },
  billHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: Spacing.sm },
  billMonth: { fontSize: FontSize.md, fontWeight: '700', color: Colors.text },
  billRows: { gap: Spacing.xs, marginBottom: Spacing.sm },
  billRow: { flexDirection: 'row', alignItems: 'center', gap: Spacing.sm },
  billRowLabel: { flex: 1, fontSize: FontSize.sm, color: Colors.textSecondary },
  billRowAmount: { fontSize: FontSize.sm, fontWeight: '600', color: Colors.text },
  billTotal: { flexDirection: 'row', justifyContent: 'space-between', borderTopWidth: 1, borderTopColor: Colors.border, paddingTop: Spacing.sm, marginBottom: Spacing.xs },
  billTotalLabel: { fontSize: FontSize.md, fontWeight: '700', color: Colors.text },
  billTotalAmount: { fontSize: FontSize.lg, fontWeight: '800', color: Colors.danger },
  billNote: { fontSize: FontSize.xs, color: Colors.textSecondary, fontStyle: 'italic' },
  emptyCard: { alignItems: 'center', padding: Spacing.xl, gap: Spacing.sm, marginBottom: Spacing.lg },
  emptyTitle: { fontSize: FontSize.lg, fontWeight: '700', color: Colors.text },
  emptyText: { fontSize: FontSize.sm, color: Colors.textSecondary, textAlign: 'center' },
  browseBtn: { backgroundColor: Colors.primary, borderRadius: Radius.md, paddingHorizontal: Spacing.lg, paddingVertical: Spacing.sm, marginTop: Spacing.sm },
  browseBtnText: { color: Colors.textInverse, fontWeight: '700', fontSize: FontSize.sm },
  actionsGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: Spacing.sm },
  actionBtn: { width: '47%', backgroundColor: Colors.surface, borderRadius: Radius.lg, padding: Spacing.md, alignItems: 'center', gap: Spacing.sm },
  actionIcon: { width: 48, height: 48, borderRadius: Radius.md, backgroundColor: Colors.borderLight, alignItems: 'center', justifyContent: 'center' },
  actionLabel: { fontSize: FontSize.sm, fontWeight: '600', color: Colors.text },
});
