import React, { useState } from 'react';
import { StyleSheet, Text, View, SafeAreaView, ScrollView, TouchableOpacity, Alert, Modal } from 'react-native';
import { useVoicePrintStore } from '@/store/voicePrintStore';
import { Card, Button, Input, EmptyState } from '@/components';
import { COLORS, FONT_SIZES, SPACING, BORDER_RADIUS } from '@/constants/theme';

export function VoicePrintScreen() {
  const { profiles, analyses, isRecording, addProfile, removeProfile, startRecording, stopRecording } = useVoicePrintStore();
  const [showEnrollModal, setShowEnrollModal] = useState(false);
  const [profileName, setProfileName] = useState('');
  const [relationship, setRelationship] = useState('');

  const handleEnroll = async () => {
    if (!profileName || !relationship) return;

    await addProfile(profileName, relationship);
    setProfileName('');
    setRelationship('');
    setShowEnrollModal(false);
  };

  const handleRemoveProfile = (id: string, name: string) => {
    Alert.alert(
      'Remove Voice Profile',
      `Remove voice profile for "${name}"? This cannot be undone.`,
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Remove',
          style: 'destructive',
          onPress: () => removeProfile(id),
        },
      ]
    );
  };

  const handleRecording = () => {
    if (isRecording) {
      stopRecording();
    } else {
      startRecording();
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>VoicePrint</Text>
        <Text style={styles.subtitle}>Voice authentication & protection</Text>
      </View>

      <ScrollView style={styles.content}>
        <Card title="Voice Profiles">
          <Button
            title="+ Enroll Family Member"
            onPress={() => setShowEnrollModal(true)}
            variant="secondary"
            fullWidth
          />

          {profiles.length === 0 ? (
            <EmptyState
              title="No voice profiles"
              message="Enroll family members to protect against voice impersonation"
            />
          ) : (
            profiles.map((profile) => (
              <View key={profile.id} style={styles.profileItem}>
                <View style={styles.profileItemLeft}>
                  <View style={styles.avatar}>
                    <Text style={styles.avatarText}>
                      {profile.name.charAt(0).toUpperCase()}
                    </Text>
                  </View>
                  <View style={styles.profileInfo}>
                    <Text style={styles.profileName}>{profile.name}</Text>
                    <Text style={styles.profileRelationship}>{profile.relationship}</Text>
                  </View>
                </View>
                <View style={styles.profileItemRight}>
                  <Text style={styles.confidence}>
                    {profile.confidence}% match
                  </Text>
                  <TouchableOpacity onPress={() => handleRemoveProfile(profile.id, profile.name)}>
                    <Text style={styles.removeText}>Remove</Text>
                  </TouchableOpacity>
                </View>
              </View>
            ))
          )}
        </Card>

        <Card title="Voice Analysis">
          <View style={styles.recordingSection}>
            <TouchableOpacity
              style={[
                styles.recordButton,
                { backgroundColor: isRecording ? COLORS.danger : COLORS.primary },
              ]}
              onPress={handleRecording}
            >
              <View style={[styles.recordDot, { backgroundColor: isRecording ? '#fff' : COLORS.card }]} />
              <Text style={styles.recordButtonText}>
                {isRecording ? 'Stop Recording' : 'Test Voice Match'}
              </Text>
            </TouchableOpacity>
            <Text style={styles.recordingHint}>
              {isRecording
                ? 'Recording... Speak clearly into the microphone'
                : 'Tap to test voice matching against enrolled profiles'
              }
            </Text>
          </View>

          {analyses.length === 0 ? (
            <EmptyState title="No analysis results" message="Record voice samples to see match results" />
          ) : (
            analyses.map((analysis) => (
              <View key={analysis.id} style={styles.analysisItem}>
                <View style={styles.analysisLeft}>
                  <Text style={styles.analysisTime}>
                    {new Date(analysis.timestamp).toLocaleString()}
                  </Text>
                  <Text style={[
                    styles.analysisResult,
                    { color: analysis.isMatch ? COLORS.success : COLORS.danger }
                  ]}>
                    {analysis.isMatch ? 'Match' : 'No Match'} - {analysis.confidence}%
                  </Text>
                </View>
              </View>
            ))
          )}
        </Card>
      </ScrollView>

      <Modal visible={showEnrollModal} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>Enroll Family Member</Text>

            <Input
              label="Name"
              placeholder="e.g., Mom"
              value={profileName}
              onChangeText={setProfileName}
            />

            <Input
              label="Relationship"
              placeholder="e.g., Mother"
              value={relationship}
              onChangeText={setRelationship}
            />

            <View style={styles.modalActions}>
              <Button
                title="Cancel"
                onPress={() => setShowEnrollModal(false)}
                variant="ghost"
              />
              <Button
                title="Enroll"
                onPress={handleEnroll}
                variant="primary"
              />
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    padding: SPACING.md,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  title: {
    color: COLORS.text,
    fontSize: FONT_SIZES.xxl,
    fontWeight: 'bold',
  },
  subtitle: {
    color: COLORS.textSecondary,
    fontSize: FONT_SIZES.sm,
    marginTop: SPACING.xs,
  },
  content: {
    flex: 1,
  },
  profileItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: SPACING.sm,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  profileItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: COLORS.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: SPACING.sm,
  },
  avatarText: {
    color: '#fff',
    fontSize: FONT_SIZES.md,
    fontWeight: '600',
  },
  profileInfo: {
    flex: 1,
  },
  profileName: {
    color: COLORS.text,
    fontSize: FONT_SIZES.md,
    fontWeight: '500',
  },
  profileRelationship: {
    color: COLORS.textSecondary,
    fontSize: FONT_SIZES.sm,
  },
  profileItemRight: {
    alignItems: 'flex-end',
    gap: SPACING.xs,
  },
  confidence: {
    color: COLORS.accent,
    fontSize: FONT_SIZES.sm,
  },
  removeText: {
    color: COLORS.danger,
    fontSize: FONT_SIZES.sm,
  },
  recordingSection: {
    alignItems: 'center',
    paddingVertical: SPACING.md,
  },
  recordButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING.sm,
    paddingVertical: SPACING.md,
    paddingHorizontal: SPACING.xl,
    borderRadius: BORDER_RADIUS.round,
  },
  recordDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
  },
  recordButtonText: {
    color: '#fff',
    fontSize: FONT_SIZES.md,
    fontWeight: '600',
  },
  recordingHint: {
    color: COLORS.textMuted,
    fontSize: FONT_SIZES.sm,
    marginTop: SPACING.sm,
    textAlign: 'center',
  },
  analysisItem: {
    paddingVertical: SPACING.sm,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  analysisLeft: {
    gap: 4,
  },
  analysisTime: {
    color: COLORS.textMuted,
    fontSize: FONT_SIZES.xs,
  },
  analysisResult: {
    fontSize: FONT_SIZES.sm,
    fontWeight: '500',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: COLORS.backgroundLight,
    borderTopLeftRadius: BORDER_RADIUS.xl,
    borderTopRightRadius: BORDER_RADIUS.xl,
    padding: SPACING.lg,
    paddingBottom: SPACING.xxl,
  },
  modalTitle: {
    color: COLORS.text,
    fontSize: FONT_SIZES.xl,
    fontWeight: 'bold',
    marginBottom: SPACING.md,
  },
  modalActions: {
    flexDirection: 'row',
    gap: SPACING.md,
    marginTop: SPACING.md,
  },
});
