/**
 * Deal pipeline — active deals organized by phase.
 * Paperless Pipeline replacement: visual deal board.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SectionList,
  TouchableOpacity,
  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 { getDeals, Deal } from '../../services/api';

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

const PHASE_NAMES: Record<number, string> = {
  0: 'Pre-Listing',
  1: 'Listed',
  2: 'Under Contract',
  3: 'Inspections',
  4: 'Appraisal',
  5: 'Loan Contingency',
  6: 'Title & Escrow',
  7: 'Final Walkthrough',
  8: 'Closing',
  9: 'Closed',
};

export default function Pipeline({ navigation }: Props) {
  const { theme } = useTheme();
  const [deals, setDeals] = useState<Deal[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [filter, setFilter] = useState<'active' | 'all'>('active');

  const loadDeals = useCallback(async () => {
    const params: Record<string, string> = {};
    if (filter === 'active') params.status = 'active';
    const res = await getDeals(params);
    if (res.success && res.data) {
      setDeals(res.data);
    }
  }, [filter]);

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

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

  // Group by phase
  const sections = Object.entries(
    deals.reduce<Record<number, Deal[]>>((acc, deal) => {
      const phase = deal.phase ?? 0;
      if (!acc[phase]) acc[phase] = [];
      acc[phase].push(deal);
      return acc;
    }, {})
  )
    .sort(([a], [b]) => Number(a) - Number(b))
    .map(([phase, data]) => ({
      title: PHASE_NAMES[Number(phase)] ?? `Phase ${phase}`,
      phase: Number(phase),
      data,
    }));

  const totalValue = deals.reduce((sum, d) => sum + (d.price || 0), 0);

  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()}`;
  };

  const phaseColor = (phase: number): string => {
    if (phase <= 1) return theme.colors.info;
    if (phase <= 4) return theme.colors.warning;
    if (phase <= 7) return theme.colors.accent;
    return theme.colors.success;
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      {/* Summary Bar */}
      <View style={[styles.summaryBar, { backgroundColor: theme.colors.card }]}>
        <View>
          <Text style={[styles.summaryLabel, { color: theme.colors.textSecondary }]}>Active Deals</Text>
          <Text style={[styles.summaryValue, { color: theme.colors.text }]}>{deals.length}</Text>
        </View>
        <View>
          <Text style={[styles.summaryLabel, { color: theme.colors.textSecondary }]}>Pipeline Value</Text>
          <Text style={[styles.summaryValue, { color: theme.colors.primary }]}>
            {formatCurrency(totalValue)}
          </Text>
        </View>
        <View style={styles.filterToggle}>
          {(['active', 'all'] as const).map((f) => (
            <TouchableOpacity
              key={f}
              style={[styles.filterChip, { backgroundColor: filter === f ? theme.colors.primary : theme.colors.inputBg }]}
              onPress={() => setFilter(f)}
            >
              <Text style={[styles.filterText, { color: filter === f ? '#FFF' : theme.colors.textSecondary }]}>
                {f === 'active' ? 'Active' : 'All'}
              </Text>
            </TouchableOpacity>
          ))}
        </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}>
            <View style={[styles.phaseDot, { backgroundColor: phaseColor(section.phase) }]} />
            <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>{section.title}</Text>
            <Text style={[styles.sectionCount, { color: theme.colors.textSecondary }]}>
              {section.data.length}
            </Text>
          </View>
        )}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={[styles.dealCard, theme.shadow.sm, { backgroundColor: theme.colors.card }]}
            onPress={() => navigation.navigate('DealDetail', { id: item.id })}
          >
            <View style={styles.dealTop}>
              <Text style={[styles.dealAddress, { color: theme.colors.text }]} numberOfLines={1}>
                {item.property_address}
              </Text>
              <Text style={[styles.dealPrice, { color: theme.colors.accent }]}>
                {formatCurrency(item.price)}
              </Text>
            </View>
            <View style={styles.dealBottom}>
              <View style={[styles.typeBadge, {
                backgroundColor: item.deal_type === 'buy' ? theme.colors.info + '20' :
                                 item.deal_type === 'sell' ? theme.colors.success + '20' :
                                 theme.colors.accent + '20',
              }]}>
                <Text style={[styles.typeText, {
                  color: item.deal_type === 'buy' ? theme.colors.info :
                         item.deal_type === 'sell' ? theme.colors.success :
                         theme.colors.accent,
                }]}>
                  {item.deal_type.toUpperCase()}
                </Text>
              </View>
              <Text style={[styles.jurisdiction, { color: theme.colors.textSecondary }]}>
                {item.jurisdiction}
              </Text>
              {item.close_date && (
                <Text style={[styles.closeDate, { color: theme.colors.textSecondary }]}>
                  Close: {new Date(item.close_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                </Text>
              )}
            </View>
          </TouchableOpacity>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No deals found</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  summaryBar: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 14,
    gap: 20,
  },
  summaryLabel: { fontSize: 11, fontWeight: '500' },
  summaryValue: { fontSize: 20, fontWeight: '800' },
  filterToggle: { flexDirection: 'row', marginLeft: 'auto', gap: 6 },
  filterChip: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 16 },
  filterText: { fontSize: 12, fontWeight: '600' },
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingTop: 16,
    paddingBottom: 6,
    gap: 8,
  },
  phaseDot: { width: 10, height: 10, borderRadius: 5 },
  sectionTitle: { fontSize: 15, fontWeight: '700' },
  sectionCount: { fontSize: 13 },
  dealCard: {
    marginHorizontal: 16,
    marginVertical: 4,
    borderRadius: 10,
    padding: 14,
  },
  dealTop: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  dealAddress: { fontSize: 15, fontWeight: '600', flex: 1, marginRight: 8 },
  dealPrice: { fontSize: 16, fontWeight: '700' },
  dealBottom: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
    gap: 10,
  },
  typeBadge: { paddingHorizontal: 8, paddingVertical: 3, borderRadius: 6 },
  typeText: { fontSize: 10, fontWeight: '700' },
  jurisdiction: { fontSize: 12 },
  closeDate: { fontSize: 12, marginLeft: 'auto' },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
