import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  ActivityIndicator,
  RefreshControl,
  ListRenderItemInfo,
} from 'react-native';
import { fetchScripts, Script } from '../api/client';

function SkillCard({ item }: { item: Script }): React.JSX.Element {
  const savingColor =
    item.avg_saving_pct >= 70
      ? '#22c55e'
      : item.avg_saving_pct >= 40
      ? '#f59e0b'
      : '#c9cdd8';

  return (
    <View style={styles.card}>
      <View style={styles.cardHeader}>
        <Text style={styles.skillName} numberOfLines={1}>
          {item.name}
        </Text>
        <View style={styles.badge}>
          <Text style={[styles.badgeText, { color: savingColor }]}>
            {item.avg_saving_pct > 0 ? `${item.avg_saving_pct.toFixed(0)}% saved` : 'No data'}
          </Text>
        </View>
      </View>
      <Text style={styles.skillDesc} numberOfLines={2}>
        {item.description}
      </Text>
      <View style={styles.cardFooter}>
        <Text style={styles.footerText}>
          {item.usage_count} {item.usage_count === 1 ? 'use' : 'uses'}
        </Text>
        <Text style={styles.footerText}>v{item.version}</Text>
        {item.tags.length > 0 && (
          <Text style={styles.tags}>{item.tags.slice(0, 3).join(' · ')}</Text>
        )}
      </View>
    </View>
  );
}

function EmptyState(): React.JSX.Element {
  return (
    <View style={styles.empty}>
      <Text style={styles.emptyIcon}>🧩</Text>
      <Text style={styles.emptyText}>No skills installed</Text>
      <Text style={styles.emptySubtext}>
        Install skill packs via the CLI:{'\n'}
        <Text style={styles.code}>bibividi add scripts/pdf-clause-extractor/</Text>
      </Text>
    </View>
  );
}

export function SkillsScreen(): React.JSX.Element {
  const [scripts, setScripts] = useState<Script[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setError(null);
    try {
      const data = await fetchScripts();
      setScripts(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load skills');
    }
  }, []);

  useEffect(() => {
    setLoading(true);
    load().finally(() => setLoading(false));
  }, [load]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  if (loading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator size="large" color="#7c3aed" />
        <Text style={styles.loadingText}>Loading skills…</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.center}>
        <Text style={styles.errorIcon}>⚠</Text>
        <Text style={styles.errorText}>{error}</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <View style={styles.headerBar}>
        <Text style={styles.headerTitle}>
          {scripts.length} {scripts.length === 1 ? 'skill' : 'skills'} installed
        </Text>
      </View>
      <FlatList<Script>
        data={scripts}
        keyExtractor={(item) => item.id}
        renderItem={({ item }: ListRenderItemInfo<Script>) => (
          <SkillCard item={item} />
        )}
        ListEmptyComponent={<EmptyState />}
        contentContainerStyle={
          scripts.length === 0 ? styles.emptyContainer : styles.listContent
        }
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor="#7c3aed"
            colors={['#7c3aed']}
          />
        }
        showsVerticalScrollIndicator={false}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0f1117',
  },
  center: {
    flex: 1,
    backgroundColor: '#0f1117',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 12,
  },
  loadingText: {
    color: '#6b7280',
    fontSize: 14,
    marginTop: 8,
  },
  errorIcon: {
    fontSize: 32,
    color: '#ef4444',
  },
  errorText: {
    color: '#ef4444',
    fontSize: 14,
    textAlign: 'center',
    paddingHorizontal: 24,
  },
  headerBar: {
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#2a2d3a',
    backgroundColor: '#1a1d27',
  },
  headerTitle: {
    color: '#6b7280',
    fontSize: 12,
  },
  listContent: {
    padding: 16,
    gap: 12,
    paddingBottom: 32,
  },
  card: {
    backgroundColor: '#1a1d27',
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#2a2d3a',
    padding: 16,
    marginBottom: 12,
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 6,
  },
  skillName: {
    flex: 1,
    color: '#c9cdd8',
    fontSize: 15,
    fontWeight: '700',
    marginRight: 8,
  },
  badge: {
    backgroundColor: '#0f1117',
    borderRadius: 6,
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderWidth: 1,
    borderColor: '#2a2d3a',
  },
  badgeText: {
    fontSize: 11,
    fontWeight: '600',
  },
  skillDesc: {
    color: '#6b7280',
    fontSize: 13,
    lineHeight: 18,
    marginBottom: 10,
  },
  cardFooter: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
  },
  footerText: {
    color: '#6b7280',
    fontSize: 11,
  },
  tags: {
    color: '#7c3aed',
    fontSize: 11,
    flex: 1,
    textAlign: 'right',
  },
  emptyContainer: {
    flex: 1,
  },
  empty: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 80,
    paddingHorizontal: 32,
    gap: 8,
  },
  emptyIcon: {
    fontSize: 40,
    marginBottom: 8,
  },
  emptyText: {
    color: '#c9cdd8',
    fontSize: 16,
    fontWeight: '600',
  },
  emptySubtext: {
    color: '#6b7280',
    fontSize: 13,
    textAlign: 'center',
    lineHeight: 20,
    marginTop: 4,
  },
  code: {
    color: '#7c3aed',
    fontFamily: 'monospace',
    fontSize: 12,
  },
});
