import { useAlert } from '@/aesthetics/Alert';
import { Text } from '@/aesthetics/Text';
import { IngredientChips } from '@/see-log/components/IngredientChips';
import { TextInput } from '@/aesthetics/TextInput';
import { font, radius, shadows, spacing, useColors } from '@/aesthetics/styles';
import { useStrings } from '@/common/hooks/useStrings';
import { formatDateTime } from '@/common/utils/format';
import type { NutritionDisplayMode, NutritionSortMode } from '@/types/nutrition';
import { ArrowLeft, Pencil, Share, ThumbsDown, ThumbsUp, Trash2 } from 'lucide-react-native';
import { useState } from 'react';
import { Image, Modal, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { BASE_DAILY_TARGETS } from '@/common/constants/nutrition';
import { NutrientBreakdown } from '@/see-log/home-page/NutrientBreakdown';
import { CastleDebugSections } from './CastleDebugSections';
import { useFoodLogDetail } from './useFoodLogDetail';

export function FoodLogDetailScreen() {
  const c = useColors();
  const strings = useStrings();
  const insets = useSafeAreaInsets();
  const { showAlert } = useAlert();
  const [displayMode, setDisplayMode] = useState<NutritionDisplayMode>('nutrients');
  const [sortMode, setSortMode] = useState<NutritionSortMode>('default');

  const {
    log,
    photoUri,
    primaryPrediction,
    predictions,
    showAiComparison,
    editVisible,
    editFoodName,
    setEditVisible,
    setEditFoodName,
    handleDelete,
    handleEdit,
    handleSaveEdit,
    router,
  } = useFoodLogDetail(strings);

  if (!log) {
    return (
      <SafeAreaView style={[styles.container, { backgroundColor: c.background }]}>
        <View style={styles.header}>
          <Pressable
            style={({ pressed }) => [styles.backButton, pressed && styles.pressed]}
            onPress={() => router.back()}
            hitSlop={12}
          >
            <ArrowLeft size={22} color={c.text} strokeWidth={1.5} />
          </Pressable>
        </View>
        <View style={styles.notFound}>
          <Text style={[styles.notFoundText, { color: c.tertiaryText }]}>
            {strings.seeLog.detail.logNotFound}
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: c.background }]}>
      <View style={styles.header}>
        <Pressable
          style={({ pressed }) => [styles.backButton, pressed && styles.pressed]}
          onPress={() => router.back()}
          hitSlop={12}
        >
          <ArrowLeft size={22} color={c.text} strokeWidth={1.5} />
        </Pressable>
      </View>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: 100 + insets.bottom }]}
        showsVerticalScrollIndicator={false}
      >
        {photoUri && (
          <View style={styles.photoContainer}>
            <Image source={{ uri: photoUri }} style={styles.photo} />
          </View>
        )}

        <View style={styles.titleSection}>
          <Text style={[styles.foodName, { color: c.text, fontWeight: '600' }]}>
            {log.foodName}
          </Text>
          <Text style={[styles.time, { color: c.tertiaryText }]}>
            {formatDateTime(log.eatenAt)}
          </Text>
        </View>

        {log.ingredients.length > 0 && (
          <View
            style={[
              styles.card,
              shadows.sm,
              { backgroundColor: c.surface, borderColor: c.borderSubtle },
            ]}
          >
            <Text style={[styles.cardTitle, { color: c.text }]}>
              {strings.seeLog.detail.ingredients}
            </Text>
            <IngredientChips ingredients={log.ingredients} />
          </View>
        )}

        {primaryPrediction && (
          <View
            style={[
              styles.card,
              shadows.sm,
              { backgroundColor: c.surface, borderColor: c.borderSubtle },
            ]}
          >
            <Text style={[styles.cardTitle, { color: c.text }]}>
              {strings.seeLog.detail.detection}
            </Text>
            <View style={styles.detection}>
              <Text style={[styles.detectionName, { color: c.text }]}>
                {primaryPrediction.predictedFoodName ?? strings.common.unknown}
              </Text>
              {primaryPrediction.ingredients && primaryPrediction.ingredients.length > 0 && (
                <Text style={[styles.detectionIngredients, { color: c.secondaryText }]}>
                  {primaryPrediction.ingredients.join(', ')}
                </Text>
              )}
            </View>
          </View>
        )}

        {log.nutrition && Object.keys(log.nutrition).length > 0 && (
          <View
            style={[
              styles.card,
              shadows.sm,
              { backgroundColor: c.surface, borderColor: c.borderSubtle },
            ]}
          >
            <Text style={[styles.cardTitle, { color: c.text }]}>
              {strings.seeLog.detail.nutrition}
            </Text>
            <NutrientBreakdown
              consumed={log.nutrition}
              targets={BASE_DAILY_TARGETS}
              displayMode={displayMode}
              sortMode={sortMode}
              onChangeDisplayMode={setDisplayMode}
              onChangeSortMode={setSortMode}
            />
          </View>
        )}

        {showAiComparison && predictions && predictions.length > 0 && (
          <CastleDebugSections predictions={predictions} photoUri={photoUri ?? undefined} />
        )}
      </ScrollView>

      <View
        style={[
          styles.actionBar,
          shadows.md,
          { backgroundColor: c.surface, borderColor: c.borderSubtle },
        ]}
      >
        <Pressable
          style={({ pressed }) => [styles.actionBtn, pressed && styles.pressed]}
          onPress={() => showAlert(strings.seeLog.detail.liked, strings.common.comingSoon)}
        >
          <ThumbsUp size={20} color={c.secondaryText} strokeWidth={1.5} />
        </Pressable>
        <Pressable
          style={({ pressed }) => [styles.actionBtn, pressed && styles.pressed]}
          onPress={() => showAlert(strings.seeLog.detail.disliked, strings.common.comingSoon)}
        >
          <ThumbsDown size={20} color={c.secondaryText} strokeWidth={1.5} />
        </Pressable>
        <Pressable
          style={({ pressed }) => [styles.actionBtn, pressed && styles.pressed]}
          onPress={handleEdit}
        >
          <Pencil size={20} color={c.secondaryText} strokeWidth={1.5} />
        </Pressable>
        <Pressable
          style={({ pressed }) => [styles.actionBtn, pressed && styles.pressed]}
          onPress={() => showAlert(strings.seeLog.detail.share, strings.common.comingSoon)}
        >
          <Share size={20} color={c.secondaryText} strokeWidth={1.5} />
        </Pressable>
        <Pressable
          style={({ pressed }) => [styles.actionBtn, pressed && styles.pressed]}
          onPress={handleDelete}
        >
          <Trash2 size={20} color={c.danger} strokeWidth={1.5} />
        </Pressable>
      </View>

      <Modal visible={editVisible} transparent animationType="fade">
        <Pressable
          style={[styles.modalOverlay, { backgroundColor: c.overlay }]}
          onPress={() => setEditVisible(false)}
        >
          <View
            style={[styles.modalContent, shadows.lg, { backgroundColor: c.surface }]}
            onStartShouldSetResponder={() => true}
          >
            <Text style={[styles.modalTitle, { color: c.text, fontWeight: '600' }]}>
              {strings.seeLog.detail.editName}
            </Text>
            <TextInput
              style={[styles.modalInput, { color: c.text, backgroundColor: c.tagBg }]}
              value={editFoodName}
              onChangeText={setEditFoodName}
              autoFocus
              onSubmitEditing={handleSaveEdit}
            />
            <View style={styles.modalActions}>
              <Pressable
                style={({ pressed }) => [
                  styles.modalBtn,
                  { backgroundColor: c.tagBg },
                  pressed && styles.pressed,
                ]}
                onPress={() => setEditVisible(false)}
              >
                <Text style={[styles.modalBtnText, { color: c.secondaryText }]}>
                  {strings.common.cancel}
                </Text>
              </Pressable>
              <Pressable
                style={({ pressed }) => [
                  styles.modalBtn,
                  { backgroundColor: c.accent },
                  pressed && styles.pressed,
                ]}
                onPress={handleSaveEdit}
              >
                <Text style={[styles.modalBtnText, { color: c.buttonText }]}>
                  {strings.common.save}
                </Text>
              </Pressable>
            </View>
          </View>
        </Pressable>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: spacing.xl,
    paddingVertical: spacing.md,
  },
  backButton: {
    width: 40,
    height: 40,
    borderRadius: radius.md,
    alignItems: 'center',
    justifyContent: 'center',
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: spacing.xl,
    gap: spacing.lg,
  },
  photoContainer: {
    borderRadius: radius.lg,
    overflow: 'hidden',
  },
  photo: {
    width: '100%',
    aspectRatio: 1,
  },
  titleSection: {
    alignItems: 'center',
    gap: spacing.xs,
  },
  foodName: {
    fontSize: font.xxl,
    textAlign: 'center',
    letterSpacing: 0.3,
  },
  time: {
    fontSize: font.sm,
  },
  notFound: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  notFoundText: {
    fontSize: font.md,
  },
  card: {
    borderRadius: radius.lg,
    borderWidth: 1,
    padding: spacing.lg,
    gap: spacing.md,
  },
  cardTitle: {
    fontSize: font.md,
    fontWeight: '600',
  },
  detection: {
    gap: spacing.xs,
  },
  detectionName: {
    fontSize: font.md,
    fontWeight: '500',
  },
  detectionIngredients: {
    fontSize: font.sm,
  },
  actionBar: {
    position: 'absolute',
    bottom: 0,
    left: spacing.xl,
    right: spacing.xl,
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingVertical: spacing.lg,
    borderRadius: radius.xl,
    borderWidth: 1,
    marginBottom: spacing.xl,
  },
  actionBtn: {
    padding: spacing.md,
    borderRadius: radius.md,
  },
  pressed: {
    opacity: 0.7,
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    width: '85%',
    borderRadius: radius.xl,
    padding: spacing.xl,
  },
  modalTitle: {
    fontSize: font.xl,
    marginBottom: spacing.lg,
  },
  modalInput: {
    borderRadius: radius.md,
    padding: spacing.lg,
    fontSize: font.md,
    marginBottom: spacing.lg,
  },
  modalActions: {
    flexDirection: 'row',
    gap: spacing.md,
  },
  modalBtn: {
    flex: 1,
    paddingVertical: spacing.md,
    borderRadius: radius.md,
    alignItems: 'center',
  },
  modalBtnText: {
    fontSize: font.md,
    fontWeight: '500',
  },
});
