/**
 * TC task list — transaction coordinator checklist.
 * Grouped by phase with completion tracking.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SectionList,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { DealsStackParamList } from '../../navigation/stacks/DealsStack';
import { useTheme } from '../../themes/ThemeProvider';
import TaskItem, { Task } from '../../components/TaskItem';
import { getDealTasks, updateTask } from '../../services/api';

type Props = NativeStackScreenProps<DealsStackParamList, 'TransactionTC'>;

export default function TransactionTC({ route }: Props) {
  const { theme } = useTheme();
  const { dealId } = route.params;
  const [tasks, setTasks] = useState<Task[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const res = await getDealTasks(dealId);
    if (res.success && res.data) {
      setTasks(res.data as Task[]);
    }
  }, [dealId]);

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

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

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

  // Group by phase
  const sections = Object.entries(
    tasks.reduce<Record<number, Task[]>>((acc, task) => {
      const phase = task.phase ?? 0;
      if (!acc[phase]) acc[phase] = [];
      acc[phase].push(task);
      return acc;
    }, {})
  )
    .sort(([a], [b]) => Number(a) - Number(b))
    .map(([phase, data]) => ({
      title: `Phase ${phase}`,
      data,
      completed: data.filter((t) => t.status === 'completed').length,
      total: data.length,
    }));

  const totalCompleted = tasks.filter((t) => t.status === 'completed').length;

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      {/* Overall Progress */}
      <View style={[styles.progressSection, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.progressTitle, { color: theme.colors.text }]}>
          TC Checklist Progress
        </Text>
        <View style={styles.progressInfo}>
          <Text style={[styles.progressPercent, { color: theme.colors.primary }]}>
            {tasks.length > 0 ? Math.round((totalCompleted / tasks.length) * 100) : 0}%
          </Text>
          <Text style={[styles.progressCount, { color: theme.colors.textSecondary }]}>
            {totalCompleted} of {tasks.length} tasks complete
          </Text>
        </View>
        <View style={[styles.progressBar, { backgroundColor: theme.colors.border }]}>
          <View
            style={[
              styles.progressFill,
              {
                width: tasks.length > 0 ? `${(totalCompleted / tasks.length) * 100}%` : '0%',
                backgroundColor: theme.colors.success,
              },
            ]}
          />
        </View>
      </View>

      <SectionList
        sections={sections}
        keyExtractor={(item) => String(item.id)}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderSectionHeader={({ section }) => (
          <View style={[styles.sectionHeader, { backgroundColor: theme.colors.background }]}>
            <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>
              {section.title}
            </Text>
            <Text style={[styles.sectionProgress, { color: theme.colors.textSecondary }]}>
              {section.completed}/{section.total}
            </Text>
          </View>
        )}
        renderItem={({ item }) => (
          <TaskItem task={item} onToggle={handleToggle} onPress={() => {}} />
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              No tasks for this deal
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  progressSection: { padding: 16 },
  progressTitle: { fontSize: 16, fontWeight: '700', marginBottom: 8 },
  progressInfo: { flexDirection: 'row', alignItems: 'baseline', gap: 8, marginBottom: 8 },
  progressPercent: { fontSize: 28, fontWeight: '800' },
  progressCount: { fontSize: 13 },
  progressBar: { height: 8, borderRadius: 4, overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 4 },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 10,
  },
  sectionTitle: { fontSize: 15, fontWeight: '700' },
  sectionProgress: { fontSize: 13 },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
