import React, { useState } from 'react'
import {
  View, Text, TouchableOpacity, ScrollView,
  StyleSheet, Alert, Image, TextInput,
} from 'react-native'
import * as ImagePicker from 'expo-image-picker'
import * as DocumentPicker from 'expo-document-picker'
import { apiFetch } from '../lib/api'

interface ScannedDoc {
  uri: string
  name: string
  type: 'photo' | 'file'
}

export default function DocumentScanScreen() {
  const [docs, setDocs]           = useState<ScannedDoc[]>([])
  const [clientFolderId, setClientFolderId] = useState('')
  const [matterId, setMatterId]   = useState('')
  const [title, setTitle]         = useState('')
  const [uploading, setUploading] = useState(false)
  const [uploaded, setUploaded]   = useState(false)

  async function scanWithCamera() {
    const perm = await ImagePicker.requestCameraPermissionsAsync()
    if (!perm.granted) { Alert.alert('Permission', 'Camera access is needed'); return }
    const result = await ImagePicker.launchCameraAsync({ quality: 0.85 })
    if (!result.canceled && result.assets[0]) {
      const asset = result.assets[0]
      setDocs(d => [...d, { uri: asset.uri, name: `scan_${Date.now()}.jpg`, type: 'photo' }])
    }
  }

  async function pickFromGallery() {
    const perm = await ImagePicker.requestMediaLibraryPermissionsAsync()
    if (!perm.granted) { Alert.alert('Permission', 'Camera roll access is needed'); return }
    const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: 'images', allowsMultipleSelection: true, quality: 0.85 })
    if (!result.canceled) {
      const newDocs = result.assets.map(a => ({ uri: a.uri, name: a.fileName ?? `img_${Date.now()}.jpg`, type: 'photo' as const }))
      setDocs(d => [...d, ...newDocs])
    }
  }

  async function pickDocument() {
    const result = await DocumentPicker.getDocumentAsync({ type: '*/*', multiple: true })
    if (!result.canceled) {
      const newDocs = result.assets.map(a => ({ uri: a.uri, name: a.name, type: 'file' as const }))
      setDocs(d => [...d, ...newDocs])
    }
  }

  function removeDoc(idx: number) {
    setDocs(d => d.filter((_, i) => i !== idx))
  }

  async function upload() {
    if (!clientFolderId || !title || !docs.length) {
      Alert.alert('Required', 'Client ID, title, and at least one document are required')
      return
    }
    setUploading(true)
    try {
      // POST each document as a metadata entry; in production, upload to object storage first
      for (const doc of docs) {
        await apiFetch('/documents', {
          method: 'POST',
          body: JSON.stringify({
            clientFolderId,
            matterId:     matterId || undefined,
            title:        title || doc.name,
            fileName:     doc.name,
            fileUrl:      doc.uri,   // TODO: replace with actual upload URL
            fileSize:     0,
            mimeType:     doc.type === 'photo' ? 'image/jpeg' : 'application/octet-stream',
            privilege:    'non_privileged',
            uploadedBy:   'Counsel',
          }),
        })
      }
      setUploaded(true)
      setDocs([])
      setTitle('')
      setTimeout(() => setUploaded(false), 3000)
    } catch (e: any) {
      Alert.alert('Error', e.message ?? 'Upload failed')
    } finally {
      setUploading(false)
    }
  }

  return (
    <ScrollView style={styles.container} contentContainerStyle={{ paddingBottom: 40 }}>
      <Text style={styles.title}>Scan & Upload Documents</Text>

      {uploaded && (
        <View style={styles.savedBanner}>
          <Text style={styles.savedText}>✅ Documents uploaded successfully</Text>
        </View>
      )}

      <Text style={styles.label}>Client Folder ID</Text>
      <TextInput style={styles.input} value={clientFolderId} onChangeText={setClientFolderId} placeholder='CF-2026-0001' placeholderTextColor='#9CA3AF' autoCapitalize='characters' />

      <Text style={styles.label}>Matter ID (optional)</Text>
      <TextInput style={styles.input} value={matterId} onChangeText={setMatterId} placeholder='MT-2026-0001' placeholderTextColor='#9CA3AF' autoCapitalize='characters' />

      <Text style={styles.label}>Document Title</Text>
      <TextInput style={styles.input} value={title} onChangeText={setTitle} placeholder='Visa Extension Application — 2026' placeholderTextColor='#9CA3AF' />

      <Text style={styles.label}>Documents ({docs.length})</Text>

      {docs.length > 0 && (
        <View style={styles.docList}>
          {docs.map((doc, i) => (
            <View key={i} style={styles.docItem}>
              {doc.type === 'photo' ? (
                <Image source={{ uri: doc.uri }} style={styles.docThumb} />
              ) : (
                <View style={styles.docIcon}>
                  <Text style={{ fontSize: 22 }}>📄</Text>
                </View>
              )}
              <Text style={styles.docName} numberOfLines={1}>{doc.name}</Text>
              <TouchableOpacity onPress={() => removeDoc(i)} style={styles.docRemove}>
                <Text style={styles.docRemoveText}>✕</Text>
              </TouchableOpacity>
            </View>
          ))}
        </View>
      )}

      <View style={styles.captureRow}>
        <TouchableOpacity style={styles.captureBtn} onPress={scanWithCamera}>
          <Text style={styles.captureBtnIcon}>📷</Text>
          <Text style={styles.captureBtnText}>Camera</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.captureBtn} onPress={pickFromGallery}>
          <Text style={styles.captureBtnIcon}>🖼</Text>
          <Text style={styles.captureBtnText}>Gallery</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.captureBtn} onPress={pickDocument}>
          <Text style={styles.captureBtnIcon}>📂</Text>
          <Text style={styles.captureBtnText}>Files</Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={[styles.btn, (uploading || !docs.length) && styles.btnDisabled]} onPress={upload} disabled={uploading || !docs.length}>
        <Text style={styles.btnText}>{uploading ? 'Uploading…' : `Upload ${docs.length} Document${docs.length !== 1 ? 's' : ''}`}</Text>
      </TouchableOpacity>
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  container:      { flex: 1, backgroundColor: '#F9FAFB', padding: 16 },
  title:          { fontSize: 20, fontWeight: '700', color: '#1A1A2E', marginBottom: 16 },
  label:          { fontSize: 12, fontWeight: '600', color: '#6B7280', marginBottom: 4, marginTop: 12, letterSpacing: 0.3 },
  input:          { backgroundColor: '#fff', borderWidth: 1, borderColor: '#E5E7EB', borderRadius: 10, paddingHorizontal: 14, paddingVertical: 12, fontSize: 15, color: '#1A1A2E' },
  btn:            { backgroundColor: '#0D9394', borderRadius: 12, paddingVertical: 16, alignItems: 'center', marginTop: 24 },
  btnDisabled:    { opacity: 0.5 },
  btnText:        { color: '#fff', fontWeight: '700', fontSize: 16 },
  savedBanner:    { backgroundColor: '#EEFBE5', borderRadius: 10, padding: 12, marginBottom: 8, alignItems: 'center' },
  savedText:      { fontSize: 14, fontWeight: '600', color: '#71DD37' },
  captureRow:     { flexDirection: 'row', gap: 10, marginTop: 8 },
  captureBtn:     { flex: 1, backgroundColor: '#fff', borderWidth: 1, borderColor: '#E5E7EB', borderRadius: 10, padding: 14, alignItems: 'center' },
  captureBtnIcon: { fontSize: 24, marginBottom: 4 },
  captureBtnText: { fontSize: 12, color: '#374151', fontWeight: '500' },
  docList:        { gap: 8, marginBottom: 4 },
  docItem:        { flexDirection: 'row', alignItems: 'center', backgroundColor: '#fff', borderRadius: 10, padding: 10, borderWidth: 1, borderColor: '#E5E7EB', gap: 10 },
  docThumb:       { width: 44, height: 44, borderRadius: 6, resizeMode: 'cover' },
  docIcon:        { width: 44, height: 44, borderRadius: 6, backgroundColor: '#F3F4F6', alignItems: 'center', justifyContent: 'center' },
  docName:        { flex: 1, fontSize: 13, color: '#374151' },
  docRemove:      { padding: 4 },
  docRemoveText:  { color: '#FF4C51', fontWeight: '700', fontSize: 15 },
})
