import { CameraView, useCameraPermissions } from 'expo-camera';
import * as Location from 'expo-location';
import * as ScreenOrientation from 'expo-screen-orientation';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  ActivityIndicator,
  useWindowDimensions,
} from 'react-native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { RootStackParamList } from '../navigation/types';
import { FooterConfig, loadFooterConfig, StampMeta } from '../photo/footerConfig';
import { getActiveProjectId, getProject } from '../db/repositories';
import { COLORS } from '../ui/components';
import { FooterOverlay } from '../photo/FooterOverlay';

type Props = NativeStackScreenProps<RootStackParamList, 'Camera'>;

export function CameraScreen({ route, navigation }: Props) {
  const { onCapture } = route.params;
  const [permission, requestPermission] = useCameraPermissions();
  const cameraRef = useRef<CameraView>(null);
  const { width: winW, height: winH } = useWindowDimensions();

  const [config, setConfig] = useState<FooterConfig | null>(null);
  const [meta, setMeta] = useState<StampMeta | null>(null);
  const [taking, setTaking] = useState(false);
  const [rotation, setRotation] = useState(0);

  // Detectar orientación física para rotar el sello
  useEffect(() => {
    const updateOrientation = async () => {
      const info = await ScreenOrientation.getOrientationAsync();
      handleOrientation(info);
    };

    const handleOrientation = (o: ScreenOrientation.Orientation) => {
      // Nota: LANDSCAPE_LEFT es rotar el móvil a la derecha (home button a la derecha)
      // Queremos contrarrestar el giro para que el sello esté derecho.
      if (o === ScreenOrientation.Orientation.LANDSCAPE_LEFT) setRotation(90);
      else if (o === ScreenOrientation.Orientation.LANDSCAPE_RIGHT) setRotation(-90);
      else if (o === ScreenOrientation.Orientation.PORTRAIT_UPSIDE_DOWN) setRotation(180);
      else setRotation(0);
    };

    void updateOrientation();
    const sub = ScreenOrientation.addOrientationChangeListener((evt) => {
      handleOrientation(evt.orientationInfo.orientation);
    });
    return () => ScreenOrientation.removeOrientationChangeListener(sub);
  }, []);

  const loadData = useCallback(async () => {
    const [cfg, projectId] = await Promise.all([
      loadFooterConfig(),
      getActiveProjectId(),
    ]);
    setConfig(cfg);

    let projectName: string | null = null;
    if (projectId != null) {
      const proj = await getProject(projectId);
      projectName = proj?.name ?? null;
    }

    const { granted } = await Location.requestForegroundPermissionsAsync();
    let coordsStr: string | null = null;
    if (granted) {
      const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced });
      const lat = loc.coords.latitude;
      const lng = loc.coords.longitude;
      const la = lat >= 0 ? 'N' : 'S';
      const lo = lng >= 0 ? 'E' : 'O';
      coordsStr = `${Math.abs(lat).toFixed(5)}°${la}, ${Math.abs(lng).toFixed(5)}°${lo}`;
    }

    setMeta({
      projectName,
      date: new Date().toLocaleString('es-ES', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit',
      }),
      coordinates: coordsStr,
    });
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  if (!permission) {
    return <View style={styles.center}><ActivityIndicator size="large" /></View>;
  }

  if (!permission.granted) {
    return (
      <View style={styles.center}>
        <Text style={styles.message}>Necesitamos permiso para usar la cámara</Text>
        <TouchableOpacity style={styles.btn} onPress={requestPermission}>
          <Text style={styles.btnText}>Conceder permiso</Text>
        </TouchableOpacity>
      </View>
    );
  }

  const capture = async () => {
    if (!cameraRef.current || taking) return;
    setTaking(true);
    try {
      const photo = await cameraRef.current.takePictureAsync({
        quality: config?.quality ?? 0.85,
        base64: false,
        exif: false,
      });
      if (photo) {
        onCapture(photo.uri, photo.width, photo.height);
        navigation.goBack();
      }
    } catch (e) {
      console.error('Error taking picture:', e);
    } finally {
      setTaking(false);
    }
  };

  return (
    <View style={styles.container}>
      <CameraView
        ref={cameraRef}
        style={StyleSheet.absoluteFill}
        facing="back"
        autofocus="on"
      />

      {/* Capa de UI sobre la cámara */}
      <View style={styles.overlay}>
        {/* Header con botón cerrar */}
        <View style={styles.header}>
          <TouchableOpacity onPress={() => navigation.goBack()} style={styles.closeBtn}>
            <Text style={styles.closeTxt}>✕</Text>
          </TouchableOpacity>
        </View>

        {/* Preview del sello (posicionado en su esquina con rotación) */}
        {config && meta && (
          <View style={styles.fullOverlay} pointerEvents="none">
            <FooterOverlay
              config={config}
              meta={meta}
              imageWidth={Math.min(winW, winH)}
              rotation={rotation}
            />
          </View>
        )}

        {/* Botón de disparo abajo al centro */}
        <View style={styles.footerControls}>
          <TouchableOpacity
            style={[styles.captureBtn, taking && styles.disabled]}
            onPress={() => void capture()}
            disabled={taking}
          >
            <View style={styles.captureInner} />
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#000' },
  overlay: { flex: 1, justifyContent: 'space-between', zIndex: 10 },
  fullOverlay: {
    ...StyleSheet.absoluteFillObject,
    // No centramos aquí, dejamos que FooterOverlay use sus offsets top/bottom/left/right
  },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#000' },
  message: { color: '#fff', textAlign: 'center', marginBottom: 20 },
  btn: { backgroundColor: COLORS.primary, padding: 12, borderRadius: 8 },
  btnText: { color: '#fff', fontWeight: 'bold' },
  header: { padding: 20, paddingTop: 50 },
  closeBtn: { width: 40, height: 40, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.3)', borderRadius: 20 },
  closeTxt: { color: '#fff', fontSize: 24 },
  footerControls: {
    paddingBottom: 40,
    alignItems: 'center',
    width: '100%',
  },
  captureBtn: {
    width: 76,
    height: 70, // Un poco ovalado para que se note
    borderRadius: 38,
    borderWidth: 5,
    borderColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  captureInner: {
    width: 54,
    height: 54,
    borderRadius: 27,
    backgroundColor: '#fff',
  },
  disabled: { opacity: 0.5 },
});
