import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Linking,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import { AppColors, BorderRadius, FontSizes, Spacing } from '@/constants/theme';
import { PageHeader } from '@/components/PageHeader';

interface FAQItemProps {
  question: string;
  answer: string;
  isExpanded: boolean;
  onToggle: () => void;
}

function FAQItem({ question, answer, isExpanded, onToggle }: FAQItemProps) {
  return (
    <TouchableOpacity style={styles.faqItem} onPress={onToggle} activeOpacity={0.7}>
      <View style={styles.faqHeader}>
        <Text style={styles.faqQuestion}>{question}</Text>
        <Ionicons
          name={isExpanded ? 'chevron-up' : 'chevron-down'}
          size={20}
          color={AppColors.textMuted}
        />
      </View>
      {isExpanded && (
        <Text style={styles.faqAnswer}>{answer}</Text>
      )}
    </TouchableOpacity>
  );
}

interface GuideCategoryProps {
  icon: keyof typeof Ionicons.glyphMap;
  iconColor: string;
  iconBgColor: string;
  title: string;
  description: string;
  onPress: () => void;
}

function GuideCategory({
  icon,
  iconColor,
  iconBgColor,
  title,
  description,
  onPress,
}: GuideCategoryProps) {
  return (
    <TouchableOpacity style={styles.guideItem} onPress={onPress}>
      <View style={[styles.guideIcon, { backgroundColor: iconBgColor }]}>
        <Ionicons name={icon} size={24} color={iconColor} />
      </View>
      <Text style={styles.guideTitle}>{title}</Text>
      <Text style={styles.guideDescription}>{description}</Text>
    </TouchableOpacity>
  );
}

export default function HelpScreen() {
  const [searchQuery, setSearchQuery] = useState('');
  const [expandedFAQ, setExpandedFAQ] = useState<number | null>(null);

  const faqs = [
    {
      question: 'How do I add a new beneficiary?',
      answer: 'Beneficiaries are assigned by your organization administrator. Contact your admin or support team to request access to additional beneficiaries. Once assigned, they will automatically appear in your dashboard.',
    },
    {
      question: 'What does the wellness score mean?',
      answer: 'The wellness score (0-100%) reflects the overall health pattern of your beneficiary based on daily activities, sleep patterns, movement data, and vital signs. A score above 70% indicates healthy patterns, 40-70% suggests some concerns, and below 40% may require attention.',
    },
    {
      question: 'How often is the data updated?',
      answer: 'Sensor data is collected in real-time and synced every few minutes. Dashboard summaries are calculated daily. Emergency alerts are instant and will notify you immediately.',
    },
    {
      question: 'What triggers an emergency alert?',
      answer: 'Emergency alerts are triggered by: falls detected by motion sensors, prolonged inactivity exceeding normal patterns, SOS button press by the beneficiary, and abnormal vital sign readings (if health monitors are connected).',
    },
    {
      question: 'Can I share access with family members?',
      answer: 'Yes! Contact your administrator to add additional caregivers. Each caregiver will have their own account and can set their own notification preferences while sharing access to the same beneficiary data.',
    },
    {
      question: 'How do I change notification sounds?',
      answer: 'Go to Profile > Notifications to customize your alert preferences. You can set different sounds for emergency alerts vs regular notifications, and configure quiet hours for non-urgent alerts.',
    },
    {
      question: 'Is my data secure?',
      answer: 'Yes. WellNuo uses end-to-end encryption for all data transmission. Your data is stored in HIPAA-compliant servers, and we never share personal information with third parties. You can export or delete your data at any time.',
    },
    {
      question: 'What devices are compatible?',
      answer: 'WellNuo works with most motion sensors, door/window sensors, and smart home devices. Supported health monitors include select blood pressure cuffs, pulse oximeters, and weight scales. Check our device compatibility list for specifics.',
    },
  ];

  const filteredFAQs = faqs.filter(
    faq =>
      faq.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
      faq.answer.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <PageHeader title="Help Center" />
      <ScrollView showsVerticalScrollIndicator={false}>
        {/* Search */}
        <View style={styles.searchSection}>
          <View style={styles.searchContainer}>
            <Ionicons name="search" size={20} color={AppColors.textMuted} />
            <TextInput
              style={styles.searchInput}
              placeholder="Search for help..."
              placeholderTextColor={AppColors.textMuted}
              value={searchQuery}
              onChangeText={setSearchQuery}
            />
            {searchQuery.length > 0 && (
              <TouchableOpacity onPress={() => setSearchQuery('')}>
                <Ionicons name="close-circle" size={20} color={AppColors.textMuted} />
              </TouchableOpacity>
            )}
          </View>
        </View>

        {/* Quick Guides */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Quick Guides</Text>
          <View style={styles.guidesGrid}>
            <GuideCategory
              icon="rocket"
              iconColor="#3B82F6"
              iconBgColor="#DBEAFE"
              title="Getting Started"
              description="Learn the basics"
              onPress={() => Linking.openURL('https://wellnuo.com/guides/getting-started')}
            />
            <GuideCategory
              icon="people"
              iconColor="#10B981"
              iconBgColor="#D1FAE5"
              title="Managing Care"
              description="Beneficiary tips"
              onPress={() => Linking.openURL('https://wellnuo.com/guides/managing-care')}
            />
            <GuideCategory
              icon="notifications"
              iconColor="#F59E0B"
              iconBgColor="#FEF3C7"
              title="Alerts & Notifications"
              description="Stay informed"
              onPress={() => Linking.openURL('https://wellnuo.com/guides/alerts')}
            />
            <GuideCategory
              icon="hardware-chip"
              iconColor="#8B5CF6"
              iconBgColor="#EDE9FE"
              title="Device Setup"
              description="Connect sensors"
              onPress={() => Linking.openURL('https://wellnuo.com/guides/devices')}
            />
          </View>
        </View>

        {/* FAQs */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Frequently Asked Questions</Text>
          <View style={styles.faqContainer}>
            {filteredFAQs.length > 0 ? (
              filteredFAQs.map((faq, index) => (
                <View key={index}>
                  <FAQItem
                    question={faq.question}
                    answer={faq.answer}
                    isExpanded={expandedFAQ === index}
                    onToggle={() => setExpandedFAQ(expandedFAQ === index ? null : index)}
                  />
                  {index < filteredFAQs.length - 1 && <View style={styles.faqDivider} />}
                </View>
              ))
            ) : (
              <View style={styles.noResults}>
                <Ionicons name="search-outline" size={48} color={AppColors.textMuted} />
                <Text style={styles.noResultsText}>No results found</Text>
                <Text style={styles.noResultsHint}>Try different keywords</Text>
              </View>
            )}
          </View>
        </View>

        {/* Video Tutorials */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Video Tutorials</Text>
          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.videosScroll}>
            {[
              { title: 'App Overview', duration: '3:45' },
              { title: 'Setting Up Alerts', duration: '2:30' },
              { title: 'Understanding Data', duration: '4:15' },
              { title: 'Troubleshooting', duration: '5:00' },
            ].map((video, index) => (
              <TouchableOpacity key={index} style={styles.videoCard}>
                <View style={styles.videoThumbnail}>
                  <Ionicons name="play-circle" size={40} color={AppColors.white} />
                </View>
                <Text style={styles.videoTitle}>{video.title}</Text>
                <Text style={styles.videoDuration}>{video.duration}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>

        {/* Still Need Help */}
        <View style={styles.section}>
          <View style={styles.needHelpCard}>
            <View style={styles.needHelpIcon}>
              <Ionicons name="chatbubbles" size={32} color={AppColors.primary} />
            </View>
            <Text style={styles.needHelpTitle}>Still need help?</Text>
            <Text style={styles.needHelpText}>
              Our support team is available 24/7 to assist you with any questions.
            </Text>
            <TouchableOpacity
              style={styles.contactButton}
              onPress={() => Linking.openURL('mailto:support@wellnuo.com')}
            >
              <Text style={styles.contactButtonText}>Contact Support</Text>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.surface,
  },
  searchSection: {
    padding: Spacing.lg,
    backgroundColor: AppColors.background,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.lg,
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
  },
  searchInput: {
    flex: 1,
    marginLeft: Spacing.sm,
    fontSize: FontSizes.base,
    color: AppColors.textPrimary,
  },
  section: {
    marginTop: Spacing.md,
  },
  sectionTitle: {
    fontSize: FontSizes.sm,
    fontWeight: '600',
    color: AppColors.textSecondary,
    paddingHorizontal: Spacing.lg,
    paddingVertical: Spacing.sm,
    textTransform: 'uppercase',
  },
  guidesGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: Spacing.sm,
    backgroundColor: AppColors.background,
  },
  guideItem: {
    width: '50%',
    padding: Spacing.md,
    alignItems: 'center',
  },
  guideIcon: {
    width: 56,
    height: 56,
    borderRadius: BorderRadius.lg,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: Spacing.sm,
  },
  guideTitle: {
    fontSize: FontSizes.sm,
    fontWeight: '600',
    color: AppColors.textPrimary,
    textAlign: 'center',
  },
  guideDescription: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    textAlign: 'center',
    marginTop: 2,
  },
  faqContainer: {
    backgroundColor: AppColors.background,
  },
  faqItem: {
    paddingVertical: Spacing.md,
    paddingHorizontal: Spacing.lg,
  },
  faqHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  faqQuestion: {
    flex: 1,
    fontSize: FontSizes.base,
    fontWeight: '500',
    color: AppColors.textPrimary,
    marginRight: Spacing.sm,
  },
  faqAnswer: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
    marginTop: Spacing.sm,
    lineHeight: 20,
  },
  faqDivider: {
    height: 1,
    backgroundColor: AppColors.border,
    marginHorizontal: Spacing.lg,
  },
  noResults: {
    alignItems: 'center',
    paddingVertical: Spacing.xl,
  },
  noResultsText: {
    fontSize: FontSizes.base,
    fontWeight: '500',
    color: AppColors.textPrimary,
    marginTop: Spacing.md,
  },
  noResultsHint: {
    fontSize: FontSizes.sm,
    color: AppColors.textMuted,
    marginTop: Spacing.xs,
  },
  videosScroll: {
    backgroundColor: AppColors.background,
    paddingVertical: Spacing.md,
  },
  videoCard: {
    width: 160,
    marginLeft: Spacing.md,
  },
  videoThumbnail: {
    height: 90,
    backgroundColor: AppColors.primary,
    borderRadius: BorderRadius.md,
    justifyContent: 'center',
    alignItems: 'center',
  },
  videoTitle: {
    fontSize: FontSizes.sm,
    fontWeight: '500',
    color: AppColors.textPrimary,
    marginTop: Spacing.sm,
  },
  videoDuration: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    marginTop: 2,
  },
  needHelpCard: {
    backgroundColor: AppColors.background,
    margin: Spacing.lg,
    borderRadius: BorderRadius.lg,
    padding: Spacing.xl,
    alignItems: 'center',
  },
  needHelpIcon: {
    width: 64,
    height: 64,
    borderRadius: 32,
    backgroundColor: '#DBEAFE',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: Spacing.md,
  },
  needHelpTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  needHelpText: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
    textAlign: 'center',
    marginTop: Spacing.sm,
    marginBottom: Spacing.lg,
  },
  contactButton: {
    backgroundColor: AppColors.primary,
    borderRadius: BorderRadius.lg,
    paddingVertical: Spacing.md,
    paddingHorizontal: Spacing.xl,
  },
  contactButtonText: {
    fontSize: FontSizes.base,
    fontWeight: '600',
    color: AppColors.white,
  },
});
