import { View, Text, ScrollView, TouchableOpacity, Modal, FlatList } from 'react-native';
import { useState, useCallback } from 'react';
import { useFocusEffect, router } from 'expo-router';
import { Plus, Users, Calendar, BookOpen, ChevronRight, X } from 'lucide-react-native';
import { useUserStore } from '@/store/useUserStore';
import { getDatabase } from '@/lib/database';
import { Contact } from '@/store/useContactStore';
import { dbToContact } from '@/lib/contactHelpers';
import { formatDate } from '@/lib/visitHelpers';

interface Stats {
  total: number;
  returnVisits: number;
  bibleStudies: number;
  visitsDue: number;
}

interface ReturnVisit {
  contactId: string;
  contactName: string;
  nextVisitDate: number;
}

export default function HomeScreen() {
  const user = useUserStore((s) => s.user);
  const [stats, setStats] = useState<Stats>({ total: 0, returnVisits: 0, bibleStudies: 0, visitsDue: 0 });
  const [dueVisits, setDueVisits] = useState<ReturnVisit[]>([]);
  const [showFAB, setShowFAB] = useState(false);

  async function loadDashboard() {
    const db = await getDatabase();
    const now = Math.floor(Date.now() / 1000);
    const todayEnd = now + 86400 * 3; // next 3 days

    const contacts = await db.getAllAsync<any>('SELECT status FROM contacts WHERE deleted_at IS NULL');
    const total = contacts.length;
    const returnVisits = contacts.filter((c) => c.status === 'Return Visit').length;
    const bibleStudies = contacts.filter((c) => c.status === 'Bible Study').length;

    const due = await db.getAllAsync<any>(
      `SELECT v.contact_id, c.full_name, MAX(v.next_visit_date) as next_visit_date
       FROM visits v JOIN contacts c ON c.id = v.contact_id
       WHERE v.next_visit_date IS NOT NULL AND v.next_visit_date <= ? AND c.deleted_at IS NULL
       GROUP BY v.contact_id ORDER BY next_visit_date ASC`,
      [todayEnd]
    );

    setStats({ total, returnVisits, bibleStudies, visitsDue: due.length });
    setDueVisits(due.map((d) => ({ contactId: d.contact_id, contactName: d.full_name, nextVisitDate: d.next_visit_date })));
  }

  useFocusEffect(useCallback(() => { loadDashboard(); }, []));

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

  return (
    <View className="flex-1 bg-secondary">
      {/* Header */}
      <View className="bg-primary pt-14 pb-6 px-4">
        <Text className="text-white/70 text-sm">{greeting()},</Text>
        <Text className="text-white text-2xl font-bold">{user?.displayName ?? 'Friend'}</Text>
        <Text className="text-white/60 text-sm mt-1">
          {new Date().toLocaleDateString('en-PH', { weekday: 'long', month: 'long', day: 'numeric' })}
        </Text>
      </View>

      <ScrollView className="flex-1 px-4 pt-4" contentContainerStyle={{ gap: 12, paddingBottom: 100 }}>
        {/* Stats Grid */}
        <View className="flex-row gap-3">
          <StatCard label="Total Contacts" value={stats.total} color="bg-primary" icon="👥" />
          <StatCard label="Return Visits" value={stats.returnVisits} color="bg-blue-500" icon="📅" />
        </View>
        <View className="flex-row gap-3">
          <StatCard label="Bible Studies" value={stats.bibleStudies} color="bg-purple-500" icon="📖" />
          <StatCard label="Visits Due" value={stats.visitsDue} color={stats.visitsDue > 0 ? "bg-orange-500" : "bg-gray-400"} icon="⏰" />
        </View>

        {/* Return Visits Due */}
        {dueVisits.length > 0 && (
          <View className="bg-white rounded-2xl p-4">
            <Text className="text-charcoal font-semibold mb-3">⏰ Visits Due Soon</Text>
            {dueVisits.slice(0, 5).map((v) => (
              <TouchableOpacity
                key={v.contactId}
                onPress={() => router.push({ pathname: '/contact/[id]', params: { id: v.contactId } })}
                className="flex-row items-center justify-between py-2 border-b border-gray-50"
              >
                <Text className="text-charcoal font-medium">{v.contactName}</Text>
                <Text className="text-primary text-sm">{formatDate(v.nextVisitDate)}</Text>
              </TouchableOpacity>
            ))}
            {dueVisits.length > 5 && (
              <Text className="text-gray-400 text-sm text-center mt-2">+{dueVisits.length - 5} more</Text>
            )}
          </View>
        )}

        {/* Quick actions */}
        <View className="bg-white rounded-2xl p-4">
          <Text className="text-charcoal font-semibold mb-3">Quick Actions</Text>
          <QuickAction icon="👥" label="View Contacts" onPress={() => router.push('/(tabs)/contacts')} />
          <QuickAction icon="🗺️" label="Open Map" onPress={() => router.push('/(tabs)/map')} />
          <QuickAction icon="⚙️" label="Settings" onPress={() => router.push('/(tabs)/settings')} />
        </View>
      </ScrollView>

      {/* FAB */}
      <TouchableOpacity
        onPress={() => setShowFAB(true)}
        className="absolute bottom-8 right-6 w-14 h-14 bg-primary rounded-full items-center justify-center shadow-lg"
        style={{ elevation: 8 }}
      >
        <Plus size={28} color="white" />
      </TouchableOpacity>

      {/* FAB Action Sheet */}
      <Modal visible={showFAB} transparent animationType="fade">
        <TouchableOpacity className="flex-1 bg-black/50 justify-end" onPress={() => setShowFAB(false)}>
          <View className="bg-white rounded-t-3xl px-4 pt-6 pb-10">
            <Text className="text-charcoal font-semibold text-lg mb-4 text-center">Quick Add</Text>
            <FABAction
              icon="👤"
              label="Add Contact"
              sub="Record a new person"
              onPress={() => {
                setShowFAB(false);
                router.push({ pathname: '/(tabs)/contacts', params: { openAdd: '1' } });
              }}
            />
            <FABAction
              icon="📍"
              label="Log Visit"
              sub="Record a visit to a contact"
              onPress={() => { setShowFAB(false); router.push('/(tabs)/contacts'); }}
            />
          </View>
        </TouchableOpacity>
      </Modal>
    </View>
  );
}

function StatCard({ label, value, color, icon }: { label: string; value: number; color: string; icon: string }) {
  return (
    <View className={`flex-1 ${color} rounded-2xl p-4`}>
      <Text className="text-2xl mb-1">{icon}</Text>
      <Text className="text-white text-2xl font-bold">{value}</Text>
      <Text className="text-white/80 text-xs">{label}</Text>
    </View>
  );
}

function QuickAction({ icon, label, onPress }: { icon: string; label: string; onPress: () => void }) {
  return (
    <TouchableOpacity onPress={onPress} className="flex-row items-center py-3 border-b border-gray-50">
      <Text className="text-2xl mr-3">{icon}</Text>
      <Text className="flex-1 text-charcoal font-medium">{label}</Text>
      <ChevronRight size={16} color="#9CA3AF" />
    </TouchableOpacity>
  );
}

function FABAction({ icon, label, sub, onPress }: { icon: string; label: string; sub: string; onPress: () => void }) {
  return (
    <TouchableOpacity onPress={onPress} className="flex-row items-center py-3 px-2 mb-2 border border-gray-100 rounded-xl">
      <Text className="text-3xl mr-4">{icon}</Text>
      <View>
        <Text className="text-charcoal font-semibold">{label}</Text>
        <Text className="text-gray-400 text-sm">{sub}</Text>
      </View>
    </TouchableOpacity>
  );
}
