import { CameraView } from '@/add-log/camera/CameraView';
import { FoodLogEditor } from '@/add-log/food-log-editor/FoodLogEditor';
import { Text } from '@/aesthetics/Text';
import { TextInput } from '@/aesthetics/TextInput';
import { colors, font, radius, spacing, useColors } from '@/aesthetics/styles';
import { useStrings } from '@/common/hooks/useStrings';
import {
  Camera as CameraIcon,
  Check,
  Crop,
  ImageIcon,
  SendHorizontal,
  X,
} from 'lucide-react-native';
import { Keyboard, Pressable, StyleSheet, View } from 'react-native';
import { useKeyboardHandler } from 'react-native-keyboard-controller';
import Animated, { useAnimatedStyle, useSharedValue } from 'react-native-reanimated';
import { StagedFoodLogList } from './StagedFoodLogList';
import { SuggestionList } from './SuggestionList';
import { useLogScreen } from './useLogScreen';

export function LogScreenContent() {
  const c = useColors();
  const strings = useStrings();
  const { camera, logs, editor, suggestions, input, layout, haptics } = useLogScreen();

  const keyboardHeight = useSharedValue(0);
  useKeyboardHandler(
    {
      onStart: () => {
        'worklet';
      },
      onMove: e => {
        'worklet';
        keyboardHeight.value = e.height;
      },
      onEnd: () => {
        'worklet';
      },
      onInteractive: e => {
        'worklet';
        keyboardHeight.value = e.height;
      },
    },
    []
  );

  const animatedContainerStyle = useAnimatedStyle(() => {
    return { paddingBottom: keyboardHeight.value };
  });

  const { isCropMode, cropAreaCenterY, cropBoxHeight } = camera;
  const insetsTop = layout.insets.top;
  const stagedLogsStyle = useAnimatedStyle(() => {
    const top = isCropMode ? cropAreaCenterY + cropBoxHeight.value / 2 : insetsTop;
    return { paddingTop: top };
  }, [isCropMode, cropAreaCenterY, insetsTop]);

  return (
    <View style={styles.container}>
      <CameraView
        hasPermission={camera.hasPermission}
        requestCameraPermission={camera.requestPermission}
        device={camera.device}
        format={camera.format}
        cameraOn={camera.on}
        cameraActive={camera.active}
        cameraRef={camera.ref}
        zoom={camera.zoom}
        onInitialized={() => camera.setReady(true)}
        gesture={camera.gesture}
        showCropOverlay={camera.showCropOverlay}
        cropGestures={camera.cropGestures}
        cropBoxWidth={camera.cropBoxWidth}
        cropBoxHeight={camera.cropBoxHeight}
        cropAreaCenterY={camera.cropAreaCenterY}
        onEnableCamera={() => {
          Keyboard.dismiss();
          haptics.impact();
          camera.setMode('fullscreen');
        }}
        focusPoint={camera.focusPoint}
      />

      <View style={styles.contentOverlay} pointerEvents="box-none">
        <Animated.View
          style={[styles.keyboardArea, animatedContainerStyle]}
          pointerEvents="box-none"
        >
          <Animated.View
            style={[styles.stagedLogsContainer, stagedLogsStyle]}
            pointerEvents="box-none"
          >
            <StagedFoodLogList
              stagedFoodLogs={logs.staged}
              onEditLog={logs.edit}
              onDeleteLog={logs.delete}
              onToggleIngredient={logs.toggleIngredient}
              onSwitchCandidate={logs.switchCandidate}
            />
          </Animated.View>

          <SuggestionList
            suggestions={suggestions.items}
            onPressSuggestion={suggestions.press}
            onDeleteSuggestion={suggestions.delete}
            onAddSuggestion={suggestions.add}
          />

          <View style={styles.inputArea}>
            <View style={styles.inputPill}>
              <Pressable
                style={[
                  styles.cameraToggle,
                  camera.on ? styles.cameraToggleActive : styles.cameraToggleOff,
                ]}
                onPress={() => {
                  haptics.impact();
                  camera.setMode(prev => {
                    if (prev === 'off') return 'fullscreen';
                    if (prev === 'fullscreen') return 'cropped';
                    return 'off';
                  });
                }}
              >
                {camera.mode === 'off' && <CameraIcon size={18} color={colors.camera.iconOff} />}
                {camera.mode === 'fullscreen' && (
                  <CameraIcon size={18} color={colors.camera.icon} />
                )}
                {camera.mode === 'cropped' && <Crop size={18} color={colors.camera.icon} />}
              </Pressable>
              <TextInput
                style={styles.textInput}
                placeholder={strings.addLog.log.whatDidYouEat}
                placeholderTextColor={colors.camera.placeholder}
                value={input.text}
                onChangeText={input.setText}
                onSubmitEditing={input.submit}
                returnKeyType="done"
              />
              {input.text.trim() ? (
                <Pressable
                  style={[styles.inputAction, { backgroundColor: c.accent }]}
                  onPress={input.submit}
                >
                  <SendHorizontal
                    size={16}
                    color={colors.camera.text}
                    style={{ transform: [{ rotate: '-90deg' }] }}
                  />
                </Pressable>
              ) : (
                <Pressable
                  style={[styles.inputAction, styles.cameraToggleActive]}
                  onPress={input.pickImage}
                >
                  <ImageIcon size={18} color={colors.camera.icon} />
                </Pressable>
              )}
            </View>
          </View>

          <View style={[styles.shutterArea, { paddingBottom: layout.insets.bottom }]}>
            <View style={styles.shutterRow}>
              <Pressable
                style={({ pressed }) => [styles.sideButton, pressed && styles.pressed]}
                onPress={() => layout.router.back()}
                hitSlop={12}
              >
                <X size={22} color={colors.camera.iconStrong} strokeWidth={1.5} />
              </Pressable>

              <Pressable
                style={[styles.shutterButton, !camera.on && styles.shutterDisabled]}
                onPress={camera.takePhoto}
                disabled={!camera.on}
              >
                <View style={[styles.shutterInner, !camera.on && styles.shutterInnerDisabled]} />
              </Pressable>

              {logs.staged.length > 0 ? (
                <Pressable
                  style={({ pressed }) => [styles.logButton, pressed && styles.pressed]}
                  onPress={logs.logAll}
                >
                  <Check size={20} color={colors.camera.text} strokeWidth={2} />
                  <Text style={styles.logButtonText}>{logs.staged.length}</Text>
                </Pressable>
              ) : (
                <View style={styles.sideButton} />
              )}
            </View>
          </View>
        </Animated.View>
      </View>

      <FoodLogEditor
        editingLog={editor.log}
        onClose={() => editor.setLog(null)}
        editFoodName={editor.foodName}
        onChangeFoodName={editor.setFoodName}
        editIngredients={editor.ingredients}
        newIngredient={editor.newIngredient}
        onChangeNewIngredient={editor.setNewIngredient}
        onAddIngredient={editor.addIngredient}
        onRemoveIngredient={editor.removeIngredient}
        onSave={editor.save}
      />
    </View>
  );
}

const INPUT_PILL_HEIGHT = 52;

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.camera.background },
  contentOverlay: { ...StyleSheet.absoluteFillObject },
  keyboardArea: { flex: 1, justifyContent: 'flex-end' },
  stagedLogsContainer: { flex: 1, marginHorizontal: 16 },
  inputArea: { paddingHorizontal: spacing.lg },
  inputPill: {
    flexDirection: 'row',
    alignItems: 'center',
    height: INPUT_PILL_HEIGHT,
    borderRadius: INPUT_PILL_HEIGHT / 2,
    paddingHorizontal: spacing.sm,
    backgroundColor: colors.camera.inputBg,
    borderWidth: 1,
    borderColor: colors.camera.inputBorder,
    gap: spacing.sm,
  },
  cameraToggle: {
    width: 40,
    height: 40,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  cameraToggleActive: { backgroundColor: colors.camera.buttonBgActive },
  cameraToggleOff: { backgroundColor: colors.camera.text },
  textInput: {
    flex: 1,
    height: INPUT_PILL_HEIGHT,
    fontSize: font.md,
    color: colors.camera.text,
    paddingVertical: 0,
  },
  inputAction: {
    width: 40,
    height: 40,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  shutterArea: { paddingHorizontal: spacing.xl },
  shutterRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: spacing.lg,
    gap: spacing.xxl,
  },
  sideButton: {
    width: 48,
    height: 48,
    borderRadius: radius.xl,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.camera.buttonBg,
  },
  shutterButton: {
    width: 76,
    height: 76,
    borderRadius: 38,
    backgroundColor: colors.camera.shutterBg,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 3,
    borderColor: colors.camera.shutterBorder,
  },
  shutterDisabled: { opacity: 0.4 },
  shutterInner: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: colors.camera.shutterInner,
  },
  shutterInnerDisabled: { backgroundColor: colors.camera.shutterInnerDisabled },
  logButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 48,
    paddingHorizontal: spacing.lg,
    borderRadius: radius.xl,
    backgroundColor: colors.camera.successBg,
    gap: spacing.sm,
  },
  logButtonText: { color: colors.camera.text, fontSize: font.lg, fontWeight: '600' },
  pressed: { opacity: 0.7 },
});
