import { router } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { ImageBackground, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { ListingCard } from '../../src/components/cards/CatalogCard';
import { NaviHeader } from '../../src/components/layout/NaviHeader';
import { SectionHeader } from '../../src/components/layout/SectionHeader';
import { ServiceTile } from '../../src/components/service/ServiceTile';
import { Screen } from '../../src/components/Screen';
import { StateView } from '../../src/components/StateView';
import { api } from '../../src/api/client';
import { useLocale } from '../../src/state/locale';
import { naviAssets } from '../../src/assets/naviAssets';
import { color, radius, spacing, typography } from '../../src/theme';
import { naviTheme } from '../../src/theme/naviTheme';

const SERVICES = [
  { key: 'stays', icon: 'ST', target: '/services/stays', tone: 'blue' },
  { key: 'activities', icon: 'AC', target: '/services/activities', tone: 'teal' },
  { key: 'taxi', icon: 'TX', target: '/services/taxi', tone: 'orange' },
  { key: 'food', icon: 'FD', target: '/services/food', tone: 'teal' },
  { key: 'pharmacies', icon: 'PH', target: '/services/pharmacy', tone: 'blue' },
  { key: 'groceries', icon: 'GR', target: '/services/grocery', tone: 'teal' },
  { key: 'sim', icon: '5G', target: '/services/sim', tone: 'blue' },
  { key: 'emergency', icon: '!', target: '/emergency', tone: 'red' },
] as const;

export default function Home() {
  const { t } = useTranslation();
  const locale = useLocale((s) => s.locale);
  const home = useQuery({ queryKey: ['home'], queryFn: () => api.search.home() });
  const emirates = useQuery({ queryKey: ['emirates'], queryFn: () => api.geo.emirates() });

  const featured = (home.data?.featuredListings ?? []).filter((item) => item.kind === 'ACTIVITY' || item.kind === 'STAY').slice(0, 6);

  return (
    <Screen>
      <NaviHeader variant="brand" />

      <ImageBackground source={naviAssets.destinations.homeHero} style={styles.hero} imageStyle={styles.heroImage}>
        <View style={styles.heroOverlay}>
          <Text style={styles.heroTitle}>{t('home.exploreEmirates')}</Text>
          <Text style={styles.heroBody}>{t('home.allInOne')}</Text>
          <Pressable style={styles.searchBar} onPress={() => router.push('/(tabs)/discover')} accessibilityRole="button">
            <Text style={styles.searchText}>{t('home.whereTo')}</Text>
          </Pressable>
        </View>
      </ImageBackground>

      <View style={styles.grid}>
        {SERVICES.map((service) => (
          <ServiceTile
            key={service.key}
            label={t(`services.${service.key}`)}
            icon={service.icon}
            tone={service.tone}
            onPress={() => router.push(service.target)}
          />
        ))}
      </View>

      <Pressable onPress={() => router.push('/services/stays')} accessibilityRole="button">
        <ImageBackground source={naviAssets.destinations.rakOffer} style={styles.offer} imageStyle={styles.offerImage}>
          <View style={styles.offerOverlay}>
            <Text style={styles.offerEyebrow}>{t('home.weekendGetaways')}</Text>
            <Text style={styles.offerTitle}>{t('home.rakStays')}</Text>
            <Text style={styles.offerCta}>{t('actions.bookNow')}</Text>
          </View>
        </ImageBackground>
      </Pressable>

      <SectionHeader title={t('home.featuredExperiences')} actionLabel={t('actions.seeAll')} onAction={() => router.push('/(tabs)/discover')} />
      {home.isLoading ? <StateView tone="loading" title={t('home.loadingExperiences')} /> : null}
      {home.isError ? <StateView tone="error" title={t('home.catalogUnavailable')} body={t('home.refreshRetry')} /> : null}
      {featured.length ? (
        <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.rail}>
          {featured.map((item) => (
            <View key={item.id} style={styles.railItem}>
              <ListingCard
                listing={item}
                locale={locale}
                ctaLabel={t('actions.explore')}
                onPress={() => router.push(`/listing/${item.id}`)}
              />
            </View>
          ))}
        </ScrollView>
      ) : null}

      <SectionHeader title={t('home.sevenEmirates')} />
      <View style={styles.emirates}>
        {(emirates.data ?? []).slice(0, 8).map((city) => (
          <Pressable key={city.id} style={styles.emirateChip} onPress={() => router.push('/(tabs)/discover')} accessibilityRole="button">
            <Text style={styles.emirateName}>{city.name}</Text>
            <Text style={styles.emirateMeta}>{city.emirateCode}</Text>
          </Pressable>
        ))}
      </View>
    </Screen>
  );
}

const styles = StyleSheet.create({
  hero: {
    backgroundColor: color.blue[600],
    borderRadius: radius.xl,
    height: 254,
    overflow: 'hidden',
    ...naviTheme.shadows.imageCard,
  },
  heroImage: {
    borderRadius: radius.xl,
  },
  heroOverlay: {
    backgroundColor: 'rgba(11,18,32,0.34)',
    flex: 1,
    justifyContent: 'flex-end',
    padding: spacing[5],
  },
  heroTitle: {
    color: color.bg[0],
    fontSize: 34,
    fontWeight: '900',
    lineHeight: 39,
  },
  heroBody: {
    color: color.bg[0],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
    marginTop: spacing[2],
    opacity: 0.94,
  },
  searchBar: {
    backgroundColor: color.bg[0],
    borderRadius: radius.lg,
    height: 54,
    justifyContent: 'center',
    marginTop: spacing[5],
    paddingHorizontal: spacing[4],
  },
  searchText: {
    color: color.ink[500],
    fontWeight: '700',
  },
  grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing[3],
  },
  offer: {
    borderRadius: radius.xl,
    minHeight: 118,
    overflow: 'hidden',
    ...naviTheme.shadows.card,
  },
  offerImage: {
    borderRadius: radius.xl,
  },
  offerOverlay: {
    backgroundColor: 'rgba(11,18,32,0.34)',
    flex: 1,
    gap: spacing[1],
    justifyContent: 'center',
    padding: spacing[5],
  },
  offerEyebrow: {
    color: color.bg[0],
    fontSize: typography.scale.caption.size,
    fontWeight: '800',
    opacity: 0.88,
  },
  offerTitle: {
    color: color.bg[0],
    fontSize: typography.scale.h2.size,
    fontWeight: '900',
    lineHeight: 28,
  },
  offerCta: {
    color: color.bg[0],
    fontWeight: '900',
    marginTop: spacing[2],
  },
  rail: {
    gap: spacing[4],
    paddingRight: spacing[6],
  },
  railItem: {
    width: 288,
  },
  emirates: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing[3],
  },
  emirateChip: {
    backgroundColor: color.bg[0],
    borderColor: color.border,
    borderRadius: radius.lg,
    borderWidth: 1,
    padding: spacing[4],
    width: '47.8%',
  },
  emirateName: {
    color: color.ink[900],
    fontWeight: '800',
  },
  emirateMeta: {
    color: color.ink[500],
    fontSize: typography.scale.caption.size,
    marginTop: spacing[1],
  },
});
