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

const CATEGORIES = [
  { value: 'court_filing',    label: 'Court Filing' },
  { value: 'translation',     label: 'Translation' },
  { value: 'notarization',    label: 'Notarization' },
  { value: 'travel',          label: 'Travel' },
  { value: 'accommodation',   label: 'Accommodation' },
  { value: 'courier',         label: 'Courier' },
  { value: 'printing',        label: 'Printing' },
  { value: 'government_fee',  label: 'Government Fee' },
  { value: 'expert_witness',  label: 'Expert Witness' },
  { value: 'other',           label: 'Other' },
]

export default function ExpenseScreen() {
  const [form, setForm] = useState({
    clientFolderId: '',
    matterId:       '',
    description:    '',
    category:       'other',
    amount:         '',
    expenseDate:    new Date().toISOString().slice(0, 10),
    billable:       true,
    notes:          '',
    createdBy:      'Counsel',
  })
  const [receiptUri, setReceiptUri] = useState<string | null>(null)
  const [saving, setSaving]         = useState(false)
  const [saved, setSaved]           = useState(false)
  const [catOpen, setCatOpen]       = useState(false)

  async function pickReceipt() {
    const perm = await ImagePicker.requestMediaLibraryPermissionsAsync()
    if (!perm.granted) { Alert.alert('Permission', 'Camera roll access is needed'); return }
    const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: 'images', quality: 0.8 })
    if (!result.canceled && result.assets[0]) setReceiptUri(result.assets[0].uri)
  }

  async function takePhoto() {
    const perm = await ImagePicker.requestCameraPermissionsAsync()
    if (!perm.granted) { Alert.alert('Permission', 'Camera access is needed'); return }
    const result = await ImagePicker.launchCameraAsync({ quality: 0.8 })
    if (!result.canceled && result.assets[0]) setReceiptUri(result.assets[0].uri)
  }

  async function save() {
    if (!form.clientFolderId || !form.amount || !form.description) {
      Alert.alert('Required', 'Fill in client folder ID, amount, and description')
      return
    }
    setSaving(true)
    try {
      // TODO: upload receiptUri to storage and get URL back
      await apiFetch('/expenses', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          amount:      parseFloat(form.amount),
          currency:    'THB',
          receiptUrl:  receiptUri ?? undefined,
        }),
      })
      setSaved(true)
      setForm(f => ({ ...f, description: '', amount: '', notes: '' }))
      setReceiptUri(null)
      setTimeout(() => setSaved(false), 3000)
    } catch (e: any) {
      Alert.alert('Error', e.message ?? 'Failed to save expense')
    } finally {
      setSaving(false)
    }
  }

  const selectedCat = CATEGORIES.find(c => c.value === form.category)

  return (
    <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={{ flex: 1 }}>
      <ScrollView style={styles.container} contentContainerStyle={{ paddingBottom: 40 }}>
        <Text style={styles.title}>Add Expense</Text>

        {saved && (
          <View style={styles.savedBanner}>
            <Text style={styles.savedText}>✅ Expense saved</Text>
          </View>
        )}

        <Text style={styles.label}>Client Folder ID</Text>
        <TextInput style={styles.input} value={form.clientFolderId} onChangeText={v => setForm(f => ({ ...f, clientFolderId: v }))} placeholder='CF-2026-0001' placeholderTextColor='#9CA3AF' autoCapitalize='characters' />

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

        <Text style={styles.label}>Description</Text>
        <TextInput style={styles.input} value={form.description} onChangeText={v => setForm(f => ({ ...f, description: v }))} placeholder='Court filing fee for MOI appeal' placeholderTextColor='#9CA3AF' />

        <View style={styles.row}>
          <View style={{ flex: 1 }}>
            <Text style={styles.label}>Amount (THB)</Text>
            <TextInput style={styles.input} value={form.amount} onChangeText={v => setForm(f => ({ ...f, amount: v }))} keyboardType='numeric' placeholder='2500' placeholderTextColor='#9CA3AF' />
          </View>
          <View style={{ width: 12 }} />
          <View style={{ flex: 1 }}>
            <Text style={styles.label}>Date</Text>
            <TextInput style={styles.input} value={form.expenseDate} onChangeText={v => setForm(f => ({ ...f, expenseDate: v }))} placeholder='YYYY-MM-DD' placeholderTextColor='#9CA3AF' />
          </View>
        </View>

        <Text style={styles.label}>Category</Text>
        <TouchableOpacity style={styles.select} onPress={() => setCatOpen(!catOpen)}>
          <Text style={styles.selectText}>{selectedCat?.label ?? 'Other'}</Text>
          <Text style={{ color: '#6B7280' }}>▾</Text>
        </TouchableOpacity>
        {catOpen && (
          <View style={styles.dropdown}>
            {CATEGORIES.map(c => (
              <TouchableOpacity
                key={c.value}
                style={[styles.dropdownItem, form.category === c.value && styles.dropdownItemActive]}
                onPress={() => { setForm(f => ({ ...f, category: c.value })); setCatOpen(false) }}
              >
                <Text style={[styles.dropdownText, form.category === c.value && { color: '#0D9394', fontWeight: '600' }]}>{c.label}</Text>
              </TouchableOpacity>
            ))}
          </View>
        )}

        <Text style={styles.label}>Billable to Client</Text>
        <View style={styles.toggleRow}>
          {['Yes', 'No'].map(opt => (
            <TouchableOpacity
              key={opt}
              style={[styles.toggleBtn, form.billable === (opt === 'Yes') && styles.toggleBtnActive]}
              onPress={() => setForm(f => ({ ...f, billable: opt === 'Yes' }))}
            >
              <Text style={[styles.toggleText, form.billable === (opt === 'Yes') && styles.toggleTextActive]}>{opt}</Text>
            </TouchableOpacity>
          ))}
        </View>

        {/* Receipt capture */}
        <Text style={styles.label}>Receipt</Text>
        {receiptUri ? (
          <View style={styles.receiptPreview}>
            <Image source={{ uri: receiptUri }} style={styles.receiptImage} />
            <TouchableOpacity style={styles.receiptClear} onPress={() => setReceiptUri(null)}>
              <Text style={styles.receiptClearText}>✕ Remove</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <View style={styles.receiptBtns}>
            <TouchableOpacity style={styles.receiptBtn} onPress={takePhoto}>
              <Text style={styles.receiptBtnIcon}>📷</Text>
              <Text style={styles.receiptBtnText}>Take Photo</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.receiptBtn} onPress={pickReceipt}>
              <Text style={styles.receiptBtnIcon}>🖼</Text>
              <Text style={styles.receiptBtnText}>From Gallery</Text>
            </TouchableOpacity>
          </View>
        )}

        <Text style={styles.label}>Notes (optional)</Text>
        <TextInput style={[styles.input, { height: 70, textAlignVertical: 'top' }]} value={form.notes} onChangeText={v => setForm(f => ({ ...f, notes: v }))} multiline placeholderTextColor='#9CA3AF' />

        <TouchableOpacity style={[styles.btn, saving && styles.btnDisabled]} onPress={save} disabled={saving}>
          <Text style={styles.btnText}>{saving ? 'Saving…' : 'Save Expense'}</Text>
        </TouchableOpacity>
      </ScrollView>
    </KeyboardAvoidingView>
  )
}

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' },
  row:                { flexDirection: 'row' },
  btn:                { backgroundColor: '#0D9394', borderRadius: 12, paddingVertical: 16, alignItems: 'center', marginTop: 24 },
  btnDisabled:        { opacity: 0.6 },
  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' },
  select:             { backgroundColor: '#fff', borderWidth: 1, borderColor: '#E5E7EB', borderRadius: 10, paddingHorizontal: 14, paddingVertical: 12, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  selectText:         { fontSize: 15, color: '#1A1A2E' },
  dropdown:           { backgroundColor: '#fff', borderWidth: 1, borderColor: '#E5E7EB', borderRadius: 10, marginTop: 4, overflow: 'hidden' },
  dropdownItem:       { paddingHorizontal: 14, paddingVertical: 11, borderBottomWidth: 1, borderBottomColor: '#F3F4F6' },
  dropdownItemActive: { backgroundColor: '#E8F7F7' },
  dropdownText:       { fontSize: 14, color: '#374151' },
  toggleRow:          { flexDirection: 'row', gap: 10 },
  toggleBtn:          { flex: 1, borderWidth: 1, borderColor: '#E5E7EB', borderRadius: 10, paddingVertical: 12, alignItems: 'center', backgroundColor: '#fff' },
  toggleBtnActive:    { borderColor: '#0D9394', backgroundColor: '#E8F7F7' },
  toggleText:         { fontSize: 14, color: '#6B7280' },
  toggleTextActive:   { color: '#0D9394', fontWeight: '700' },
  receiptBtns:        { flexDirection: 'row', gap: 10 },
  receiptBtn:         { flex: 1, backgroundColor: '#fff', borderWidth: 1, borderColor: '#E5E7EB', borderRadius: 10, padding: 14, alignItems: 'center' },
  receiptBtnIcon:     { fontSize: 24, marginBottom: 4 },
  receiptBtnText:     { fontSize: 12, color: '#374151', fontWeight: '500' },
  receiptPreview:     { borderRadius: 10, overflow: 'hidden', backgroundColor: '#F3F4F6' },
  receiptImage:       { width: '100%', height: 180, resizeMode: 'cover' },
  receiptClear:       { padding: 10, alignItems: 'center', backgroundColor: '#FFECEC' },
  receiptClearText:   { fontSize: 13, color: '#FF4C51', fontWeight: '600' },
})
