/**
 * Document list — files per deal, upload, review status.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as DocumentPicker from 'expo-document-picker';
import { useTheme } from '../../themes/ThemeProvider';
import { getDocuments, uploadDocument, Document as DocType } from '../../services/api';

export default function DocList({ route, navigation }: any) {
  const { theme } = useTheme();
  const dealId = route.params?.deal_id;
  const [docs, setDocs] = useState<DocType[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const params: Record<string, string> = {};
    if (dealId) params.deal_id = String(dealId);
    const res = await getDocuments(params);
    if (res.success && res.data) setDocs(res.data);
  }, [dealId]);

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

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

  const handleUpload = async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: ['application/pdf', 'image/*'],
        copyToCacheDirectory: true,
      });

      if (result.canceled || !result.assets?.[0]) return;

      const file = result.assets[0];
      const formData = new FormData();
      formData.append('file', {
        uri: file.uri,
        name: file.name,
        type: file.mimeType ?? 'application/pdf',
      } as any);
      if (dealId) formData.append('deal_id', String(dealId));

      const res = await uploadDocument(formData);
      if (res.success) {
        await load();
      } else {
        Alert.alert('Upload Failed', res.error ?? 'Could not upload document');
      }
    } catch {
      Alert.alert('Error', 'Document picker failed');
    }
  };

  const statusConfig: Record<string, { color: string; label: string }> = {
    draft: { color: '#6B7280', label: 'Draft' },
    pending_review: { color: '#F59E0B', label: 'Pending' },
    approved: { color: '#10B981', label: 'Approved' },
    signed: { color: '#3B82F6', label: 'Signed' },
  };

  const fileIcon = (type: string): string => {
    if (type.includes('pdf')) return '📄';
    if (type.includes('image')) return '🖼';
    if (type.includes('word') || type.includes('doc')) return '📝';
    return '📁';
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <View style={[styles.toolbar, { backgroundColor: theme.colors.surface }]}>
        <Text style={[styles.count, { color: theme.colors.textSecondary }]}>
          {docs.length} document{docs.length !== 1 ? 's' : ''}
        </Text>
        <TouchableOpacity
          style={[styles.uploadBtn, { backgroundColor: theme.colors.primary }]}
          onPress={handleUpload}
        >
          <Text style={styles.uploadBtnText}>Upload</Text>
        </TouchableOpacity>
      </View>

      <FlatList
        data={docs}
        keyExtractor={(item) => String(item.id)}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderItem={({ item }) => {
          const config = statusConfig[item.status] ?? statusConfig.draft;
          return (
            <TouchableOpacity
              style={[styles.docRow, { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border }]}
              onPress={() => {
                if (item.status === 'approved') {
                  navigation.navigate('SignDocument', { envelopeId: item.id });
                }
              }}
            >
              <Text style={styles.icon}>{fileIcon(item.file_type)}</Text>
              <View style={styles.docInfo}>
                <Text style={[styles.filename, { color: theme.colors.text }]} numberOfLines={1}>
                  {item.filename}
                </Text>
                <Text style={[styles.docMeta, { color: theme.colors.textSecondary }]}>
                  v{item.version} • {(item.file_size / 1024).toFixed(0)}KB •{' '}
                  {new Date(item.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                </Text>
              </View>
              <View style={[styles.statusBadge, { backgroundColor: config.color + '20' }]}>
                <Text style={[styles.statusText, { color: config.color }]}>{config.label}</Text>
              </View>
            </TouchableOpacity>
          );
        }}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No documents yet</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  toolbar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
  },
  count: { fontSize: 13 },
  uploadBtn: { paddingHorizontal: 16, paddingVertical: 8, borderRadius: 8 },
  uploadBtnText: { color: '#FFF', fontWeight: '700', fontSize: 14 },
  docRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  icon: { fontSize: 24, marginRight: 12 },
  docInfo: { flex: 1 },
  filename: { fontSize: 15, fontWeight: '500' },
  docMeta: { fontSize: 12, marginTop: 2 },
  statusBadge: { paddingHorizontal: 10, paddingVertical: 4, borderRadius: 8 },
  statusText: { fontSize: 11, fontWeight: '700' },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15 },
});
