import { useState } from 'react';
import { Alert, StyleSheet, Text, TextInput, View } from 'react-native';

import { ActionButton } from '@/shared/components/ActionButton';
import { Screen } from '@/shared/components/Screen';
import { Colors, Radius, Spacing } from '@/constants/theme';
import { captureReceiptFromCamera, pickReceiptFromLibrary } from '@/platform/camera/receiptCapture';
import { transcribeVoice, useVoiceRecorder } from '@/platform/voice/voiceInput';

export default function AssistantScreen() {
  const [message, setMessage] = useState('');
  const [receiptName, setReceiptName] = useState('');
  const [isRecording, setIsRecording] = useState(false);
  const voice = useVoiceRecorder();

  async function handleCamera() {
    try {
      const receipt = await captureReceiptFromCamera();
      if (receipt) {
        setReceiptName(receipt.fileName);
      }
    } catch (error) {
      Alert.alert('无法拍照', error instanceof Error ? error.message : '请检查相机权限。');
    }
  }

  async function handleLibrary() {
    try {
      const receipt = await pickReceiptFromLibrary();
      if (receipt) {
        setReceiptName(receipt.fileName);
      }
    } catch (error) {
      Alert.alert('无法选择票据', error instanceof Error ? error.message : '请检查相册权限。');
    }
  }

  async function toggleVoice() {
    try {
      if (!isRecording) {
        setIsRecording(true);
        await voice.start();
        return;
      }
      const uri = await voice.stop();
      setIsRecording(false);
      if (uri) {
        const result = await transcribeVoice(uri);
        setMessage(result.text);
      }
    } catch (error) {
      setIsRecording(false);
      Alert.alert('语音输入失败', error instanceof Error ? error.message : '请检查麦克风权限。');
    }
  }

  return (
    <Screen title="AI 助手" subtitle="输入问题、拍摄票据或使用语音描述费用，助手会返回可确认的报销建议。">
      <View style={styles.hero}>
        <Text style={styles.badge}>AI 报销助手</Text>
        <Text style={styles.title}>你好，我是你的报销助手</Text>
        <Text style={styles.copy}>我可以帮你识别费用类型、解读报销制度、检测缺失材料并生成报销单。</Text>
      </View>

      <View style={styles.answerCard}>
        <Text style={styles.answerTitle}>示例建议</Text>
        <Text style={styles.answerText}>
          你可以说：“我昨天打车 86 元，请客户吃饭 320 元，怎么报？”
        </Text>
      </View>

      {receiptName ? (
        <View style={styles.receiptBar}>
          <Text style={styles.receiptText}>已选择票据：{receiptName}</Text>
        </View>
      ) : null}

      <View style={styles.inputCard}>
        <TextInput
          accessibilityLabel="助手输入框"
          multiline
          placeholder="描述费用或输入你的问题"
          placeholderTextColor={Colors.light.textSecondary}
          style={styles.input}
          value={message}
          onChangeText={setMessage}
        />
        <View style={styles.actionRow}>
          <ActionButton accessibilityLabel="拍照识别票据" variant="secondary" onPress={handleCamera}>
            拍照
          </ActionButton>
          <ActionButton accessibilityLabel="从相册上传票据" variant="secondary" onPress={handleLibrary}>
            相册
          </ActionButton>
          <ActionButton accessibilityLabel="语音输入" variant={isRecording ? 'danger' : 'secondary'} onPress={toggleVoice}>
            {isRecording ? '停止' : '语音'}
          </ActionButton>
          <ActionButton accessibilityLabel="发送给 AI 助手">发送</ActionButton>
        </View>
      </View>
    </Screen>
  );
}

const styles = StyleSheet.create({
  hero: {
    gap: Spacing.three,
    borderRadius: Radius.lg,
    backgroundColor: Colors.light.primarySoft,
    borderWidth: 1,
    borderColor: '#BFEEDB',
    padding: Spacing.four,
  },
  badge: {
    alignSelf: 'flex-start',
    borderRadius: Radius.pill,
    backgroundColor: '#DFF8EC',
    color: Colors.light.primary,
    paddingHorizontal: 10,
    paddingVertical: 4,
    fontSize: 12,
    fontWeight: '900',
  },
  title: {
    color: Colors.light.text,
    fontSize: 23,
    fontWeight: '900',
  },
  copy: {
    color: Colors.light.textSecondary,
    fontSize: 14,
    lineHeight: 23,
  },
  answerCard: {
    gap: Spacing.two,
    borderRadius: Radius.lg,
    backgroundColor: '#FFFFFF',
    borderWidth: 1,
    borderColor: Colors.light.border,
    padding: Spacing.four,
  },
  answerTitle: {
    color: Colors.light.text,
    fontSize: 16,
    fontWeight: '900',
  },
  answerText: {
    color: Colors.light.textSecondary,
    fontSize: 14,
    lineHeight: 23,
  },
  receiptBar: {
    borderRadius: Radius.md,
    backgroundColor: '#E8F1FF',
    padding: Spacing.three,
  },
  receiptText: {
    color: Colors.light.info,
    fontWeight: '800',
  },
  inputCard: {
    gap: Spacing.three,
    borderRadius: Radius.lg,
    backgroundColor: '#FFFFFF',
    borderWidth: 1,
    borderColor: Colors.light.border,
    padding: Spacing.four,
  },
  input: {
    minHeight: 92,
    color: Colors.light.text,
    fontSize: 15,
    textAlignVertical: 'top',
  },
  actionRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: Spacing.three,
  },
});
