import { Ionicons } from '@expo/vector-icons';
import * as Haptics from 'expo-haptics';
import * as ImagePicker from 'expo-image-picker';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import React, { useCallback, useRef, useState } from 'react';
import {
  Alert,
  Animated,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useColors } from '@/hooks/useColors';
import { CATEGORIES } from '@/data/mockData';

type Step = 'pick' | 'details' | 'uploading' | 'done';

const UPLOAD_STAGES = ['Uploading video...', 'Processing...', 'Optimising quality...', 'Publishing...'];

const GRADIENT_PREVIEWS: [string, string][] = [
  ['#FF6B35', '#FF3CAC'],
  ['#7928CA', '#FF0080'],
  ['#0F2027', '#203A43'],
  ['#FF4500', '#FF8C00'],
];

export default function UploadScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();

  const [step, setStep] = useState<Step>('pick');
  const [videoUri, setVideoUri] = useState<string | null>(null);
  const [videoDuration, setVideoDuration] = useState<number>(0);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('beauty');
  const [earningsEnabled, setEarningsEnabled] = useState(false);
  const [earningsPotential, setEarningsPotential] = useState('');
  const [uploadStage, setUploadStage] = useState(0);
  const [gradientIndex] = useState(() => Math.floor(Math.random() * GRADIENT_PREVIEWS.length));

  const progressAnim = useRef(new Animated.Value(0)).current;
  const checkAnim = useRef(new Animated.Value(0)).current;
  const topPad = Platform.OS === 'web' ? 67 : insets.top;
  const bottomPad = Platform.OS === 'web' ? 34 : insets.bottom;

  const pickFromGallery = useCallback(async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission required', 'Please allow access to your photo library to upload videos.');
      return;
    }
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: 'videos',
      allowsEditing: true,
      videoMaxDuration: 60,
      quality: 1,
    });
    if (!result.canceled && result.assets[0]) {
      const asset = result.assets[0];
      setVideoUri(asset.uri);
      setVideoDuration(Math.round((asset.duration ?? 0) / 1000));
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      setStep('details');
    }
  }, []);

  const recordVideo = useCallback(async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission required', 'Please allow camera access to record videos.');
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: 'videos',
      allowsEditing: true,
      videoMaxDuration: 60,
      quality: 1,
    });
    if (!result.canceled && result.assets[0]) {
      const asset = result.assets[0];
      setVideoUri(asset.uri);
      setVideoDuration(Math.round((asset.duration ?? 0) / 1000));
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      setStep('details');
    }
  }, []);

  const startUpload = useCallback(() => {
    if (!title.trim()) {
      Alert.alert('Title required', 'Please add a title for your video.');
      return;
    }
    Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    setStep('uploading');

    let stageIndex = 0;
    const advanceStage = () => {
      if (stageIndex < UPLOAD_STAGES.length - 1) {
        stageIndex++;
        setUploadStage(stageIndex);
        setTimeout(advanceStage, 900 + Math.random() * 400);
      }
    };
    setTimeout(advanceStage, 800);

    Animated.timing(progressAnim, {
      toValue: 1,
      duration: 3800,
      useNativeDriver: false,
    }).start(() => {
      setStep('done');
      Animated.spring(checkAnim, {
        toValue: 1,
        useNativeDriver: true,
        speed: 60,
        bounciness: 18,
      }).start();
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    });
  }, [title, progressAnim, checkAnim]);

  const reset = useCallback(() => {
    setStep('pick');
    setVideoUri(null);
    setTitle('');
    setDescription('');
    setSelectedCategory('beauty');
    setEarningsEnabled(false);
    setEarningsPotential('');
    setUploadStage(0);
    progressAnim.setValue(0);
    checkAnim.setValue(0);
  }, [progressAnim, checkAnim]);

  const progressWidth = progressAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0%', '100%'],
  });

  const checkScale = checkAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [0.3, 1],
  });

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <View style={[s.header, { paddingTop: topPad + 10, borderBottomColor: colors.border }]}>
        <TouchableOpacity onPress={() => router.back()} style={s.backBtn}>
          <Ionicons name="arrow-back" size={22} color={colors.foreground} />
        </TouchableOpacity>
        <Text style={[s.headerTitle, { color: colors.foreground }]}>
          {step === 'pick' ? 'Upload Short' : step === 'details' ? 'Add Details' : step === 'uploading' ? 'Publishing...' : 'Published!'}
        </Text>
        <View style={{ width: 36 }} />
      </View>

      {step === 'pick' && (
        <ScrollView contentContainerStyle={[s.scroll, { paddingBottom: bottomPad + 24 }]}>
          <LinearGradient
            colors={['#FF6B3511', '#FF3CAC08']}
            style={s.pickBanner}
          >
            <Ionicons name="videocam" size={52} color={colors.primary} />
            <Text style={[s.pickTitle, { color: colors.foreground }]}>Share your skill</Text>
            <Text style={[s.pickSub, { color: colors.mutedForeground }]}>
              Upload a 60-second short to teach, inspire, and earn from your knowledge
            </Text>
          </LinearGradient>

          <View style={s.pickActions}>
            <TouchableOpacity
              onPress={recordVideo}
              style={[s.pickBtn, s.pickBtnPrimary, { backgroundColor: colors.primary }]}
              activeOpacity={0.85}
            >
              <View style={s.pickBtnIcon}>
                <Ionicons name="radio-button-on" size={28} color="#fff" />
              </View>
              <View style={s.pickBtnInfo}>
                <Text style={s.pickBtnLabel}>Record a Video</Text>
                <Text style={s.pickBtnDesc}>Open camera and record now</Text>
              </View>
              <Ionicons name="chevron-forward" size={18} color="rgba(255,255,255,0.7)" />
            </TouchableOpacity>

            <TouchableOpacity
              onPress={pickFromGallery}
              style={[s.pickBtn, { backgroundColor: colors.card, borderColor: colors.border, borderWidth: 1 }]}
              activeOpacity={0.85}
            >
              <View style={[s.pickBtnIcon, { backgroundColor: colors.secondary }]}>
                <Ionicons name="images" size={28} color={colors.primary} />
              </View>
              <View style={s.pickBtnInfo}>
                <Text style={[s.pickBtnLabel, { color: colors.foreground }]}>Choose from Gallery</Text>
                <Text style={[s.pickBtnDesc, { color: colors.mutedForeground }]}>Pick an existing video</Text>
              </View>
              <Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
            </TouchableOpacity>
          </View>

          <View style={[s.tipsCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
            <Text style={[s.tipsTitle, { color: colors.foreground }]}>Tips for great shorts</Text>
            {[
              { icon: 'time-outline', text: 'Keep it under 60 seconds — shorter is better' },
              { icon: 'phone-portrait-outline', text: 'Shoot vertically (portrait mode)' },
              { icon: 'sunny-outline', text: 'Good lighting = more views' },
              { icon: 'mic-outline', text: 'Clear audio matters as much as video' },
            ].map((tip) => (
              <View key={tip.icon} style={s.tipRow}>
                <Ionicons name={tip.icon as any} size={16} color={colors.primary} />
                <Text style={[s.tipText, { color: colors.mutedForeground }]}>{tip.text}</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      )}

      {step === 'details' && (
        <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }}>
          <ScrollView contentContainerStyle={[s.scroll, { paddingBottom: bottomPad + 24 }]} keyboardShouldPersistTaps="handled">
            <View style={s.previewWrap}>
              <LinearGradient
                colors={GRADIENT_PREVIEWS[gradientIndex]}
                style={s.preview}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Ionicons name="play-circle" size={56} color="rgba(255,255,255,0.8)" />
                {videoDuration > 0 && (
                  <View style={s.durationTag}>
                    <Text style={s.durationTagText}>{videoDuration}s</Text>
                  </View>
                )}
              </LinearGradient>
              <TouchableOpacity
                onPress={reset}
                style={[s.changeBtn, { backgroundColor: colors.card, borderColor: colors.border }]}
              >
                <Ionicons name="refresh" size={14} color={colors.foreground} />
                <Text style={[s.changeBtnText, { color: colors.foreground }]}>Change</Text>
              </TouchableOpacity>
            </View>

            <View style={s.form}>
              <Text style={[s.label, { color: colors.foreground }]}>Title <Text style={{ color: colors.primary }}>*</Text></Text>
              <TextInput
                style={[s.input, { backgroundColor: colors.card, borderColor: colors.border, color: colors.foreground }]}
                placeholder="What skill are you teaching?"
                placeholderTextColor={colors.mutedForeground}
                value={title}
                onChangeText={setTitle}
                maxLength={80}
              />
              <Text style={[s.charCount, { color: colors.mutedForeground }]}>{title.length}/80</Text>

              <Text style={[s.label, { color: colors.foreground }]}>Description</Text>
              <TextInput
                style={[s.input, s.textArea, { backgroundColor: colors.card, borderColor: colors.border, color: colors.foreground }]}
                placeholder="Tell viewers what they'll learn..."
                placeholderTextColor={colors.mutedForeground}
                value={description}
                onChangeText={setDescription}
                multiline
                numberOfLines={3}
                maxLength={200}
              />

              <Text style={[s.label, { color: colors.foreground }]}>Category</Text>
              <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={s.catRow}>
                {CATEGORIES.slice(1).map((cat) => (
                  <TouchableOpacity
                    key={cat.id}
                    onPress={() => setSelectedCategory(cat.id)}
                    style={[
                      s.catChip,
                      selectedCategory === cat.id
                        ? { backgroundColor: colors.primary, borderColor: colors.primary }
                        : { backgroundColor: colors.card, borderColor: colors.border },
                    ]}
                  >
                    <Text style={[s.catChipText, { color: selectedCategory === cat.id ? '#fff' : colors.mutedForeground }]}>
                      {cat.name}
                    </Text>
                  </TouchableOpacity>
                ))}
              </ScrollView>

              <TouchableOpacity
                onPress={() => setEarningsEnabled(!earningsEnabled)}
                style={[s.earningsToggle, { backgroundColor: colors.card, borderColor: earningsEnabled ? colors.primary : colors.border }]}
              >
                <View style={[s.earningsToggleIcon, { backgroundColor: earningsEnabled ? colors.primary + '22' : colors.secondary }]}>
                  <Ionicons name="trending-up" size={20} color={earningsEnabled ? colors.primary : colors.mutedForeground} />
                </View>
                <View style={s.earningsToggleInfo}>
                  <Text style={[s.earningsToggleLabel, { color: colors.foreground }]}>Show earnings potential</Text>
                  <Text style={[s.earningsToggleSub, { color: colors.mutedForeground }]}>
                    Display how much learners can earn
                  </Text>
                </View>
                <View style={[s.toggle, { backgroundColor: earningsEnabled ? colors.primary : colors.border }]}>
                  <View style={[s.toggleThumb, { transform: [{ translateX: earningsEnabled ? 18 : 2 }] }]} />
                </View>
              </TouchableOpacity>

              {earningsEnabled && (
                <TextInput
                  style={[s.input, { backgroundColor: colors.card, borderColor: colors.primary, color: colors.foreground }]}
                  placeholder="e.g. ₦30,000 – ₦80,000/week"
                  placeholderTextColor={colors.mutedForeground}
                  value={earningsPotential}
                  onChangeText={setEarningsPotential}
                />
              )}

              <TouchableOpacity
                onPress={startUpload}
                style={[s.uploadBtn, { backgroundColor: colors.primary }]}
                activeOpacity={0.85}
              >
                <Ionicons name="cloud-upload-outline" size={20} color="#fff" />
                <Text style={s.uploadBtnText}>Publish Short</Text>
              </TouchableOpacity>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
      )}

      {step === 'uploading' && (
        <View style={[s.uploadingScreen, { paddingBottom: bottomPad }]}>
          <LinearGradient
            colors={GRADIENT_PREVIEWS[gradientIndex]}
            style={s.uploadingThumb}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
          >
            <Ionicons name="play-circle" size={64} color="rgba(255,255,255,0.8)" />
          </LinearGradient>

          <Text style={[s.uploadingTitle, { color: colors.foreground }]} numberOfLines={2}>{title}</Text>
          <Text style={[s.uploadingStage, { color: colors.primary }]}>{UPLOAD_STAGES[uploadStage]}</Text>

          <View style={[s.progressTrack, { backgroundColor: colors.border }]}>
            <Animated.View style={[s.progressFill, { width: progressWidth, backgroundColor: colors.primary }]} />
          </View>
          <Text style={[s.uploadingHint, { color: colors.mutedForeground }]}>
            Please keep the app open while uploading
          </Text>
        </View>
      )}

      {step === 'done' && (
        <View style={[s.doneScreen, { paddingBottom: bottomPad }]}>
          <Animated.View style={[s.checkCircle, { backgroundColor: colors.primary, transform: [{ scale: checkScale }] }]}>
            <Ionicons name="checkmark" size={52} color="#fff" />
          </Animated.View>
          <Text style={[s.doneTitle, { color: colors.foreground }]}>Published!</Text>
          <Text style={[s.doneSub, { color: colors.mutedForeground }]}>
            Your short is live. Learners can now find and watch it on the feed.
          </Text>

          <View style={[s.doneCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
            <LinearGradient colors={GRADIENT_PREVIEWS[gradientIndex]} style={s.doneThumb}>
              <Ionicons name="play-circle" size={28} color="rgba(255,255,255,0.8)" />
            </LinearGradient>
            <View style={s.doneCardInfo}>
              <Text style={[s.doneCardTitle, { color: colors.foreground }]} numberOfLines={2}>{title}</Text>
              <Text style={[s.doneCardCat, { color: colors.primary }]}>
                {CATEGORIES.find((c) => c.id === selectedCategory)?.name}
              </Text>
            </View>
          </View>

          <View style={s.doneActions}>
            <TouchableOpacity
              onPress={reset}
              style={[s.doneBtn, { borderColor: colors.border, borderWidth: 1.5 }]}
              activeOpacity={0.85}
            >
              <Ionicons name="add-circle-outline" size={18} color={colors.foreground} />
              <Text style={[s.doneBtnText, { color: colors.foreground }]}>Upload Another</Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => router.back()}
              style={[s.doneBtn, { backgroundColor: colors.primary }]}
              activeOpacity={0.85}
            >
              <Ionicons name="home-outline" size={18} color="#fff" />
              <Text style={[s.doneBtnText, { color: '#fff' }]}>Go to Feed</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  header: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    paddingHorizontal: 16, paddingBottom: 14, borderBottomWidth: 1,
  },
  backBtn: { width: 36, height: 36, alignItems: 'center', justifyContent: 'center' },
  headerTitle: { fontSize: 17, fontFamily: 'Poppins_700Bold' },
  scroll: { padding: 16 },

  pickBanner: {
    borderRadius: 20, padding: 28, alignItems: 'center', gap: 10, marginBottom: 20,
  },
  pickTitle: { fontSize: 22, fontFamily: 'Poppins_700Bold' },
  pickSub: { fontSize: 14, fontFamily: 'Poppins_400Regular', textAlign: 'center', lineHeight: 20 },
  pickActions: { gap: 12, marginBottom: 24 },
  pickBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 14,
    padding: 16, borderRadius: 16,
  },
  pickBtnPrimary: {},
  pickBtnIcon: {
    width: 54, height: 54, borderRadius: 14,
    backgroundColor: 'rgba(255,255,255,0.2)',
    alignItems: 'center', justifyContent: 'center',
  },
  pickBtnInfo: { flex: 1 },
  pickBtnLabel: { color: '#fff', fontSize: 15, fontFamily: 'Poppins_600SemiBold' },
  pickBtnDesc: { color: 'rgba(255,255,255,0.7)', fontSize: 12, fontFamily: 'Poppins_400Regular', marginTop: 2 },
  tipsCard: { borderRadius: 16, borderWidth: 1, padding: 16, gap: 12 },
  tipsTitle: { fontSize: 14, fontFamily: 'Poppins_700Bold', marginBottom: 2 },
  tipRow: { flexDirection: 'row', alignItems: 'center', gap: 10 },
  tipText: { fontSize: 13, fontFamily: 'Poppins_400Regular', flex: 1 },

  previewWrap: { alignItems: 'center', marginBottom: 20 },
  preview: {
    width: 160, height: 220, borderRadius: 16,
    alignItems: 'center', justifyContent: 'center',
  },
  durationTag: {
    position: 'absolute', bottom: 10, right: 10,
    backgroundColor: 'rgba(0,0,0,0.5)', paddingHorizontal: 8, paddingVertical: 3, borderRadius: 6,
  },
  durationTagText: { color: '#fff', fontSize: 12, fontFamily: 'Poppins_600SemiBold' },
  changeBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6,
    marginTop: 10, paddingHorizontal: 14, paddingVertical: 7,
    borderRadius: 20, borderWidth: 1,
  },
  changeBtnText: { fontSize: 13, fontFamily: 'Poppins_500Medium' },

  form: { gap: 8 },
  label: { fontSize: 14, fontFamily: 'Poppins_600SemiBold', marginTop: 8, marginBottom: 4 },
  input: {
    borderWidth: 1, borderRadius: 12,
    paddingHorizontal: 14, paddingVertical: 13,
    fontSize: 15, fontFamily: 'Poppins_400Regular',
  },
  textArea: { height: 88, textAlignVertical: 'top', paddingTop: 12 },
  charCount: { fontSize: 11, fontFamily: 'Poppins_400Regular', textAlign: 'right', marginTop: -4 },
  catRow: { gap: 8, paddingRight: 8, marginBottom: 4 },
  catChip: { paddingHorizontal: 14, paddingVertical: 8, borderRadius: 20, borderWidth: 1 },
  catChipText: { fontSize: 13, fontFamily: 'Poppins_500Medium' },
  earningsToggle: {
    flexDirection: 'row', alignItems: 'center', gap: 12,
    padding: 14, borderRadius: 14, borderWidth: 1.5, marginVertical: 4,
  },
  earningsToggleIcon: { width: 40, height: 40, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
  earningsToggleInfo: { flex: 1 },
  earningsToggleLabel: { fontSize: 14, fontFamily: 'Poppins_600SemiBold' },
  earningsToggleSub: { fontSize: 12, fontFamily: 'Poppins_400Regular', marginTop: 2 },
  toggle: { width: 42, height: 24, borderRadius: 12, justifyContent: 'center' },
  toggleThumb: { width: 20, height: 20, borderRadius: 10, backgroundColor: '#fff' },
  uploadBtn: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10,
    borderRadius: 14, paddingVertical: 16, marginTop: 12,
  },
  uploadBtnText: { color: '#fff', fontSize: 16, fontFamily: 'Poppins_700Bold' },

  uploadingScreen: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32, gap: 16 },
  uploadingThumb: { width: 140, height: 190, borderRadius: 16, alignItems: 'center', justifyContent: 'center', marginBottom: 8 },
  uploadingTitle: { fontSize: 18, fontFamily: 'Poppins_700Bold', textAlign: 'center', lineHeight: 26 },
  uploadingStage: { fontSize: 14, fontFamily: 'Poppins_600SemiBold' },
  progressTrack: { width: '100%', height: 6, borderRadius: 3, overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 3 },
  uploadingHint: { fontSize: 12, fontFamily: 'Poppins_400Regular', textAlign: 'center' },

  doneScreen: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 28, gap: 14 },
  checkCircle: { width: 96, height: 96, borderRadius: 48, alignItems: 'center', justifyContent: 'center', marginBottom: 8 },
  doneTitle: { fontSize: 28, fontFamily: 'Poppins_700Bold' },
  doneSub: { fontSize: 14, fontFamily: 'Poppins_400Regular', textAlign: 'center', lineHeight: 20 },
  doneCard: {
    flexDirection: 'row', gap: 12, alignItems: 'center',
    width: '100%', borderRadius: 14, borderWidth: 1, padding: 12,
  },
  doneThumb: { width: 56, height: 72, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
  doneCardInfo: { flex: 1 },
  doneCardTitle: { fontSize: 14, fontFamily: 'Poppins_600SemiBold', lineHeight: 20 },
  doneCardCat: { fontSize: 12, fontFamily: 'Poppins_500Medium', marginTop: 4 },
  doneActions: { flexDirection: 'row', gap: 10, width: '100%', marginTop: 8 },
  doneBtn: {
    flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center',
    gap: 8, paddingVertical: 14, borderRadius: 14,
  },
  doneBtnText: { fontSize: 14, fontFamily: 'Poppins_700Bold' },
});
