/**
 * My Goals — personal pacing dashboard.
 * Sisu replacement: goal tracking with visual pacing indicators.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import { getAgentGoals, getAgentPacing } from '../../services/api';
import { getStoredUser } from '../../services/auth';

interface Goal {
  id: number;
  metric: string;
  target: number;
  current: number;
  unit: string;
  period: 'monthly' | 'quarterly' | 'annual';
}

interface PacingData {
  days_elapsed: number;
  days_in_period: number;
  expected_pct: number;
  actual_pct: number;
  on_pace: boolean;
}

export default function MyGoals() {
  const { theme } = useTheme();
  const [goals, setGoals] = useState<Goal[]>([]);
  const [pacing, setPacing] = useState<PacingData | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const user = await getStoredUser();
    if (!user) return;
    const [goalsRes, pacingRes] = await Promise.allSettled([
      getAgentGoals(user.id),
      getAgentPacing(user.id),
    ]);
    if (goalsRes.status === 'fulfilled' && goalsRes.value.data) setGoals(goalsRes.value.data as Goal[]);
    if (pacingRes.status === 'fulfilled' && pacingRes.value.data) setPacing(pacingRes.value.data as PacingData);
  }, []);

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

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

  const progressColor = (current: number, target: number, expectedPct: number): string => {
    const pct = target > 0 ? current / target : 0;
    if (pct >= expectedPct) return theme.colors.success;
    if (pct >= expectedPct * 0.8) return theme.colors.warning;
    return theme.colors.error;
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <ScrollView
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />}
      >
        {/* Pacing Overview */}
        {pacing && (
          <View style={[styles.pacingCard, theme.shadow.md, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.pacingTitle, { color: theme.colors.text }]}>Overall Pacing</Text>
            <View style={styles.pacingVisual}>
              <View style={[styles.pacingCircle, {
                borderColor: pacing.on_pace ? theme.colors.success : theme.colors.error,
              }]}>
                <Text style={[styles.pacingPct, { color: pacing.on_pace ? theme.colors.success : theme.colors.error }]}>
                  {Math.round(pacing.actual_pct * 100)}%
                </Text>
                <Text style={[styles.pacingLabel, { color: theme.colors.textSecondary }]}>actual</Text>
              </View>
              <View style={styles.pacingInfo}>
                <Text style={[styles.pacingExpected, { color: theme.colors.textSecondary }]}>
                  Expected: {Math.round(pacing.expected_pct * 100)}%
                </Text>
                <Text style={[styles.pacingDays, { color: theme.colors.textSecondary }]}>
                  Day {pacing.days_elapsed} of {pacing.days_in_period}
                </Text>
                <View style={[styles.pacingStatus, {
                  backgroundColor: pacing.on_pace ? theme.colors.success + '20' : theme.colors.error + '20',
                }]}>
                  <Text style={[styles.pacingStatusText, {
                    color: pacing.on_pace ? theme.colors.success : theme.colors.error,
                  }]}>
                    {pacing.on_pace ? 'ON PACE' : 'BEHIND PACE'}
                  </Text>
                </View>
              </View>
            </View>
          </View>
        )}

        {/* Individual Goals */}
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Goals</Text>
        {goals.map((goal) => {
          const pct = goal.target > 0 ? goal.current / goal.target : 0;
          const expectedPct = pacing?.expected_pct ?? 0;
          const color = progressColor(goal.current, goal.target, expectedPct);

          return (
            <View key={goal.id} style={[styles.goalCard, theme.shadow.sm, { backgroundColor: theme.colors.card }]}>
              <View style={styles.goalHeader}>
                <Text style={[styles.goalMetric, { color: theme.colors.text }]}>{goal.metric}</Text>
                <Text style={[styles.goalPeriod, { color: theme.colors.textSecondary }]}>
                  {goal.period}
                </Text>
              </View>
              <View style={styles.goalProgress}>
                <Text style={[styles.goalCurrent, { color }]}>
                  {goal.unit === '$' ? `$${goal.current.toLocaleString()}` : goal.current}
                </Text>
                <Text style={[styles.goalTarget, { color: theme.colors.textSecondary }]}>
                  / {goal.unit === '$' ? `$${goal.target.toLocaleString()}` : goal.target}
                </Text>
              </View>
              <View style={[styles.goalBar, { backgroundColor: theme.colors.border }]}>
                <View style={[styles.goalFill, { width: `${Math.min(pct * 100, 100)}%`, backgroundColor: color }]} />
                {expectedPct > 0 && (
                  <View style={[styles.expectedMarker, { left: `${Math.min(expectedPct * 100, 100)}%` }]} />
                )}
              </View>
              <Text style={[styles.goalPct, { color }]}>
                {Math.round(pct * 100)}% complete
              </Text>
            </View>
          );
        })}

        {goals.length === 0 && (
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              No goals set. Contact your admin to set targets.
            </Text>
          </View>
        )}

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

const styles = StyleSheet.create({
  safe: { flex: 1 },
  pacingCard: { margin: 16, borderRadius: 14, padding: 20 },
  pacingTitle: { fontSize: 18, fontWeight: '700', marginBottom: 16 },
  pacingVisual: { flexDirection: 'row', alignItems: 'center', gap: 20 },
  pacingCircle: {
    width: 90,
    height: 90,
    borderRadius: 45,
    borderWidth: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  pacingPct: { fontSize: 24, fontWeight: '800' },
  pacingLabel: { fontSize: 11 },
  pacingInfo: { flex: 1, gap: 6 },
  pacingExpected: { fontSize: 14 },
  pacingDays: { fontSize: 13 },
  pacingStatus: { paddingHorizontal: 12, paddingVertical: 4, borderRadius: 8, alignSelf: 'flex-start' },
  pacingStatusText: { fontSize: 12, fontWeight: '700' },
  sectionTitle: { fontSize: 18, fontWeight: '700', paddingHorizontal: 16, paddingTop: 12, paddingBottom: 8 },
  goalCard: { marginHorizontal: 16, marginVertical: 6, borderRadius: 12, padding: 16 },
  goalHeader: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 8 },
  goalMetric: { fontSize: 15, fontWeight: '600' },
  goalPeriod: { fontSize: 12, textTransform: 'capitalize' },
  goalProgress: { flexDirection: 'row', alignItems: 'baseline', marginBottom: 8 },
  goalCurrent: { fontSize: 22, fontWeight: '800' },
  goalTarget: { fontSize: 14, marginLeft: 4 },
  goalBar: { height: 8, borderRadius: 4, overflow: 'hidden', position: 'relative' },
  goalFill: { height: '100%', borderRadius: 4 },
  expectedMarker: { position: 'absolute', top: -2, width: 2, height: 12, backgroundColor: '#333' },
  goalPct: { fontSize: 12, fontWeight: '600', marginTop: 6 },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 14, textAlign: 'center' },
  bottomPad: { height: 40 },
});
