import { useState } from 'react';
import { router } from 'expo-router';
import { useMutation } from '@tanstack/react-query';
import * as ImagePicker from 'expo-image-picker';
import { Image, Pressable, StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
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 { naviAssets } from '../../src/assets/naviAssets';
import { color, radius, spacing, typography } from '../../src/theme';

interface PickedImage {
  uri: string;
  base64: string;
}

export default function ImageTranslator() {
  const { t } = useTranslation();
  const user = useAuth((s) => s.user);
  const [target, setTarget] = useState<'en' | 'ar'>('en');
  const [image, setImage] = useState<PickedImage | null>(null);
  const [error, setError] = useState<string | null>(null);

  const translate = useMutation({
    mutationFn: async () => {
      if (!image) throw new Error(t('translator.chooseFirst'));
      return api.translator.image({ imageBase64: image.base64, target });
    },
    onError: (e) => setError(e instanceof Error ? e.message : t('translator.translateFailed')),
  });

  async function openCamera() {
    setError(null);
    try {
      const permission = await ImagePicker.requestCameraPermissionsAsync();
      if (!permission.granted) {
        setError(t('translator.cameraPermission'));
        return;
      }
      const result = await ImagePicker.launchCameraAsync({
        allowsEditing: false,
        base64: true,
        quality: 0.72,
      });
      if (!result.canceled && result.assets[0]?.base64) {
        setImage({ uri: result.assets[0].uri, base64: result.assets[0].base64 });
      }
    } catch {
      setError(t('translator.cameraUnavailable'));
    }
  }

  async function openGallery() {
    setError(null);
    try {
      const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (!permission.granted) {
        setError(t('translator.galleryPermission'));
        return;
      }
      const result = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: false,
        base64: true,
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        quality: 0.72,
      });
      if (!result.canceled && result.assets[0]?.base64) {
        setImage({ uri: result.assets[0].uri, base64: result.assets[0].base64 });
      }
    } catch {
      setError(t('translator.galleryUnavailable'));
    }
  }

  if (!user) {
    return (
      <Screen>
        <NaviHeader variant="center" title={t('translator.title')} showBack onBack={() => router.replace('/(tabs)/home')} />
        <Text style={styles.h1}>{t('translator.title')}</Text>
        <StateView tone="denied" title={t('translator.signInTitle')} body={t('translator.signInBody')} />
        <PrimaryButton label={t('actions.signIn')} onPress={() => router.push('/(auth)/login')} />
      </Screen>
    );
  }

  const job = translate.data?.job;

  return (
    <Screen>
      <NaviHeader variant="center" title={t('translator.title')} showBack onBack={() => router.replace('/(tabs)/home')} />
      <View style={styles.headerRow}>
        <View>
          <Text style={styles.h1}>{t('translator.title')}</Text>
          <Text style={styles.sub}>{t('translator.subtitle')}</Text>
        </View>
        <Pressable onPress={() => router.push('/translator/history')} accessibilityRole="button">
          <Text style={styles.historyLink}>{t('actions.history')}</Text>
        </Pressable>
      </View>

      <View style={styles.languageRow}>
        <FilterChip label={t('translator.arabicToEnglish')} active={target === 'en'} onPress={() => setTarget('en')} />
        <FilterChip label={t('translator.englishToArabic')} active={target === 'ar'} onPress={() => setTarget('ar')} />
      </View>

      <View style={styles.cameraFrame}>
        {image ? (
          <Image source={{ uri: image.uri }} style={styles.preview} resizeMode="cover" />
        ) : (
          <>
            <Image source={naviAssets.translator.cameraPreview} style={styles.preview} resizeMode="cover" />
            <View style={styles.frameCopy}>
              <Text style={styles.frameTitle}>{t('translator.alignTitle')}</Text>
              <Text style={styles.frameBody}>{t('translator.alignBody')}</Text>
            </View>
          </>
        )}
      </View>

      <View style={styles.actionRow}>
        <PrimaryButton label={t('actions.camera')} variant="secondary" onPress={openCamera} style={styles.actionButton} />
        <PrimaryButton label={t('actions.gallery')} variant="secondary" onPress={openGallery} style={styles.actionButton} />
      </View>

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

      <PrimaryButton
        label={translate.isPending ? t('actions.translating') : t('actions.translateImage')}
        onPress={() => {
          setError(null);
          translate.mutate();
        }}
        disabled={!image || translate.isPending}
      />

      {job ? (
        <View style={styles.resultCard}>
          <Text style={styles.resultLabel}>{t('translator.detectedText')}</Text>
          <Text style={styles.resultText}>{job.sourceText}</Text>
          <Text style={styles.resultLabel}>{t('translator.translation')}</Text>
          <Text style={styles.translation}>{job.translatedText}</Text>
        </View>
      ) : null}
    </Screen>
  );
}

const styles = StyleSheet.create({
  headerRow: {
    gap: spacing[3],
  },
  h1: {
    color: color.ink[900],
    fontSize: typography.scale.h1.size,
    fontWeight: '900',
  },
  sub: {
    color: color.ink[500],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
  },
  historyLink: {
    color: color.blue[600],
    fontWeight: '900',
  },
  languageRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing[2],
  },
  cameraFrame: {
    alignItems: 'center',
    backgroundColor: color.ink[900],
    borderRadius: radius.xl,
    height: 330,
    justifyContent: 'center',
    overflow: 'hidden',
  },
  preview: {
    height: '100%',
    width: '100%',
  },
  frameCopy: {
    alignItems: 'center',
    backgroundColor: 'rgba(11,18,32,0.48)',
    bottom: 0,
    gap: spacing[2],
    left: 0,
    padding: spacing[6],
    position: 'absolute',
    right: 0,
    top: 0,
    justifyContent: 'center',
  },
  frameTitle: {
    color: color.bg[0],
    fontSize: typography.scale.h3.size,
    fontWeight: '900',
    textAlign: 'center',
  },
  frameBody: {
    color: color.ink[300],
    lineHeight: 21,
    textAlign: 'center',
  },
  actionRow: {
    flexDirection: 'row',
    gap: spacing[3],
  },
  actionButton: {
    flex: 1,
  },
  resultCard: {
    backgroundColor: color.bg[0],
    borderColor: color.border,
    borderRadius: radius.xl,
    borderWidth: 1,
    gap: spacing[2],
    padding: spacing[5],
  },
  resultLabel: {
    color: color.ink[500],
    fontSize: typography.scale.caption.size,
    fontWeight: '900',
  },
  resultText: {
    color: color.ink[900],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
  },
  translation: {
    color: color.blue[600],
    fontSize: typography.scale.h3.size,
    fontWeight: '900',
    lineHeight: 24,
  },
});
