import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { BASE_URL, setBaseUrl } from '../api/client';

export function SettingsScreen(): React.JSX.Element {
  const [url, setUrl] = useState<string>(BASE_URL);
  const [saved, setSaved] = useState<boolean>(false);
  const [validationError, setValidationError] = useState<string | null>(null);

  function handleSave(): void {
    const trimmed = url.trim();
    if (!trimmed) {
      setValidationError('URL cannot be empty');
      return;
    }
    try {
      new URL(trimmed);
    } catch {
      setValidationError('Enter a valid URL (e.g. http://192.168.1.10:8080)');
      return;
    }
    setValidationError(null);
    setBaseUrl(trimmed);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  function handleReset(): void {
    const defaultUrl = 'http://localhost:8080';
    setUrl(defaultUrl);
    setBaseUrl(defaultUrl);
    setValidationError(null);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  return (
    <KeyboardAvoidingView
      style={styles.flex}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        style={styles.scroll}
        contentContainerStyle={styles.content}
        keyboardShouldPersistTaps="handled"
      >
        {/* Proxy URL */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Proxy Configuration</Text>
          <Text style={styles.label}>Base URL</Text>
          <Text style={styles.sublabel}>
            Current: <Text style={styles.urlText}>{BASE_URL}</Text>
          </Text>
          <TextInput
            style={[styles.input, validationError ? styles.inputError : null]}
            value={url}
            onChangeText={(t) => {
              setUrl(t);
              setValidationError(null);
              setSaved(false);
            }}
            placeholder="http://localhost:8080"
            placeholderTextColor="#4b5563"
            autoCapitalize="none"
            autoCorrect={false}
            keyboardType="url"
            returnKeyType="done"
            onSubmitEditing={handleSave}
          />
          {validationError ? (
            <Text style={styles.errorText}>{validationError}</Text>
          ) : null}

          <View style={styles.btnRow}>
            <TouchableOpacity
              style={[styles.saveBtn, saved && styles.saveBtnSuccess]}
              onPress={handleSave}
              activeOpacity={0.8}
            >
              <Text style={styles.saveBtnText}>{saved ? '✓ Saved' : 'Save'}</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.resetBtn}
              onPress={handleReset}
              activeOpacity={0.8}
            >
              <Text style={styles.resetBtnText}>Reset to default</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* ROI Calculator link */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Tools</Text>
          <View style={styles.linkRow}>
            <Text style={styles.linkIcon}>📈</Text>
            <View style={styles.linkInfo}>
              <Text style={styles.linkTitle}>ROI Calculator</Text>
              <Text style={styles.linkUrl}>{BASE_URL}/bibividi/roi</Text>
              <Text style={styles.linkNote}>
                Open this URL in a browser to use the interactive ROI calculator.
              </Text>
            </View>
          </View>
        </View>

        {/* About */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>About</Text>
          <Text style={styles.aboutText}>
            BIBIVIDI is an AI token optimization proxy. It sits between your app and AI APIs
            (Anthropic, OpenAI, etc.), intercepts requests, and executes matching BSS skill
            scripts locally to produce condensed context — reducing token usage by 60–95%.
          </Text>
          <View style={styles.metaRow}>
            <Text style={styles.metaLabel}>App version</Text>
            <Text style={styles.metaValue}>1.0.0</Text>
          </View>
          <View style={styles.metaRow}>
            <Text style={styles.metaLabel}>Protocol</Text>
            <Text style={styles.metaValue}>BSS v1.1</Text>
          </View>
          <View style={styles.metaRow}>
            <Text style={styles.metaLabel}>Default port</Text>
            <Text style={styles.metaValue}>8080 (HTTP) · 8443 (HTTPS)</Text>
          </View>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
    backgroundColor: '#0f1117',
  },
  scroll: {
    flex: 1,
    backgroundColor: '#0f1117',
  },
  content: {
    padding: 16,
    paddingBottom: 40,
    gap: 16,
  },
  section: {
    backgroundColor: '#1a1d27',
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#2a2d3a',
    padding: 16,
    marginBottom: 8,
  },
  sectionTitle: {
    color: '#6b7280',
    fontSize: 10,
    textTransform: 'uppercase',
    letterSpacing: 1,
    fontWeight: '700',
    marginBottom: 14,
  },
  label: {
    color: '#c9cdd8',
    fontSize: 14,
    fontWeight: '600',
    marginBottom: 4,
  },
  sublabel: {
    color: '#6b7280',
    fontSize: 12,
    marginBottom: 10,
  },
  urlText: {
    color: '#7c3aed',
    fontFamily: 'monospace',
  },
  input: {
    backgroundColor: '#0f1117',
    borderWidth: 1,
    borderColor: '#2a2d3a',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 10,
    color: '#c9cdd8',
    fontSize: 14,
    fontFamily: 'monospace',
  },
  inputError: {
    borderColor: '#ef4444',
  },
  errorText: {
    color: '#ef4444',
    fontSize: 12,
    marginTop: 6,
  },
  btnRow: {
    flexDirection: 'row',
    gap: 10,
    marginTop: 12,
  },
  saveBtn: {
    backgroundColor: '#7c3aed',
    borderRadius: 8,
    paddingHorizontal: 20,
    paddingVertical: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  saveBtnSuccess: {
    backgroundColor: '#16a34a',
  },
  saveBtnText: {
    color: '#ffffff',
    fontWeight: '700',
    fontSize: 14,
  },
  resetBtn: {
    borderRadius: 8,
    paddingHorizontal: 16,
    paddingVertical: 10,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: '#2a2d3a',
  },
  resetBtnText: {
    color: '#6b7280',
    fontSize: 13,
  },
  linkRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: 12,
  },
  linkIcon: {
    fontSize: 24,
    marginTop: 2,
  },
  linkInfo: {
    flex: 1,
  },
  linkTitle: {
    color: '#c9cdd8',
    fontSize: 14,
    fontWeight: '600',
    marginBottom: 2,
  },
  linkUrl: {
    color: '#7c3aed',
    fontSize: 12,
    fontFamily: 'monospace',
    marginBottom: 4,
  },
  linkNote: {
    color: '#6b7280',
    fontSize: 12,
    lineHeight: 17,
  },
  aboutText: {
    color: '#6b7280',
    fontSize: 13,
    lineHeight: 20,
    marginBottom: 14,
  },
  metaRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
    borderTopWidth: 1,
    borderTopColor: '#2a2d3a',
  },
  metaLabel: {
    color: '#6b7280',
    fontSize: 13,
  },
  metaValue: {
    color: '#c9cdd8',
    fontSize: 13,
    fontWeight: '500',
  },
});
