import React, { useState, useCallback } from 'react'
import { View, Text, FlatList, Modal, TouchableOpacity, StyleSheet, RefreshControl } from 'react-native'
import { router, useFocusEffect } from 'expo-router'
import { COLORS } from '../../constants/Config'
import { getMeetingMinutes } from '../../services/api'
import MarkdownViewer from '../../components/MarkdownViewer'

export default function MeetingMinutesScreen() {
  const [items, setItems]   = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [detail, setDetail] = useState<any>(null)

  const load = useCallback(async () => {
    setLoading(true)
    try { const r = await getMeetingMinutes(); setItems(r.data?.items ?? r.data ?? []) }
    catch { setItems([]) }
    finally { setLoading(false) }
  }, [])

  useFocusEffect(useCallback(() => { load() }, [load]))

  return (
    <View style={s.container}>
      <FlatList
        data={items}
        keyExtractor={(_, i) => String(i)}
        refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
        ListEmptyComponent={<Text style={s.empty}>회의록이 없습니다.</Text>}
        contentContainerStyle={{ padding: 12 }}
        renderItem={({ item }) => (
          <TouchableOpacity style={s.card} onPress={() => setDetail(item)}>
            <Text style={s.title}>{item.title ?? item.subject ?? '회의록'}</Text>
            <Text style={s.meta}>{item.meeting_date?.slice(0, 10) ?? item.created_at?.slice(0, 10)} · {(item.attendees ?? []).join(', ')}</Text>
            {(item.action_items ?? []).length > 0 && (
              <Text style={s.actions}>액션 아이템 {item.action_items.length}개</Text>
            )}
          </TouchableOpacity>
        )}
      />

      <Modal visible={!!detail} animationType="slide">
        <View style={s.modalContainer}>
          <View style={s.modalHeader}>
            <TouchableOpacity onPress={() => setDetail(null)}><Text style={s.back}>← 닫기</Text></TouchableOpacity>
            {(detail?.action_items ?? []).length > 0 && (
              <TouchableOpacity onPress={() => { setDetail(null); router.push('/(tabs)/meeting_sr') }}>
                <Text style={s.srBtn}>SR 등록</Text>
              </TouchableOpacity>
            )}
          </View>
          <Text style={s.modalTitle}>{detail?.title ?? '회의록'}</Text>
          <MarkdownViewer content={detail?.content ?? detail?.summary ?? ''} style={{ flex: 1, padding: 16 }} />
        </View>
      </Modal>
    </View>
  )
}

const s = StyleSheet.create({
  container:      { flex: 1, backgroundColor: COLORS.bg },
  card:           { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  title:          { fontSize: 14, fontWeight: '700', color: COLORS.text, marginBottom: 4 },
  meta:           { fontSize: 12, color: COLORS.muted },
  actions:        { fontSize: 12, color: COLORS.accent, marginTop: 4, fontWeight: '600' },
  empty:          { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
  modalContainer: { flex: 1, backgroundColor: '#fff' },
  modalHeader:    { flexDirection: 'row', justifyContent: 'space-between', padding: 16, borderBottomWidth: 1, borderBottomColor: COLORS.border },
  back:           { fontSize: 15, color: COLORS.accent, fontWeight: '600' },
  srBtn:          { fontSize: 15, color: COLORS.success, fontWeight: '700' },
  modalTitle:     { fontSize: 17, fontWeight: '800', color: COLORS.text, padding: 16, paddingBottom: 0 },
})
