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

const PRIORITY_COLOR: Record<string, string> = { HIGH: '#DC2626', MEDIUM: '#D97706', LOW: '#6B7280' };
const TICKET_STATUS_COLOR: Record<string, string> = { OPEN: '#2563EB', IN_PROGRESS: '#D97706', RESOLVED: '#16A34A', CLOSED: '#6B7280' };

function KpiCard({ label, value, color, onPress }: { label: string; value: string | number; color: string; onPress?: () => void }) {
  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={!onPress}
      className="bg-white rounded-2xl p-4 flex-1 mx-1 shadow-sm border border-gray-100"
    >
      <Text className="text-gray-500 text-xs mb-1">{label}</Text>
      <Text className="text-2xl font-bold" style={{ color }}>{value}</Text>
    </TouchableOpacity>
  );
}

function QuickAction({ icon, label, onPress }: { icon: string; label: string; onPress: () => void }) {
  return (
    <TouchableOpacity className="flex-1 items-center bg-white rounded-2xl py-4 mx-1 border border-gray-100" onPress={onPress}>
      <Text className="text-2xl mb-1">{icon}</Text>
      <Text className="text-xs text-gray-600 font-medium">{label}</Text>
    </TouchableOpacity>
  );
}

export default function DashboardScreen() {
  const { user } = useAuthStore();
  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['dashboard'],
    queryFn: () => api.get('/api/v1/dashboard/summary').then(r => r.data),
  });

  const greeting = () => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 17) return 'Good afternoon';
    return 'Good evening';
  };

  return (
    <ScrollView
      className="flex-1 bg-gray-50"
      refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
    >
      {/* Header */}
      <View className="px-4 pt-14 pb-6 bg-primary">
        <Text className="text-white/70 text-sm">{greeting()},</Text>
        <Text className="text-white text-2xl font-bold">{user?.firstName ?? 'Field Staff'} 👋</Text>
        <Text className="text-white/50 text-xs mt-1">{new Date().toLocaleDateString('en-PH', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</Text>
      </View>

      {isLoading ? (
        <View className="flex-1 items-center justify-center py-20">
          <ActivityIndicator color="#2563EB" />
        </View>
      ) : (
        <View className="px-3 py-4">
          {/* KPIs */}
          <Text className="text-gray-700 font-semibold mb-3 px-1">Overview</Text>
          <View className="flex-row mb-2">
            <KpiCard
              label="Total Clients"
              value={data?.totalClients ?? 0}
              color="#2563EB"
              onPress={() => router.push('/(app)/clients')}
            />
            <KpiCard
              label="Active Subs"
              value={data?.activeSubscriptions ?? 0}
              color="#16A34A"
            />
          </View>
          <View className="flex-row mb-5">
            <KpiCard
              label="Overdue"
              value={data?.overdueInvoices ?? 0}
              color="#DC2626"
              onPress={() => router.push('/(app)/clients')}
            />
            <KpiCard
              label="Today's Collections"
              value={`₱${(data?.todayCollections ?? 0).toLocaleString()}`}
              color="#D97706"
              onPress={() => router.push('/(app)/payments')}
            />
          </View>

          {/* Quick Actions */}
          <Text className="text-gray-700 font-semibold mb-3 px-1">Quick Actions</Text>
          <View className="flex-row mb-5">
            <QuickAction icon="💰" label="Collect" onPress={() => router.push('/(app)/payments/record')} />
            <QuickAction icon="🎫" label="New Ticket" onPress={() => router.push('/(app)/tickets/create')} />
            <QuickAction icon="🔌" label="Install" onPress={() => router.push('/(app)/installations')} />
            <QuickAction icon="📋" label="Remit" onPress={() => router.push('/(app)/remittances/submit')} />
          </View>

          {/* Recent Tickets */}
          <Text className="text-gray-700 font-semibold mb-3 px-1">Recent Tickets</Text>
          {(data?.recentTickets ?? []).length === 0 ? (
            <View className="bg-white rounded-2xl p-6 items-center border border-gray-100">
              <Text className="text-gray-400 mb-3">No recent tickets</Text>
              <TouchableOpacity
                className="bg-primary rounded-xl px-5 py-2"
                onPress={() => router.push('/(app)/tickets/create')}
              >
                <Text className="text-white text-sm font-semibold">Create Ticket</Text>
              </TouchableOpacity>
            </View>
          ) : (
            (data?.recentTickets ?? []).map((t: any) => (
              <TouchableOpacity
                key={t.id}
                className="bg-white rounded-xl p-4 mb-2 border border-gray-100"
                onPress={() => router.push(`/(app)/tickets/${t.id}`)}
              >
                <View className="flex-row justify-between items-start mb-1">
                  <Text className="font-medium text-gray-900 flex-1 mr-2" numberOfLines={1}>{t.subject}</Text>
                  <View className="rounded-full px-2 py-0.5" style={{ backgroundColor: `${PRIORITY_COLOR[t.priority] ?? '#6B7280'}20` }}>
                    <Text className="text-xs font-medium" style={{ color: PRIORITY_COLOR[t.priority] ?? '#6B7280' }}>{t.priority}</Text>
                  </View>
                </View>
                <View className="flex-row justify-between items-center mt-0.5">
                  <Text className="text-gray-500 text-sm">{t.clientName ?? 'No client'}</Text>
                  <View className="rounded-full px-2 py-0.5" style={{ backgroundColor: `${TICKET_STATUS_COLOR[t.status] ?? '#6B7280'}20` }}>
                    <Text className="text-xs" style={{ color: TICKET_STATUS_COLOR[t.status] ?? '#6B7280' }}>{t.status}</Text>
                  </View>
                </View>
              </TouchableOpacity>
            ))
          )}
        </View>
      )}
    </ScrollView>
  );
}
