import React, {useState} from 'react';
import {
  ActivityIndicator,
  Alert,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import Modal from 'react-native-modal';
import {AddonManifest} from '../../api/addonTypes';
import {addonManager} from '../../api/addonManager';
import {useAddonStore} from '../../store/addonStore';
import {colors, typography} from '../../utils/colors';

interface Props {
  visible: boolean;
  onClose: () => void;
  onInstalled: (manifest: AddonManifest) => void;
}

type Step = 'input' | 'preview' | 'installing';

export default function AddonInstaller({visible, onClose, onInstalled}: Props) {
  const {refresh} = useAddonStore();
  const [url, setUrl] = useState('');
  const [step, setStep] = useState<Step>('input');
  const [loading, setLoading] = useState(false);
  const [preview, setPreview] = useState<AddonManifest | null>(null);
  const [normalizedUrl, setNormalizedUrl] = useState('');

  const handleFetch = async () => {
    if (!url.trim()) return;
    setLoading(true);
    try {
      const norm = addonManager.normalizeUrl(url.trim());
      setNormalizedUrl(norm);
      const {default: axios} = await import('axios');
      const res = await axios.get(norm, {timeout: 10000});
      setPreview(res.data as AddonManifest);
      setStep('preview');
    } catch (e) {
      Alert.alert('Error', `Failed to fetch addon: ${String(e)}`);
    } finally {
      setLoading(false);
    }
  };

  const handleInstall = async () => {
    if (!preview) return;
    setStep('installing');
    try {
      // Use already-fetched manifest — no second network request
      await addonManager.saveAddon(normalizedUrl, preview);
      refresh(); // update the Zustand store so the list re-renders
      onInstalled(preview);
      handleClose();
    } catch (e) {
      Alert.alert('Install Error', String(e));
      setStep('preview');
    }
  };

  const handleClose = () => {
    setUrl('');
    setNormalizedUrl('');
    setStep('input');
    setPreview(null);
    onClose();
  };

  return (
    <Modal
      isVisible={visible}
      onBackdropPress={handleClose}
      onBackButtonPress={handleClose}
      style={styles.modal}
      avoidKeyboard>
      <View style={styles.container}>
        <Text style={styles.title}>Install Addon</Text>

        {step === 'input' && (
          <>
            <TextInput
              style={styles.input}
              value={url}
              onChangeText={setUrl}
              placeholder="https://example.com/manifest.json"
              placeholderTextColor={colors.textMuted}
              autoCapitalize="none"
              autoCorrect={false}
              keyboardType="url"
              autoFocus
            />
            <Text style={styles.hint}>
              Supports: https://, stremio://, or streamvault://addon/ URLs
            </Text>
            <TouchableOpacity
              style={styles.primaryBtn}
              onPress={handleFetch}
              disabled={loading}>
              {loading ? (
                <ActivityIndicator color={colors.textPrimary} />
              ) : (
                <Text style={styles.primaryBtnText}>Fetch Addon</Text>
              )}
            </TouchableOpacity>
          </>
        )}

        {step === 'preview' && preview && (
          <>
            <View style={styles.previewCard}>
              <Text style={styles.previewName}>{preview.name}</Text>
              <Text style={styles.previewVersion}>v{preview.version}</Text>
              {preview.description && (
                <Text style={styles.previewDesc}>{preview.description}</Text>
              )}
              <Text style={styles.previewMeta}>
                Types: {preview.types.join(', ')}
              </Text>
              <Text style={styles.previewMeta}>
                Resources:{' '}
                {preview.resources
                  .map(r => (typeof r === 'string' ? r : r.name))
                  .join(', ')}
              </Text>
            </View>
            <TouchableOpacity style={styles.primaryBtn} onPress={handleInstall}>
              <Text style={styles.primaryBtnText}>Install Addon</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.secondaryBtn} onPress={() => setStep('input')}>
              <Text style={styles.secondaryBtnText}>Back</Text>
            </TouchableOpacity>
          </>
        )}

        {step === 'installing' && (
          <View style={styles.installProgress}>
            <ActivityIndicator size="large" color={colors.primary} />
            <Text style={styles.installText}>Installing...</Text>
          </View>
        )}

        <TouchableOpacity style={styles.cancelBtn} onPress={handleClose}>
          <Text style={styles.cancelText}>Cancel</Text>
        </TouchableOpacity>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modal: {justifyContent: 'flex-end', margin: 0},
  container: {
    backgroundColor: colors.surface,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    paddingBottom: 36,
  },
  title: {
    ...typography.title,
    color: colors.textPrimary,
    marginBottom: 16,
    textAlign: 'center',
  },
  input: {
    backgroundColor: colors.surfaceLight,
    borderRadius: 10,
    padding: 12,
    color: colors.textPrimary,
    fontSize: 14,
    marginBottom: 8,
  },
  hint: {...typography.caption, color: colors.textMuted, marginBottom: 16},
  primaryBtn: {
    backgroundColor: colors.primary,
    padding: 14,
    borderRadius: 10,
    alignItems: 'center',
    marginBottom: 10,
  },
  primaryBtnText: {...typography.subtitle, color: colors.textPrimary, fontWeight: '700'},
  secondaryBtn: {
    borderWidth: 1,
    borderColor: colors.border,
    padding: 14,
    borderRadius: 10,
    alignItems: 'center',
    marginBottom: 10,
  },
  secondaryBtnText: {...typography.subtitle, color: colors.textSecondary},
  cancelBtn: {padding: 14, alignItems: 'center'},
  cancelText: {...typography.body, color: colors.textMuted},
  previewCard: {
    backgroundColor: colors.surfaceLight,
    borderRadius: 12,
    padding: 14,
    marginBottom: 16,
  },
  previewName: {...typography.subtitle, color: colors.textPrimary, marginBottom: 2},
  previewVersion: {...typography.caption, color: colors.textMuted, marginBottom: 8},
  previewDesc: {...typography.body, color: colors.textSecondary, marginBottom: 8},
  previewMeta: {...typography.caption, color: colors.textMuted, marginBottom: 4},
  installProgress: {alignItems: 'center', padding: 30, gap: 16},
  installText: {...typography.subtitle, color: colors.textSecondary},
});
