import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, ScrollView, RefreshControl, ActivityIndicator, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '@/context/AuthContext';
import { ReportAPI } from '@/services/api';
import { Card } from '@/components/ui/Card';
import { ScreenHeader } from '@/components/ui/ScreenHeader';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';

const TABS = ['income', 'occupancy', 'payments'] as const;
type Tab = typeof TABS[number];

export default function ReportsScreen() {
  const { user } = useAuth();
  const [tab, setTab] = useState<Tab>('income');
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      let result: any;
      if (tab === 'income') result = await ReportAPI.income(user!.id);
      else if (tab === 'occupancy') result = await ReportAPI.occupancy(user!.id);
      else result = await ReportAPI.payments(user!.id);
      setData(result.data ?? result);
    } catch (_) { setData(null); }
    setLoading(false);
    setRefreshing(false);
  }, [user, tab]);

  useEffect(() => { load(); }, [load]);

  return (
    <SafeAreaView style={styles.safe} edges={['top']}>
      <ScreenHeader title="Reports" subtitle="Business insights" showMenu />

      {/* Tabs */}
      <View style={styles.tabRow}>
        {TABS.map(t => (
          <TouchableOpacity key={t} onPress={() => setTab(t)} style={[styles.tab, tab === t && styles.tabActive]}>
            <Text style={[styles.tabText, tab === t && styles.tabTextActive]}>{t.charAt(0).toUpperCase() + t.slice(1)}</Text>
          </TouchableOpacity>
        ))}
      </View>

      {loading ? (
        <View style={styles.center}><ActivityIndicator color={Colors.primary} size="large" /></View>
      ) : (
        <ScrollView
          contentContainerStyle={styles.content}
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); load(); }} />}
        >
          {tab === 'income' && data && (
            <>
              <Card style={styles.highlightCard}>
                <Text style={styles.highlightLabel}>Total Income This Month</Text>
                <Text style={styles.highlightValue}>₱{parseFloat(data.total_income || 0).toLocaleString()}</Text>
              </Card>
              <Card style={styles.section}>
                <Text style={styles.sectionTitle}>Income by Property</Text>
                {(data.by_property ?? []).map((item: any) => (
                  <View key={item.id} style={styles.reportRow}>
                    <View style={styles.reportLeft}>
                      <Ionicons name="home-outline" size={16} color={Colors.primary} />
                      <Text style={styles.reportLabel}>{item.name}</Text>
                    </View>
                    <Text style={styles.reportValue}>₱{parseFloat(item.income || 0).toLocaleString()}</Text>
                  </View>
                ))}
              </Card>
            </>
          )}

          {tab === 'occupancy' && data && (
            <>
              <View style={styles.statsRow}>
                <Card style={styles.statCard}>
                  <Text style={styles.statValue}>{data.total_rooms ?? 0}</Text>
                  <Text style={styles.statLabel}>Total Rooms</Text>
                </Card>
                <Card style={styles.statCard}>
                  <Text style={[styles.statValue, { color: Colors.success }]}>{data.occupied_rooms ?? 0}</Text>
                  <Text style={styles.statLabel}>Occupied</Text>
                </Card>
                <Card style={styles.statCard}>
                  <Text style={[styles.statValue, { color: Colors.warning }]}>{data.available_rooms ?? 0}</Text>
                  <Text style={styles.statLabel}>Available</Text>
                </Card>
              </View>
              <Card style={styles.section}>
                <Text style={styles.sectionTitle}>Occupancy Rate</Text>
                <View style={styles.progressBar}>
                  <View style={[styles.progressFill, { width: `${data.occupancy_rate ?? 0}%` }]} />
                </View>
                <Text style={styles.progressLabel}>{data.occupancy_rate ?? 0}% occupied</Text>
              </Card>
              <Card style={styles.section}>
                <Text style={styles.sectionTitle}>By Property</Text>
                {(data.by_property ?? []).map((item: any) => (
                  <View key={item.id} style={styles.reportRow}>
                    <View style={styles.reportLeft}>
                      <Ionicons name="home-outline" size={16} color={Colors.primary} />
                      <Text style={styles.reportLabel}>{item.name}</Text>
                    </View>
                    <Text style={styles.reportValue}>{item.occupied}/{item.total}</Text>
                  </View>
                ))}
              </Card>
            </>
          )}

          {tab === 'payments' && data && (
            <>
              <View style={styles.statsRow}>
                <Card style={styles.statCard}>
                  <Text style={[styles.statValue, { color: Colors.success }]}>₱{parseFloat(data.total_paid || 0).toLocaleString()}</Text>
                  <Text style={styles.statLabel}>Collected</Text>
                </Card>
                <Card style={styles.statCard}>
                  <Text style={[styles.statValue, { color: Colors.danger }]}>₱{parseFloat(data.total_unpaid || 0).toLocaleString()}</Text>
                  <Text style={styles.statLabel}>Pending</Text>
                </Card>
              </View>
              <Card style={styles.section}>
                <Text style={styles.sectionTitle}>Payment Summary</Text>
                {[
                  { label: 'Paid', value: data.paid_count ?? 0, color: Colors.success },
                  { label: 'Unpaid', value: data.unpaid_count ?? 0, color: Colors.warning },
                  { label: 'Overdue', value: data.overdue_count ?? 0, color: Colors.danger },
                ].map(item => (
                  <View key={item.label} style={styles.reportRow}>
                    <View style={styles.reportLeft}>
                      <View style={[styles.dot, { backgroundColor: item.color }]} />
                      <Text style={styles.reportLabel}>{item.label}</Text>
                    </View>
                    <Text style={[styles.reportValue, { color: item.color }]}>{item.value} records</Text>
                  </View>
                ))}
              </Card>
            </>
          )}
        </ScrollView>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: Colors.background },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  tabRow: { flexDirection: 'row', backgroundColor: Colors.surface, borderBottomWidth: 1, borderBottomColor: Colors.border },
  tab: { flex: 1, paddingVertical: Spacing.sm + 2, alignItems: 'center' },
  tabActive: { borderBottomWidth: 2, borderBottomColor: Colors.primary },
  tabText: { fontSize: FontSize.sm, fontWeight: '600', color: Colors.textSecondary },
  tabTextActive: { color: Colors.primary },
  content: { padding: Spacing.md, gap: Spacing.md, paddingBottom: Spacing.xl },
  highlightCard: { alignItems: 'center', padding: Spacing.xl, backgroundColor: Colors.primary },
  highlightLabel: { fontSize: FontSize.md, color: 'rgba(255,255,255,0.8)' },
  highlightValue: { fontSize: 36, fontWeight: '800', color: Colors.textInverse, marginTop: Spacing.xs },
  section: { gap: Spacing.sm },
  sectionTitle: { fontSize: FontSize.lg, fontWeight: '700', color: Colors.text, marginBottom: Spacing.xs },
  reportRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: Spacing.xs },
  reportLeft: { flexDirection: 'row', alignItems: 'center', gap: Spacing.sm },
  reportLabel: { fontSize: FontSize.md, color: Colors.text },
  reportValue: { fontSize: FontSize.md, fontWeight: '700', color: Colors.text },
  statsRow: { flexDirection: 'row', gap: Spacing.sm },
  statCard: { flex: 1, alignItems: 'center', gap: 4 },
  statValue: { fontSize: FontSize.xl, fontWeight: '800', color: Colors.text },
  statLabel: { fontSize: FontSize.xs, color: Colors.textSecondary },
  progressBar: { height: 12, backgroundColor: Colors.borderLight, borderRadius: Radius.full, overflow: 'hidden', marginVertical: Spacing.sm },
  progressFill: { height: '100%', backgroundColor: Colors.primary, borderRadius: Radius.full },
  progressLabel: { fontSize: FontSize.sm, color: Colors.textSecondary, textAlign: 'center' },
  dot: { width: 10, height: 10, borderRadius: 5 },
});
