/**
 * Dashboard — Today's priorities, KPIs, quick actions.
 * Central hub mirroring the fogbreak.html Dashboard tab.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { useTheme } from '../themes/ThemeProvider';
import BrandHeader from '../components/BrandHeader';
import KPIWidget from '../components/KPIWidget';
import ShowingCard from '../components/ShowingCard';
import TaskItem, { Task } from '../components/TaskItem';
import {
  getKPIs,
  getTodayShowings,
  getDeals,
  KPIData,
  Showing,
  Deal,
  updateTask,
} from '../services/api';
import { getCachedData, cacheData, CacheKeys } from '../services/offline';
import { getQueueLength } from '../services/offline';

export default function Dashboard() {
  const { theme } = useTheme();
  const navigation = useNavigation<any>();
  const [kpis, setKPIs] = useState<KPIData | null>(null);
  const [showings, setShowings] = useState<Showing[]>([]);
  const [urgentTasks, setUrgentTasks] = useState<Task[]>([]);
  const [pendingDeals, setPendingDeals] = useState<Deal[]>([]);
  const [offlineCount, setOfflineCount] = useState(0);
  const [refreshing, setRefreshing] = useState(false);

  const loadData = useCallback(async () => {
    // Load from cache first for instant display
    const cachedKPIs = await getCachedData<KPIData>(CacheKeys.KPI_DATA);
    if (cachedKPIs) setKPIs(cachedKPIs);

    const cachedShowings = await getCachedData<Showing[]>(CacheKeys.TODAY_SHOWINGS);
    if (cachedShowings) setShowings(cachedShowings);

    // Then fetch fresh data
    const [kpiRes, showingRes, dealRes] = await Promise.allSettled([
      getKPIs(),
      getTodayShowings(),
      getDeals({ status: 'active' }),
    ]);

    if (kpiRes.status === 'fulfilled' && kpiRes.value.data) {
      setKPIs(kpiRes.value.data);
      await cacheData(CacheKeys.KPI_DATA, kpiRes.value.data);
    }

    if (showingRes.status === 'fulfilled' && showingRes.value.data) {
      setShowings(showingRes.value.data);
      await cacheData(CacheKeys.TODAY_SHOWINGS, showingRes.value.data);
    }

    if (dealRes.status === 'fulfilled' && dealRes.value.data) {
      const deals = dealRes.value.data as Deal[];
      setPendingDeals(deals.slice(0, 5));
    }

    const qLen = await getQueueLength();
    setOfflineCount(qLen);
  }, []);

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

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadData();
    setRefreshing(false);
  }, [loadData]);

  const handleToggleTask = async (task: Task) => {
    const newStatus = task.status === 'completed' ? 'pending' : 'completed';
    setUrgentTasks((prev) =>
      prev.map((t) => (t.id === task.id ? { ...t, status: newStatus } : t))
    );
    await updateTask(task.id, { status: newStatus });
  };

  const formatCurrency = (val: number): string => {
    if (val >= 1_000_000) return `$${(val / 1_000_000).toFixed(1)}M`;
    if (val >= 1_000) return `$${(val / 1_000).toFixed(0)}K`;
    return `$${val.toLocaleString()}`;
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['top']}>
      <BrandHeader />

      <ScrollView
        style={styles.scroll}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />}
      >
        {/* Offline sync banner */}
        {offlineCount > 0 && (
          <View style={[styles.syncBanner, { backgroundColor: theme.colors.warning }]}>
            <Text style={styles.syncText}>
              {offlineCount} action{offlineCount > 1 ? 's' : ''} pending sync
            </Text>
          </View>
        )}

        {/* Quick Actions */}
        <View style={styles.quickActions}>
          <TouchableOpacity
            style={[styles.quickBtn, { backgroundColor: theme.colors.primary }]}
            onPress={() => navigation.navigate('ClientsTab', { screen: 'AddClient' })}
          >
            <Text style={styles.quickIcon}>+</Text>
            <Text style={styles.quickLabel}>Add Lead</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.quickBtn, { backgroundColor: theme.colors.accent }]}
            onPress={() => navigation.navigate('ShowingsTab', { screen: 'ShowingCart' })}
          >
            <Text style={styles.quickIcon}>🏠</Text>
            <Text style={styles.quickLabel}>Start Tour</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.quickBtn, { backgroundColor: theme.colors.info }]}
            onPress={() => navigation.navigate('MoreTab', { screen: 'ChatScreen' })}
          >
            <Text style={styles.quickIcon}>🤖</Text>
            <Text style={styles.quickLabel}>Ask AI</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.quickBtn, { backgroundColor: theme.colors.success }]}
            onPress={() =>
              Alert.prompt?.('Log Call', 'Enter client name', () => {}) ??
              Alert.alert('Log Call', 'Open a client to log a call')
            }
          >
            <Text style={styles.quickIcon}>📞</Text>
            <Text style={styles.quickLabel}>Log Call</Text>
          </TouchableOpacity>
        </View>

        {/* KPI Row */}
        {kpis && (
          <>
            <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Today's Numbers</Text>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.kpiRow}>
              <KPIWidget label="GCI MTD" value={formatCurrency(kpis.gci_mtd)} size="sm" />
              <KPIWidget label="Deals Closed" value={kpis.deals_closed_mtd} size="sm" />
              <KPIWidget label="Pending" value={kpis.deals_pending} size="sm" />
              <KPIWidget label="Leads MTD" value={kpis.leads_mtd} size="sm" />
              <KPIWidget label="Showings" value={kpis.showings_mtd} size="sm" />
              <KPIWidget label="Conversion" value={`${(kpis.conversion_rate * 100).toFixed(1)}%`} size="sm" />
            </ScrollView>
          </>
        )}

        {/* Today's Showings */}
        {showings.length > 0 && (
          <>
            <View style={styles.sectionHeader}>
              <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>
                Today's Showings ({showings.length})
              </Text>
              <TouchableOpacity onPress={() => navigation.navigate('ShowingsTab')}>
                <Text style={[styles.seeAll, { color: theme.colors.accent }]}>See All</Text>
              </TouchableOpacity>
            </View>
            {showings.slice(0, 3).map((showing) => (
              <ShowingCard
                key={showing.id}
                showing={showing}
                onPress={() =>
                  navigation.navigate('ShowingsTab', {
                    screen: 'ShowingDetail',
                    params: { id: showing.id },
                  })
                }
              />
            ))}
          </>
        )}

        {/* Urgent Tasks */}
        {urgentTasks.length > 0 && (
          <>
            <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Urgent Tasks</Text>
            {urgentTasks.map((task) => (
              <TaskItem
                key={task.id}
                task={task}
                onToggle={handleToggleTask}
                onPress={() => {}}
              />
            ))}
          </>
        )}

        {/* Active Deals */}
        {pendingDeals.length > 0 && (
          <>
            <View style={styles.sectionHeader}>
              <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Active Deals</Text>
              <TouchableOpacity onPress={() => navigation.navigate('DealsTab')}>
                <Text style={[styles.seeAll, { color: theme.colors.accent }]}>See All</Text>
              </TouchableOpacity>
            </View>
            {pendingDeals.map((deal) => (
              <TouchableOpacity
                key={deal.id}
                style={[styles.dealCard, theme.shadow.sm, { backgroundColor: theme.colors.card }]}
                onPress={() =>
                  navigation.navigate('DealsTab', {
                    screen: 'DealDetail',
                    params: { id: deal.id },
                  })
                }
              >
                <View style={styles.dealHeader}>
                  <Text style={[styles.dealAddress, { color: theme.colors.text }]} numberOfLines={1}>
                    {deal.property_address}
                  </Text>
                  <View
                    style={[
                      styles.phaseBadge,
                      { backgroundColor: theme.colors.primary + '15' },
                    ]}
                  >
                    <Text style={[styles.phaseText, { color: theme.colors.primary }]}>
                      Phase {deal.phase}
                    </Text>
                  </View>
                </View>
                <View style={styles.dealMeta}>
                  <Text style={[styles.dealPrice, { color: theme.colors.accent }]}>
                    {formatCurrency(deal.price)}
                  </Text>
                  <Text style={[styles.dealType, { color: theme.colors.textSecondary }]}>
                    {deal.deal_type.toUpperCase()} • {deal.jurisdiction}
                  </Text>
                </View>
              </TouchableOpacity>
            ))}
          </>
        )}

        <View style={styles.bottomPad} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: {
    flex: 1,
  },
  scroll: {
    flex: 1,
  },
  syncBanner: {
    paddingVertical: 8,
    paddingHorizontal: 16,
    alignItems: 'center',
  },
  syncText: {
    color: '#FFF',
    fontWeight: '600',
    fontSize: 13,
  },
  quickActions: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 16,
    gap: 10,
  },
  quickBtn: {
    flex: 1,
    borderRadius: 12,
    paddingVertical: 14,
    alignItems: 'center',
  },
  quickIcon: {
    fontSize: 20,
    color: '#FFF',
    marginBottom: 4,
  },
  quickLabel: {
    color: '#FFF',
    fontSize: 11,
    fontWeight: '600',
  },
  kpiRow: {
    paddingHorizontal: 16,
    gap: 10,
    paddingBottom: 8,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingRight: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
    paddingHorizontal: 16,
    paddingTop: 20,
    paddingBottom: 10,
  },
  seeAll: {
    fontSize: 14,
    fontWeight: '600',
    paddingTop: 12,
  },
  dealCard: {
    marginHorizontal: 16,
    marginVertical: 4,
    borderRadius: 10,
    padding: 14,
  },
  dealHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  dealAddress: {
    fontSize: 15,
    fontWeight: '600',
    flex: 1,
    marginRight: 8,
  },
  phaseBadge: {
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: 6,
  },
  phaseText: {
    fontSize: 11,
    fontWeight: '700',
  },
  dealMeta: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 6,
  },
  dealPrice: {
    fontSize: 16,
    fontWeight: '700',
  },
  dealType: {
    fontSize: 12,
  },
  bottomPad: {
    height: 40,
  },
});
