import { useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, ActivityIndicator, RefreshControl } from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { api } from '../../../services/api';

const METHOD_ICON: Record<string, string> = { CASH: '💵', GCASH: '📱', MAYA: '💙', BANK: '🏦' };

export default function PaymentsScreen() {
  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['payments'],
    queryFn: () => api.get('/api/v1/payments?limit=50').then(r => r.data?.data ?? r.data ?? []),
  });

  const payments: any[] = data ?? [];

  // Calculate today's total
  const today = new Date().toDateString();
  const todayTotal = payments
    .filter((p: any) => new Date(p.paymentDate ?? p.createdAt).toDateString() === today)
    .reduce((sum: number, p: any) => sum + Number(p.amount), 0);

  return (
    <View className="flex-1 bg-gray-50">
      {/* Header */}
      <View className="px-4 pt-14 pb-4 bg-primary flex-row justify-between items-center">
        <View>
          <Text className="text-white text-xl font-bold">Payments</Text>
          <Text className="text-white/70 text-xs mt-0.5">Today: ₱{todayTotal.toLocaleString()}</Text>
        </View>
        <TouchableOpacity
          className="bg-white/20 rounded-xl px-4 py-2"
          onPress={() => router.push('/(app)/payments/record')}
        >
          <Text className="text-white font-semibold text-sm">+ Record</Text>
        </TouchableOpacity>
      </View>

      {isLoading ? (
        <View className="flex-1 items-center justify-center"><ActivityIndicator color="#2563EB" /></View>
      ) : (
        <FlatList
          data={payments}
          keyExtractor={(item) => item.id}
          refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
          contentContainerStyle={{ padding: 16, paddingBottom: 32 }}
          ListEmptyComponent={
            <View className="items-center py-20">
              <Text className="text-4xl mb-3">💳</Text>
              <Text className="text-gray-400 text-base">No payments yet</Text>
              <TouchableOpacity
                className="mt-4 bg-primary rounded-xl px-6 py-3"
                onPress={() => router.push('/(app)/payments/record')}
              >
                <Text className="text-white font-semibold">Record First Payment</Text>
              </TouchableOpacity>
            </View>
          }
          renderItem={({ item }) => (
            <View className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
              <View className="flex-row justify-between items-start">
                <View className="flex-1">
                  <View className="flex-row items-center mb-1">
                    <Text className="text-base mr-2">{METHOD_ICON[item.paymentMethod] ?? '💳'}</Text>
                    <Text className="font-semibold text-gray-900">
                      {item.client?.firstName} {item.client?.lastName}
                    </Text>
                  </View>
                  <Text className="text-gray-500 text-sm">{item.client?.accountNumber}</Text>
                  <Text className="text-gray-400 text-xs mt-1">
                    {new Date(item.paymentDate ?? item.createdAt).toLocaleDateString()} · {item.paymentMethod}
                  </Text>
                  {item.referenceNumber && (
                    <Text className="text-gray-400 text-xs">Ref: {item.referenceNumber}</Text>
                  )}
                </View>
                <Text className="font-bold text-green-700 text-lg">
                  ₱{Number(item.amount).toLocaleString()}
                </Text>
              </View>
            </View>
          )}
        />
      )}
    </View>
  );
}
