import React, { useCallback, useState } from 'react';
import { Alert, StyleSheet, Switch, Text, TouchableOpacity, View } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { ps } from '@/api/client';
import { useTheme } from '@/theme/ThemeContext';
import {
  clearLog,
  isFileLoggingEnabled,
  logStats,
  setFileLogging,
  shareLog,
} from '@/features/diagnostics/fileLogger';

export function DiagnosticsScreen() {
  const { colors } = useTheme();
  const [on, setOn] = useState(false);
  const [lines, setLines] = useState(0);

  useFocusEffect(
    useCallback(() => {
      setOn(isFileLoggingEnabled());
      setLines(logStats().lines);
    }, []),
  );

  const toggle = async (v: boolean) => {
    setOn(v);
    await setFileLogging(v);
    ps.setLogRequests(v);
    setLines(logStats().lines);
  };

  return (
    <View style={[styles.container, { backgroundColor: colors.bg }]}>
      <View style={[styles.card, { backgroundColor: colors.card }]}>
        <View style={styles.row}>
          <View style={{ flex: 1 }}>
            <Text style={[styles.title, { color: colors.text }]}>Record debug log</Text>
            <Text style={[styles.sub, { color: colors.subtext }]}>
              Saves API requests/responses and app events to a file on this device.
              Sensitive values (tokens, card numbers) are redacted.
            </Text>
          </View>
          <Switch value={on} onValueChange={toggle} />
        </View>
      </View>

      <Text style={[styles.count, { color: colors.subtext }]}>
        {lines} line{lines === 1 ? '' : 's'} captured
      </Text>

      <TouchableOpacity
        style={[styles.btn, { backgroundColor: colors.primary }]}
        onPress={() => shareLog().catch((e) => Alert.alert('Share failed', String(e?.message ?? e)))}
      >
        <Text style={styles.btnText}>Share log file</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={[styles.btn, { backgroundColor: colors.card, borderWidth: 1, borderColor: colors.border }]}
        onPress={() =>
          Alert.alert('Clear log?', 'Deletes the captured log.', [
            { text: 'Cancel', style: 'cancel' },
            {
              text: 'Clear',
              style: 'destructive',
              onPress: async () => {
                await clearLog();
                setLines(0);
              },
            },
          ])
        }
      >
        <Text style={[styles.btnText, { color: colors.text }]}>Clear log</Text>
      </TouchableOpacity>

      <Text style={[styles.note, { color: colors.subtext }]}>
        Turn this on before heading out, do your parking session, then come back and
        “Share log file” to send it to yourself. It persists across app restarts.
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16 },
  card: { borderRadius: 12, padding: 16 },
  row: { flexDirection: 'row', alignItems: 'center' },
  title: { fontSize: 16, fontWeight: '600' },
  sub: { fontSize: 13, marginTop: 4, lineHeight: 18 },
  count: { fontSize: 13, marginTop: 16, marginLeft: 4 },
  btn: { borderRadius: 12, padding: 16, alignItems: 'center', marginTop: 12 },
  btnText: { color: '#fff', fontWeight: '700', fontSize: 16 },
  note: { fontSize: 12, marginTop: 20, lineHeight: 18 },
});
