import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { RaceCard } from '../src/components';
import { createSchedule, getBetTypes } from '../src/services/api';
import { useAppStore } from '../src/store/appStore';
import { BetType } from '../src/types';
import { formatRaceTime, getBetTypeName } from '../src/utils/formatters';
import { analytics } from '../src/analytics';

const TIMING_OPTIONS = [
  { value: 60, label: '60 min' },
  { value: 30, label: '30 min' },
  { value: 15, label: '15 min' },
  { value: 5, label: '5 min' },
];

const CHANNEL_OPTIONS = [
  { id: 'push', name: 'Push', icon: 'notifications-outline', available: true },
  { id: 'sms', name: 'SMS', icon: 'chatbubble-outline', available: false },
  { id: 'email', name: 'Email', icon: 'mail-outline', available: false },
];

export default function ScheduleBuilderScreen() {
  const router = useRouter();
  const { selectedRace, selectedBetType, setSelectedBetType, resetTipFlow } = useAppStore();
  
  const [minutesBefore, setMinutesBefore] = useState(15);
  const [channels, setChannels] = useState<string[]>(['push']);
  const [loading, setLoading] = useState(false);
  const [betTypes, setBetTypes] = useState<{ simple: BetType[]; advanced: BetType[] }>({ simple: [], advanced: [] });

  React.useEffect(() => {
    loadBetTypes();
  }, []);

  const loadBetTypes = async () => {
    try {
      const data = await getBetTypes();
      setBetTypes(data);
    } catch (error) {
      console.error('Error loading bet types:', error);
    }
  };

  const handleToggleChannel = (channelId: string) => {
    const channel = CHANNEL_OPTIONS.find(c => c.id === channelId);
    if (!channel?.available) {
      Alert.alert('Coming Soon', `${channel?.name} notifications will be available in a future update.`);
      return;
    }
    
    if (channels.includes(channelId)) {
      if (channels.length > 1) {
        setChannels(channels.filter(c => c !== channelId));
      }
    } else {
      setChannels([...channels, channelId]);
    }
  };

  const handleCreateSchedule = async () => {
    if (!selectedRace) {
      Alert.alert('Error', 'Please select a race first');
      return;
    }

    setLoading(true);
    try {
      await createSchedule({
        race_id: selectedRace.id,
        bet_type: selectedBetType,
        minutes_before: minutesBefore,
        channels,
      });

      analytics.track('schedule_created', {
        race_id: selectedRace.id,
        minutes_before: minutesBefore,
        bet_type: selectedBetType,
      });
      
      Alert.alert(
        'Schedule Created',
        `You'll receive a tip ${minutesBefore} minutes before ${selectedRace.track} Race ${selectedRace.race_number}`,
        [
          {
            text: 'View Schedules',
            onPress: () => {
              resetTipFlow();
              router.replace('/(tabs)/schedule');
            },
          },
          {
            text: 'Done',
            onPress: () => {
              resetTipFlow();
              router.replace('/(tabs)');
            },
          },
        ]
      );
    } catch (error) {
      Alert.alert('Error', 'Failed to create schedule');
    } finally {
      setLoading(false);
    }
  };

  const handleSelectRace = () => {
    router.push('/race-picker?mode=schedule');
  };

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.closeButton} 
          onPress={() => router.back()}
        >
          <Ionicons name="close" size={24} color="#111827" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Schedule a Tip</Text>
        <View style={styles.headerSpacer} />
      </View>

      <ScrollView 
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Selected Race */}
        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Race</Text>
          {selectedRace ? (
            <TouchableOpacity onPress={handleSelectRace}>
              <RaceCard race={selectedRace} showCountdown />
              <View style={styles.changeButton}>
                <Text style={styles.changeButtonText}>Change race</Text>
              </View>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity style={styles.selectRaceCard} onPress={handleSelectRace}>
              <Ionicons name="flag-outline" size={32} color="#9ca3af" />
              <Text style={styles.selectRaceText}>Select a race</Text>
              <Ionicons name="chevron-forward" size={20} color="#9ca3af" />
            </TouchableOpacity>
          )}
        </View>

        {/* Bet Type */}
        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Bet Type</Text>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            <View style={styles.chipsRow}>
              {[...betTypes.simple, ...betTypes.advanced].map((bet) => (
                <TouchableOpacity
                  key={bet.id}
                  style={[
                    styles.chip,
                    selectedBetType === bet.id && styles.chipActive,
                  ]}
                  onPress={() => setSelectedBetType(bet.id)}
                >
                  <Text style={[
                    styles.chipText,
                    selectedBetType === bet.id && styles.chipTextActive,
                  ]}>
                    {bet.name}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        </View>

        {/* Timing */}
        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Send tip before race</Text>
          <View style={styles.timingRow}>
            {TIMING_OPTIONS.map((option) => (
              <TouchableOpacity
                key={option.value}
                style={[
                  styles.timingChip,
                  minutesBefore === option.value && styles.timingChipActive,
                ]}
                onPress={() => setMinutesBefore(option.value)}
              >
                <Text style={[
                  styles.timingChipText,
                  minutesBefore === option.value && styles.timingChipTextActive,
                ]}>
                  {option.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* Channels */}
        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Notification channels</Text>
          <View style={styles.channelsContainer}>
            {CHANNEL_OPTIONS.map((channel) => (
              <TouchableOpacity
                key={channel.id}
                style={[
                  styles.channelCard,
                  channels.includes(channel.id) && styles.channelCardActive,
                  !channel.available && styles.channelCardDisabled,
                ]}
                onPress={() => handleToggleChannel(channel.id)}
              >
                <Ionicons 
                  name={channel.icon as any} 
                  size={24} 
                  color={channels.includes(channel.id) ? '#fff' : channel.available ? '#111827' : '#9ca3af'} 
                />
                <Text style={[
                  styles.channelCardText,
                  channels.includes(channel.id) && styles.channelCardTextActive,
                  !channel.available && styles.channelCardTextDisabled,
                ]}>
                  {channel.name}
                </Text>
                {!channel.available && (
                  <Text style={styles.comingSoonText}>Soon</Text>
                )}
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* Preview */}
        {selectedRace && (
          <View style={styles.previewCard}>
            <Text style={styles.previewTitle}>What you'll receive</Text>
            <View style={styles.previewContent}>
              <Ionicons name="notifications" size={20} color="#3b82f6" />
              <View style={styles.previewTextContainer}>
                <Text style={styles.previewText}>
                  {getBetTypeName(selectedBetType)} tip for {selectedRace.track} Race {selectedRace.race_number}
                </Text>
                <Text style={styles.previewSubtext}>
                  {minutesBefore} minutes before {formatRaceTime(selectedRace.start_time)}
                </Text>
              </View>
            </View>
          </View>
        )}
      </ScrollView>

      {/* Action Button */}
      <View style={styles.footer}>
        <TouchableOpacity
          style={[
            styles.actionButton,
            (!selectedRace || loading) && styles.actionButtonDisabled,
          ]}
          onPress={handleCreateSchedule}
          disabled={!selectedRace || loading}
        >
          {loading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <>
              <Ionicons name="alarm" size={22} color="#fff" />
              <Text style={styles.actionButtonText}>Create Schedule</Text>
            </>
          )}
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e7eb',
    backgroundColor: '#fff',
  },
  closeButton: {
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
  },
  headerSpacer: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
  },
  section: {
    marginBottom: 24,
  },
  sectionLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: '#374151',
    marginBottom: 12,
  },
  selectRaceCard: {
    backgroundColor: '#fff',
    borderRadius: 16,
    padding: 24,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 16,
    borderWidth: 2,
    borderColor: '#e5e7eb',
    borderStyle: 'dashed',
  },
  selectRaceText: {
    flex: 1,
    fontSize: 16,
    color: '#6b7280',
    fontWeight: '500',
  },
  changeButton: {
    alignItems: 'center',
    marginTop: -4,
  },
  changeButtonText: {
    fontSize: 14,
    color: '#3b82f6',
    fontWeight: '600',
  },
  chipsRow: {
    flexDirection: 'row',
    gap: 10,
  },
  chip: {
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 20,
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#e5e7eb',
  },
  chipActive: {
    backgroundColor: '#111827',
    borderColor: '#111827',
  },
  chipText: {
    fontSize: 14,
    fontWeight: '500',
    color: '#374151',
  },
  chipTextActive: {
    color: '#fff',
  },
  timingRow: {
    flexDirection: 'row',
    gap: 10,
  },
  timingChip: {
    flex: 1,
    paddingVertical: 14,
    borderRadius: 12,
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#e5e7eb',
    alignItems: 'center',
  },
  timingChipActive: {
    backgroundColor: '#111827',
    borderColor: '#111827',
  },
  timingChipText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#374151',
  },
  timingChipTextActive: {
    color: '#fff',
  },
  channelsContainer: {
    flexDirection: 'row',
    gap: 12,
  },
  channelCard: {
    flex: 1,
    backgroundColor: '#fff',
    borderRadius: 14,
    padding: 16,
    alignItems: 'center',
    gap: 8,
    borderWidth: 2,
    borderColor: '#e5e7eb',
  },
  channelCardActive: {
    backgroundColor: '#111827',
    borderColor: '#111827',
  },
  channelCardDisabled: {
    opacity: 0.6,
  },
  channelCardText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#111827',
  },
  channelCardTextActive: {
    color: '#fff',
  },
  channelCardTextDisabled: {
    color: '#9ca3af',
  },
  comingSoonText: {
    fontSize: 10,
    color: '#9ca3af',
    fontWeight: '500',
  },
  previewCard: {
    backgroundColor: '#eff6ff',
    borderRadius: 14,
    padding: 16,
    borderWidth: 1,
    borderColor: '#bfdbfe',
  },
  previewTitle: {
    fontSize: 13,
    fontWeight: '600',
    color: '#1e40af',
    marginBottom: 10,
  },
  previewContent: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: 12,
  },
  previewTextContainer: {
    flex: 1,
  },
  previewText: {
    fontSize: 15,
    fontWeight: '600',
    color: '#1e40af',
  },
  previewSubtext: {
    fontSize: 13,
    color: '#3b82f6',
    marginTop: 2,
  },
  footer: {
    padding: 20,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#e5e7eb',
  },
  actionButton: {
    backgroundColor: '#111827',
    borderRadius: 14,
    paddingVertical: 18,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 10,
  },
  actionButtonDisabled: {
    backgroundColor: '#9ca3af',
  },
  actionButtonText: {
    fontSize: 17,
    fontWeight: '700',
    color: '#fff',
  },
});
