import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { BackButton } from '../../src/components/BackButton';
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 { color, radius, spacing, typography } from '../../src/theme';

export default function TranslatorHistory() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const history = useQuery({ queryKey: ['translator-history'], queryFn: () => api.translator.history() });
  const remove = useMutation({
    mutationFn: (id: string) => api.translator.remove(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['translator-history'] }),
  });

  return (
    <Screen>
      <BackButton fallbackHref="/translator/" />
      <Text style={styles.h1}>{t('translator.historyTitle')}</Text>
      <Text style={styles.sub}>{t('translator.historySubtitle')}</Text>

      {history.isLoading ? <StateView tone="loading" title={t('translator.historyLoading')} /> : null}
      {history.isError ? <StateView tone="error" title={t('translator.historyUnavailableTitle')} body={t('translator.historyUnavailableBody')} /> : null}
      {!history.isLoading && !(history.data ?? []).length ? (
        <StateView tone="empty" title={t('translator.historyEmptyTitle')} body={t('translator.historyEmptyBody')} />
      ) : null}

      {(history.data ?? []).map((job) => (
        <View key={job.id} style={styles.card}>
          <View style={styles.row}>
            <Text style={styles.lang}>{job.sourceLanguage.toUpperCase()} → {job.targetLanguage.toUpperCase()}</Text>
            <Text style={styles.date}>{new Date(job.createdAt).toLocaleDateString()}</Text>
          </View>
          <Text style={styles.source}>{job.sourceText}</Text>
          <Text style={styles.translation}>{job.translatedText}</Text>
          <PrimaryButton
            label={remove.isPending ? t('states.loading') : t('actions.delete')}
            variant="ghost"
            onPress={() => remove.mutate(job.id)}
            disabled={remove.isPending}
          />
        </View>
      ))}
    </Screen>
  );
}

const styles = StyleSheet.create({
  h1: {
    color: color.ink[900],
    fontSize: typography.scale.h1.size,
    fontWeight: '900',
  },
  sub: {
    color: color.ink[500],
    fontSize: typography.scale.body.size,
    lineHeight: 22,
  },
  card: {
    backgroundColor: color.bg[0],
    borderColor: color.border,
    borderRadius: radius.xl,
    borderWidth: 1,
    gap: spacing[2],
    padding: spacing[4],
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  lang: {
    color: color.blue[600],
    fontSize: typography.scale.caption.size,
    fontWeight: '900',
  },
  date: {
    color: color.ink[500],
    fontSize: typography.scale.caption.size,
    fontWeight: '700',
  },
  source: {
    color: color.ink[700],
    lineHeight: 21,
  },
  translation: {
    color: color.ink[900],
    fontSize: typography.scale.bodyStrong.size,
    fontWeight: '900',
    lineHeight: 22,
  },
});
