import { router, useLocalSearchParams } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { ImageBackground, StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import type { ImageSourcePropType } from 'react-native';
import type { ListingKind } from '@navi/types';
import { ListingCard } from '../../src/components/cards/CatalogCard';
import { NaviHeader } from '../../src/components/layout/NaviHeader';
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';

interface ServiceConfig {
  i18nKey: 'stays' | 'activities' | 'taxi' | 'food' | 'pharmacy' | 'grocery' | 'sim';
  kind: ListingKind;
  hero: ImageSourcePropType;
  note?: boolean;
}

const SERVICE = {
  stays: {
    i18nKey: 'stays',
    kind: 'STAY',
    hero: naviAssets.hotels.atlantisCard,
  },
  activities: {
    i18nKey: 'activities',
    kind: 'ACTIVITY',
    hero: naviAssets.experiences.desertSafari,
  },
  taxi: {
    i18nKey: 'taxi',
    kind: 'TAXI_TIER',
    hero: naviAssets.services.taxiMap,
  },
  food: {
    i18nKey: 'food',
    kind: 'RESTAURANT',
    hero: naviAssets.food.goldenGrill,
  },
  pharmacy: {
    i18nKey: 'pharmacy',
    kind: 'PHARMACY',
    hero: naviAssets.pharmacy.prescriptionBg,
    note: true,
  },
  grocery: {
    i18nKey: 'grocery',
    kind: 'GROCERY',
    hero: naviAssets.grocery.freeDelivery,
  },
  sim: {
    i18nKey: 'sim',
    kind: 'SIM_PLAN',
    hero: naviAssets.sim.hero,
  },
} satisfies Record<string, ServiceConfig>;

const DEFAULT_SERVICE = SERVICE.stays;

export default function ServiceScreen() {
  const { t } = useTranslation();
  const { type } = useLocalSearchParams<{ type: string }>();
  const locale = useLocale((s) => s.locale);
  const service = serviceFor(type);
  const title = t(`serviceScreens.${service.i18nKey}.title`);
  const subtitle = t(`serviceScreens.${service.i18nKey}.subtitle`);
  const listings = useQuery({
    queryKey: ['service', service.kind],
    queryFn: () => api.listings.list({ kind: service.kind }),
  });

  return (
    <Screen>
      <NaviHeader variant="center" title={title} showBack onBack={() => router.replace('/(tabs)/home')} />
      <ImageBackground source={service.hero} style={styles.hero} imageStyle={styles.heroImage}>
        <View style={styles.heroOverlay}>
          <Text style={styles.h1}>{title}</Text>
          <Text style={styles.sub}>{subtitle}</Text>
        </View>
      </ImageBackground>

      {service.note ? (
        <View style={styles.note}>
          <Text style={styles.noteText}>{t('serviceScreens.pharmacy.note')}</Text>
        </View>
      ) : null}

      {listings.isLoading ? <StateView tone="loading" title={t('serviceScreens.loading', { title })} /> : null}
      {listings.isError ? <StateView tone="error" title={t('serviceScreens.unavailableTitle')} body={t('serviceScreens.unavailableBody')} /> : null}
      {!listings.isLoading && !(listings.data ?? []).length ? (
        <StateView tone="empty" title={t('serviceScreens.emptyTitle')} body={t('serviceScreens.emptyBody')} />
      ) : null}
      {(listings.data ?? []).map((listing) => (
        <ListingCard
          key={listing.id}
          listing={listing}
          locale={locale}
          ctaLabel={listing.kind === 'STAY' ? t('actions.selectRoom') : listing.kind === 'ACTIVITY' ? t('actions.book') : t('actions.view')}
          onPress={() => router.push(`/listing/${listing.id}`)}
        />
      ))}
    </Screen>
  );
}

function serviceFor(type: string | undefined): ServiceConfig {
  if (type && Object.prototype.hasOwnProperty.call(SERVICE, type)) {
    return SERVICE[type as keyof typeof SERVICE];
  }
  return DEFAULT_SERVICE;
}

const styles = StyleSheet.create({
  hero: {
    backgroundColor: color.blue[600],
    borderRadius: radius.xl,
    height: 238,
    overflow: 'hidden',
  },
  heroImage: {
    borderRadius: radius.xl,
  },
  heroOverlay: {
    backgroundColor: 'rgba(11,18,32,0.38)',
    flex: 1,
    justifyContent: 'flex-end',
    padding: spacing[5],
  },
  h1: {
    color: color.bg[0],
    fontSize: 32,
    fontWeight: '900',
    lineHeight: 38,
  },
  sub: {
    color: color.bg[0],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
    marginTop: spacing[2],
    opacity: 0.94,
  },
  note: {
    backgroundColor: '#FFF4DE',
    borderColor: '#FFE0A3',
    borderRadius: radius.lg,
    borderWidth: 1,
    padding: spacing[4],
  },
  noteText: {
    color: '#7A4B00',
    fontSize: typography.scale.caption.size,
    fontWeight: '700',
    lineHeight: 19,
  },
});
