import { useMemo, useState } from 'react';
import { router, useLocalSearchParams } from 'expo-router';
import { useMutation, useQuery } from '@tanstack/react-query';
import { StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { generateTripSchema } from '@navi/validators';
import type { GenerateTripBody } from '@navi/api-client';
import { FilterChip } from '../../src/components/cards/CatalogCard';
import { NaviHeader } from '../../src/components/layout/NaviHeader';
import { PrimaryButton } from '../../src/components/PrimaryButton';
import { Screen } from '../../src/components/Screen';
import { StateView } from '../../src/components/StateView';
import { api } from '../../src/api/client';
import { useAuth } from '../../src/state/auth';
import { useTripPlanner } from '../../src/state/tripPlanner';
import { color, radius, spacing, typography } from '../../src/theme';

const PARTIES: Array<{ labelKey: string; value: GenerateTripBody['party'] }> = [
  { labelKey: 'tripPlanner.party.solo', value: 'SOLO' },
  { labelKey: 'tripPlanner.party.couple', value: 'COUPLE' },
  { labelKey: 'tripPlanner.party.family', value: 'FAMILY' },
  { labelKey: 'tripPlanner.party.friends', value: 'FRIENDS' },
];

const INTERESTS: Array<{ labelKey: string; value: GenerateTripBody['interests'][number] }> = [
  { labelKey: 'tripPlanner.interest.adventure', value: 'ADVENTURE' },
  { labelKey: 'tripPlanner.interest.luxury', value: 'LUXURY' },
  { labelKey: 'tripPlanner.interest.culture', value: 'CULTURE' },
  { labelKey: 'tripPlanner.interest.relaxation', value: 'RELAXATION' },
  { labelKey: 'tripPlanner.interest.ecotourism', value: 'ECOTOURISM' },
  { labelKey: 'tripPlanner.interest.foodDrink', value: 'FOOD_DRINK' },
  { labelKey: 'tripPlanner.interest.wellness', value: 'WELLNESS' },
  { labelKey: 'tripPlanner.interest.nightlife', value: 'NIGHTLIFE' },
];

const BUDGETS: Array<{ labelKey: string; value: GenerateTripBody['budget'] }> = [
  { labelKey: 'tripPlanner.budget.economy', value: 'ECONOMY' },
  { labelKey: 'tripPlanner.budget.standard', value: 'STANDARD' },
  { labelKey: 'tripPlanner.budget.premium', value: 'PREMIUM' },
];

const PACES: Array<{ labelKey: string; value: GenerateTripBody['pace'] }> = [
  { labelKey: 'tripPlanner.paceValue.relaxed', value: 'RELAXED' },
  { labelKey: 'tripPlanner.paceValue.moderate', value: 'MODERATE' },
  { labelKey: 'tripPlanner.paceValue.fast', value: 'FAST' },
];

export default function TripPlannerStep() {
  const { t } = useTranslation();
  const { step } = useLocalSearchParams<{ step: string }>();
  const idx = Math.max(1, Math.min(3, Number(step) || 1));
  const user = useAuth((s) => s.user);
  const planner = useTripPlanner();
  const [error, setError] = useState<string | null>(null);
  const emirates = useQuery({ queryKey: ['emirates'], queryFn: () => api.geo.emirates() });
  const selectedNames = useMemo(
    () => (emirates.data ?? []).filter((city) => planner.cityIds.includes(city.id)).map((city) => city.name),
    [emirates.data, planner.cityIds],
  );

  const generate = useMutation({
    mutationFn: async () => {
      const body = planner.toBody();
      const parsed = generateTripSchema.safeParse(body);
      if (!parsed.success) {
        throw new Error(parsed.error.issues[0]?.message ?? t('tripPlanner.completeFields'));
      }
      return api.tripPlanner.generate(parsed.data);
    },
    onSuccess: (trip) => {
      router.replace(`/trip-planner/result/${trip.id}`);
    },
    onError: (e) => {
      setError(e instanceof Error ? e.message : t('tripPlanner.generateFailed'));
    },
  });

  function goNext() {
    setError(null);
    if (idx === 1 && planner.cityIds.length === 0) {
      setError(t('tripPlanner.pickEmirate'));
      return;
    }
    if (idx === 2 && planner.interests.length === 0) {
      setError(t('tripPlanner.pickInterest'));
      return;
    }
    router.replace(`/trip-planner/${idx + 1}`);
  }

  return (
    <Screen>
      <NaviHeader
        variant="planner"
        showBack
        title={titleForStep(idx, t)}
        stepText={t('tripPlanner.stepText', { step: idx })}
        progress={idx / 3}
        onBack={() => (idx > 1 ? router.replace(`/trip-planner/${idx - 1}`) : router.replace('/(tabs)/home'))}
      />
      <Text style={styles.h1}>{titleForStep(idx, t)}</Text>
      <Text style={styles.body}>{bodyForStep(idx, t)}</Text>

      {idx === 1 ? (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t('tripPlanner.selectEmirates')}</Text>
          {emirates.isLoading ? <StateView tone="loading" title={t('tripPlanner.loadingEmirates')} /> : null}
          <View style={styles.chipWrap}>
            {(emirates.data ?? []).map((city) => (
              <FilterChip
                key={city.id}
                label={city.name}
                active={planner.cityIds.includes(city.id)}
                onPress={() => planner.toggleCity(city.id)}
              />
            ))}
          </View>
          <Text style={styles.sectionTitle}>{t('tripPlanner.travelDates')}</Text>
          <View style={styles.dateCard}>
            <Text style={styles.dateText}>{t('tripPlanner.dateRange', { start: planner.startDate, end: planner.endDate })}</Text>
            <View style={styles.chipWrap}>
              <FilterChip label={t('tripPlanner.thisWeekend')} onPress={() => planner.setDates(isoDaysFromNow(3), isoDaysFromNow(5))} />
              <FilterChip label={t('tripPlanner.nextWeek')} onPress={() => planner.setDates(isoDaysFromNow(7), isoDaysFromNow(10))} />
              <FilterChip label={t('tripPlanner.inOneMonth')} onPress={() => planner.setDates(isoDaysFromNow(30), isoDaysFromNow(35))} />
            </View>
          </View>
        </View>
      ) : null}

      {idx === 2 ? (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t('tripPlanner.whoComing')}</Text>
          <View style={styles.chipWrap}>
            {PARTIES.map((party) => (
              <FilterChip
                key={party.value}
                label={t(party.labelKey)}
                active={planner.party === party.value}
                onPress={() => planner.setParty(party.value)}
              />
            ))}
          </View>
          <Text style={styles.sectionTitle}>{t('tripPlanner.interests')}</Text>
          <View style={styles.chipWrap}>
            {INTERESTS.map((interest) => (
              <FilterChip
                key={interest.value}
                label={t(interest.labelKey)}
                active={planner.interests.includes(interest.value)}
                onPress={() => planner.toggleInterest(interest.value)}
              />
            ))}
          </View>
          <View style={styles.infoCard}>
            <Text style={styles.infoTitle}>{t('tripPlanner.curatedByAi')}</Text>
            <Text style={styles.infoBody}>{t('tripPlanner.aiBody')}</Text>
          </View>
        </View>
      ) : null}

      {idx === 3 ? (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t('tripPlanner.investment')}</Text>
          <View style={styles.chipWrap}>
            {BUDGETS.map((budget) => (
              <FilterChip
                key={budget.value}
                label={t(budget.labelKey)}
                active={planner.budget === budget.value}
                onPress={() => planner.setBudget(budget.value)}
              />
            ))}
          </View>
          <Text style={styles.sectionTitle}>{t('tripPlanner.pace')}</Text>
          <View style={styles.chipWrap}>
            {PACES.map((pace) => (
              <FilterChip
                key={pace.value}
                label={t(pace.labelKey)}
                active={planner.pace === pace.value}
                onPress={() => planner.setPace(pace.value)}
              />
            ))}
          </View>
          <View style={styles.summaryCard}>
            <Text style={styles.infoTitle}>{t('tripPlanner.journeyFlow')}</Text>
            <Text style={styles.infoBody}>
              {selectedNames.length ? selectedNames.join(', ') : t('tripPlanner.noEmirates')} · {planner.party.toLowerCase()} · {planner.budget.toLowerCase()} · {planner.pace.toLowerCase()}
            </Text>
          </View>
        </View>
      ) : null}

      {error ? <StateView tone="error" title={t('tripPlanner.checkTrip')} body={error} /> : null}

      {idx < 3 ? (
        <PrimaryButton label={t('actions.next')} onPress={goNext} />
      ) : user ? (
        <PrimaryButton
          label={generate.isPending ? t('actions.generating') : t('actions.generateMyTrip')}
          onPress={() => {
            setError(null);
            generate.mutate();
          }}
          disabled={generate.isPending}
        />
      ) : (
        <>
          <StateView tone="denied" title={t('tripPlanner.signInTitle')} body={t('tripPlanner.signInBody')} />
          <PrimaryButton label={t('actions.signIn')} onPress={() => router.push('/(auth)/login')} />
        </>
      )}
    </Screen>
  );
}

function titleForStep(step: number, t: (key: string) => string): string {
  if (step === 1) return t('tripPlanner.whereTitle');
  if (step === 2) return t('tripPlanner.vibeTitle');
  return t('tripPlanner.journeyTitle');
}

function bodyForStep(step: number, t: (key: string) => string): string {
  if (step === 1) return t('tripPlanner.whereBody');
  if (step === 2) return t('tripPlanner.vibeBody');
  return t('tripPlanner.journeyBody');
}

function isoDaysFromNow(days: number): string {
  const date = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
  return date.toISOString().slice(0, 10);
}

const styles = StyleSheet.create({
  crumb: {
    color: color.ink[500],
    fontSize: typography.scale.caption.size,
    fontWeight: '900',
  },
  h1: {
    color: color.ink[900],
    fontSize: typography.scale.h1.size,
    fontWeight: '900',
    lineHeight: 34,
  },
  body: {
    color: color.ink[700],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
  },
  bar: {
    backgroundColor: color.bg[100],
    borderRadius: radius.pill,
    height: 6,
    marginVertical: spacing[2],
  },
  barFill: {
    backgroundColor: color.blue[600],
    borderRadius: radius.pill,
    height: 6,
  },
  section: {
    gap: spacing[4],
  },
  sectionTitle: {
    color: color.ink[900],
    fontSize: typography.scale.h3.size,
    fontWeight: '900',
  },
  chipWrap: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing[2],
  },
  dateCard: {
    backgroundColor: color.bg[0],
    borderColor: color.border,
    borderRadius: radius.xl,
    borderWidth: 1,
    gap: spacing[3],
    padding: spacing[4],
  },
  dateText: {
    color: color.ink[900],
    fontWeight: '900',
  },
  infoCard: {
    backgroundColor: color.blue[100],
    borderRadius: radius.xl,
    gap: spacing[2],
    padding: spacing[5],
  },
  summaryCard: {
    backgroundColor: color.bg[0],
    borderColor: color.border,
    borderRadius: radius.xl,
    borderWidth: 1,
    gap: spacing[2],
    padding: spacing[5],
  },
  infoTitle: {
    color: color.ink[900],
    fontSize: typography.scale.h3.size,
    fontWeight: '900',
  },
  infoBody: {
    color: color.ink[700],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
  },
});
