import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, ActivityIndicator, Alert, TouchableOpacity, SafeAreaView } from 'react-native';
import { bookkeepingApi } from '../lib/api';

export const ReportScreen: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [report, setReport] = useState<{
    total_income: number;
    total_expenses: number;
    net_profit: number;
    expenses_by_category: { category: string; total: string }[];
  } | null>(null);

  const loadReportData = async () => {
    setIsLoading(true);
    try {
      const data = await bookkeepingApi.getSummary();
      setReport(data || null);
    } catch (e) {
      console.error('Failed to load bookkeeping report', e);
      Alert.alert('Gagal Memuat Laporan', 'Tidak dapat mengambil rangkuman keuangan dari server.');
    } finally {
      setIsLoading(false);
    }
  };

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

  const formatCurrency = (val: number) => {
    return `Rp ${val.toLocaleString('id-ID', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
  };

  return (
    <SafeAreaView className="flex-1 bg-slate-body">
      {/* Header */}
      <View className="bg-white px-6 py-4 border-b border-slate-light/10 shadow-sm flex-row justify-between items-center">
        <View>
          <Text className="text-slate-main text-lg font-black tracking-tight">Laporan Keuangan</Text>
          <Text className="text-slate-light text-[10px] font-bold">RANGKUMAN LABA / RUGI TOKO</Text>
        </View>
        <TouchableOpacity onPress={loadReportData} className="bg-primary/10 px-3 py-1.5 rounded-full">
          <Text className="text-primary text-[10px] font-black">REFRESH 🔄</Text>
        </TouchableOpacity>
      </View>

      {isLoading ? (
        <View className="flex-1 items-center justify-center">
          <ActivityIndicator size="large" color="#005BFF" />
          <Text className="text-slate-sub text-xs mt-2 font-medium">Menganalisis data keuangan...</Text>
        </View>
      ) : !report ? (
        <View className="flex-1 items-center justify-center p-6">
          <Text className="text-3xl">📊</Text>
          <Text className="text-slate-main font-bold text-base mt-2">Data Laporan Kosong</Text>
        </View>
      ) : (
        <ScrollView className="flex-1 p-4 space-y-4">
          {/* Card Laba Bersih (Net Profit) */}
          <View className="bg-primary rounded-3xl p-6 shadow-lg shadow-primary-glow border border-primary-hover relative overflow-hidden">
            <View className="absolute -top-10 -right-10 w-32 h-32 bg-white/5 rounded-full" />
            <Text className="text-white/70 text-[10px] font-black tracking-wider">LABA / RUGI BERSIH</Text>
            <Text className="text-white font-black text-2xl mt-1">{formatCurrency(report.net_profit)}</Text>
            <Text className="text-white/60 text-[9px] font-semibold mt-2">
              Akumulasi laba kotor dikurangi biaya pengeluaran aktif.
            </Text>
          </View>

          {/* Cards 2 Columns: Income vs Expense */}
          <View className="flex-row gap-3">
            {/* Total Income */}
            <View className="flex-1 bg-white p-5 rounded-2xl border border-slate-light/10 shadow-sm relative overflow-hidden">
              <View className="absolute -top-6 -right-6 w-16 h-16 bg-success/5 rounded-full" />
              <Text className="text-slate-light text-[9px] font-black tracking-wider uppercase">Pemasukan (Omset)</Text>
              <Text className="text-success font-black text-base mt-1" numberOfLines={1}>{formatCurrency(report.total_income)}</Text>
            </View>
            {/* Total Expense */}
            <View className="flex-1 bg-white p-5 rounded-2xl border border-slate-light/10 shadow-sm relative overflow-hidden">
              <View className="absolute -top-6 -right-6 w-16 h-16 bg-red-500/5 rounded-full" />
              <Text className="text-slate-light text-[9px] font-black tracking-wider uppercase">Pengeluaran (Biaya)</Text>
              <Text className="text-red-500 font-black text-base mt-1" numberOfLines={1}>{formatCurrency(report.total_expenses)}</Text>
            </View>
          </View>

          {/* Expenses by Category list */}
          <View className="bg-white rounded-3xl p-6 border border-slate-light/10 shadow-sm">
            <Text className="text-slate-main font-extrabold text-sm mb-4">Rincian Biaya per Kategori</Text>
            
            {report.expenses_by_category.length === 0 ? (
              <Text className="text-slate-light text-center text-xs py-4 font-semibold">Tidak ada biaya operasional terdaftar.</Text>
            ) : (
              <View className="space-y-3">
                {report.expenses_by_category.map((cat, idx) => (
                  <View key={idx} className="flex-row justify-between items-center py-2.5 border-b border-slate-light/5">
                    <View className="flex-row items-center gap-2">
                      <View className="w-2.5 h-2.5 bg-red-400 rounded-full" />
                      <Text className="text-slate-main font-bold text-xs">{cat.category}</Text>
                    </View>
                    <Text className="text-red-500 font-black text-xs">
                      -{formatCurrency(parseFloat(cat.total) || 0)}
                    </Text>
                  </View>
                ))}
              </View>
            )}
          </View>

          <View className="h-16" />
        </ScrollView>
      )}
    </SafeAreaView>
  );
};
