// Sceny dla wybranego tagu. Reuse listScenes z parameter `tags=<slug>`.
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useQuery } from '@tanstack/react-query';
import React from 'react';
import {
  FlatList,
  Pressable,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { SceneTile, sceneGridProps } from '../components/SceneTile';
import { SceneGridSkeleton } from '../components/SceneGridSkeleton';
import { useClient } from '../ClientContext';
import { usePreferences } from '../PreferencesContext';
import type { RootStackParamList } from '../navigation';
import { theme } from '../theme';
import type { SceneOut } from '../types';

export function TagScenesScreen() {
  const client = useClient();
  const { gridColumns } = usePreferences();
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList, 'TagScenes'>>();
  const route = useRoute<RouteProp<RootStackParamList, 'TagScenes'>>();
  const { slug, name } = route.params;

  React.useLayoutEffect(() => {
    navigation.setOptions({ title: name });
  }, [navigation, name]);

  const { data, isLoading, error, refetch, isRefetching } = useQuery({
    queryKey: ['tag-scenes', slug],
    queryFn: () =>
      client.listScenes({
        tags: [slug],
        sort: 'release_date',
        has_playback: true,
        per_page: 200,
      }),
  });

  return (
    <View style={styles.container}>
      {error instanceof Error && <Text style={styles.error}>{error.message}</Text>}

      {isLoading ? (
        <SceneGridSkeleton count={10} />
      ) : (
      <FlatList
        {...sceneGridProps(gridColumns)}
        data={data?.items ?? []}
        keyExtractor={(s) => s.id}
        removeClippedSubviews={false}
        renderItem={({ item }) => <SceneTile scene={item} secondLine="studio" />}
        refreshing={isRefetching}
        onRefresh={refetch}
        ListHeaderComponent={
          data ? (
            <Text style={styles.subtitle}>
              {data.total}{data.total_capped ? '+' : ''} {data.total === 1 ? 'scene' : 'scenes'} · with playback
            </Text>
          ) : null
        }
        ListEmptyComponent={!isLoading ? <Text style={styles.muted}>no scenes</Text> : null}
        contentContainerStyle={{ paddingBottom: 24 }}
      />
      )}
    </View>
  );
}

function SceneRow({ scene }: { scene: SceneOut }) {
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList, 'TagScenes'>>();
  const performers = scene.performers
    .slice(0, 3)
    .map((p) => p.canonical_name)
    .join(', ');
  return (
    <Pressable
      style={styles.row}
      onPress={() => navigation.push('SceneDetail', { id: scene.id })}
    >
      <Text style={styles.rowTitle} numberOfLines={1}>
        {scene.title}
      </Text>
      {scene.release_date || scene.studio ? (
        <Text style={styles.rowMuted} numberOfLines={1}>
          {[scene.release_date, scene.studio?.name].filter(Boolean).join(' · ')}
        </Text>
      ) : null}
      {performers ? (
        <Text style={styles.rowMuted} numberOfLines={1}>
          {performers}
          {scene.performers.length > 3 ? ` +${scene.performers.length - 3}` : ''}
        </Text>
      ) : null}
      <Text style={styles.rowSources}>
        {[...new Set(scene.external_refs.map((r) => r.source))].join(' · ')}
        {scene.playback_sources.length > 0 ? `  ▶ ${scene.playback_sources.length}` : ''}
      </Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: theme.bg, paddingHorizontal: 12, paddingTop: 8 },
  gridRow: { gap: 10, marginBottom: 14 },
  subtitle: { color: theme.muted, marginBottom: 8, paddingHorizontal: 4 },
  row: {
    backgroundColor: theme.card,
    borderColor: theme.border,
    borderWidth: 1,
    borderRadius: 8,
    padding: 12,
    marginBottom: 8,
  },
  rowTitle: { color: theme.fg, fontWeight: '600', marginBottom: 2 },
  rowMuted: { color: theme.muted, fontSize: 13, marginTop: 2 },
  rowSources: { color: theme.accent, fontSize: 11, marginTop: 4, textTransform: 'uppercase' },
  muted: { color: theme.muted, textAlign: 'center', marginTop: 24 },
  error: { color: theme.bad, padding: 12 },
});
