import React, { useState } from 'react'
import {
  View, Text, TextInput, TouchableOpacity, ScrollView,
  StyleSheet, Alert, KeyboardAvoidingView, Platform,
} from 'react-native'
import { apiFetch } from '../lib/api'

const PRACTICE_AREAS = ['immigration','corporate','civil_litigation','property','family','employment','criminal','other']

export default function TimeEntryScreen() {
  const [form, setForm] = useState({
    clientFolderId: '',
    matterId:       '',
    attorney:       '',
    date:           new Date().toISOString().slice(0, 10),
    durationMinutes: '',
    ratePerHour:     '5000',
    description:     '',
    createdBy:       'Counsel',
  })
  const [saving, setSaving] = useState(false)
  const [saved, setSaved]   = useState(false)

  const hours = form.durationMinutes ? (parseFloat(form.durationMinutes) / 60).toFixed(2) : '—'
  const total = form.durationMinutes && form.ratePerHour
    ? new Intl.NumberFormat('th-TH', { maximumFractionDigits: 0 }).format((parseFloat(form.durationMinutes) / 60) * parseFloat(form.ratePerHour))
    : '—'

  async function save() {
    if (!form.clientFolderId || !form.durationMinutes || !form.description) {
      Alert.alert('Required', 'Fill in client folder ID, duration, and description')
      return
    }
    setSaving(true)
    try {
      await apiFetch('/time-entries', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          durationMinutes: parseInt(form.durationMinutes),
          ratePerHour:     parseFloat(form.ratePerHour),
          currency:        'THB',
        }),
      })
      setSaved(true)
      setForm(f => ({ ...f, description: '', durationMinutes: '' }))
      setTimeout(() => setSaved(false), 3000)
    } catch (e: any) {
      Alert.alert('Error', e.message ?? 'Failed to save time entry')
    } finally {
      setSaving(false)
    }
  }

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

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

        <View style={styles.preview}>
          <Text style={styles.previewText}>{hours}h × ฿{form.ratePerHour}/hr = <Text style={{ color: '#0D9394', fontWeight: '700' }}>฿{total}</Text></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}>Attorney</Text>
        <TextInput style={styles.input} value={form.attorney} onChangeText={v => setForm(f => ({ ...f, attorney: v }))} placeholder='Your name' placeholderTextColor='#9CA3AF' />

        <Text style={styles.label}>Date</Text>
        <TextInput style={styles.input} value={form.date} onChangeText={v => setForm(f => ({ ...f, date: v }))} placeholder='YYYY-MM-DD' placeholderTextColor='#9CA3AF' />

        <View style={styles.row}>
          <View style={{ flex: 1 }}>
            <Text style={styles.label}>Duration (mins)</Text>
            <TextInput style={styles.input} value={form.durationMinutes} onChangeText={v => setForm(f => ({ ...f, durationMinutes: v }))} keyboardType='numeric' placeholder='90' placeholderTextColor='#9CA3AF' />
          </View>
          <View style={{ width: 12 }} />
          <View style={{ flex: 1 }}>
            <Text style={styles.label}>Rate / hour (THB)</Text>
            <TextInput style={styles.input} value={form.ratePerHour} onChangeText={v => setForm(f => ({ ...f, ratePerHour: v }))} keyboardType='numeric' placeholder='5000' placeholderTextColor='#9CA3AF' />
          </View>
        </View>

        <Text style={styles.label}>Description</Text>
        <TextInput
          style={[styles.input, { height: 90, textAlignVertical: 'top' }]}
          value={form.description}
          onChangeText={v => setForm(f => ({ ...f, description: v }))}
          placeholder='Drafted affidavit for visa extension application…'
          placeholderTextColor='#9CA3AF'
          multiline
        />

        <TouchableOpacity style={[styles.btn, saving && styles.btnDisabled]} onPress={save} disabled={saving}>
          <Text style={styles.btnText}>{saving ? 'Saving…' : 'Save Time Entry'}</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 },
  preview:     { backgroundColor: '#E8F7F7', borderRadius: 10, padding: 12, marginBottom: 8, alignItems: 'center' },
  previewText: { fontSize: 14, color: '#374151' },
  savedBanner: { backgroundColor: '#EEFBE5', borderRadius: 10, padding: 12, marginBottom: 8, alignItems: 'center' },
  savedText:   { fontSize: 14, fontWeight: '600', color: '#71DD37' },
})
