import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Alert, Modal, ScrollView, ActivityIndicator, Platform, Image } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { CameraView, Camera } from 'expo-camera';
import { COLOR_SCALES } from '@/theme/colors';
import { FLEX } from '@/theme/mixins';
import { title, paragraph } from '@/theme/typography';
import { joinCompany } from '@/services/user';
import Toast from '@/components/common/Toast';
import useToast from '@/hooks/useToast';
// QRScanner.jsx içinde
const getApiBaseUrl = () => 'https://panel.bugunyap.com/api';

const QRScanner = () => {
  const router = useRouter();
  const { mode } = useLocalSearchParams();
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);
  const [scanCooldown, setScanCooldown] = useState(false);
  const [companyInfo, setCompanyInfo] = useState(null);
  const [showCompanyModal, setShowCompanyModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const { toast, showSuccessToast, showErrorToast, hideToast } = useToast();
  const getCompanyLogoSource = (info) => {
    const base = getApiBaseUrl();
    const host = base?.replace(/\/api$/, '') || '';
    const raw = info?.profileImage || info?.logo || info?.logoUrl || info?.image || info?.avatar || info?.profile_image;
    if (!raw) return require('@/assets/images/placeholder.jpg');
    const value = String(raw);
    if (value.startsWith('http')) return { uri: value };
    return { uri: `${host}/${value.replace(/^\//, '')}` };
  };

  useEffect(() => {
    const getCameraPermissions = async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    };
    getCameraPermissions();
  }, []);

  // QR koddan şirket ID'sini çıkar
  const extractCompanyId = (qrData) => {
    try {
      if (typeof qrData !== 'string') qrData = String(qrData);
    } catch (_) {
      return null;
    }

    // 1. Basit format: COMPANY_ID:123
    if (qrData.startsWith('COMPANY_ID:')) {
      const parts = qrData.split(':');
      if (parts.length >= 2 && !isNaN(parts[1])) {
        return parseInt(parts[1], 10);
      }
    }

    // 2. JSON format
    try {
      const jsonData = JSON.parse(qrData);
      if (jsonData && jsonData.id && jsonData.type === 'company') {
        return Number(jsonData.id);
      }
    } catch (_) {}

    // 3. Sadece sayısal ID
    if (!isNaN(qrData)) {
      return parseInt(qrData, 10);
    }

    return null;
  };

  // API'den şirket bilgilerini çek ve modalı aç
  const fetchCompanyInfo = async (companyId) => {
    try {
      setIsLoading(true);
      const API_BASE_URL = getApiBaseUrl();
      const response = await fetch(`${API_BASE_URL}/company/${companyId}`);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const result = await response.json();

      if (result?.success) {
        setCompanyInfo(result.data);
        setShowCompanyModal(true);
      } else {
        Alert.alert('Hata', `Şirket bilgileri alınamadı: ${result?.message || 'Bilinmeyen hata'}`);
        setScanned(false);
      }
    } catch (error) {
      Alert.alert('Hata', `Şirket bilgileri alınırken hata: ${error.message}`);
      setScanned(false);
    } finally {
      setIsLoading(false);
    }
  };

  const handleBarCodeScanned = ({ type, data }) => {
    if (scanCooldown) return;
    setScanned(true);
    setScanCooldown(true);
    setTimeout(() => setScanCooldown(false), 1200);

    // QR Modülü modunda: kodu direkt qr-module sayfasına geri gönder
    if (mode === 'qr-module') {
      router.replace({ pathname: '/qr-module', params: { qrCode: data } });
      return;
    }

    const companyId = extractCompanyId(data);
    if (companyId) {
      fetchCompanyInfo(companyId);
    } else {
      Alert.alert('Hata', 'QR koddan şirket ID\'si çıkarılamadı. Geçerli bir şirket QR kodu olmayabilir.', [{ text: 'Tamam', onPress: () => setScanned(false) }]);
    }
  };

  const handleJoinCompany = async () => {
    try {
      const res = await joinCompany({ companyId: companyInfo?.id });
      if (res?.success) {
        showSuccessToast({ title: 'Başarılı', message: 'Şirkete katılım başarılı!' });
        setShowCompanyModal(false);
        setScanned(false);
        setTimeout(() => {
          router.replace('/(tabs)/home');
        }, 900);
      } else {
        showErrorToast({ title: 'Hata', message: res?.message ?? 'İşlem başarısız' });
      }
    } catch (e) {
      showErrorToast({ title: 'Hata', message: e?.message ?? 'İşlem başarısız' });
    }
  };

  const handleGoBack = () => {
    router.back();
  };

  if (hasPermission === null) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.permissionContainer}>
          <Text style={styles.permissionText}>Kamera izni kontrol ediliyor...</Text>
        </View>
      </SafeAreaView>
    );
  }

  if (hasPermission === false) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.permissionContainer}>
          <Ionicons name="camera-outline" size={64} color={COLOR_SCALES.colorGray[50]} />
          <Text style={styles.permissionTitle}>Kamera İzni Gerekli</Text>
          <Text style={styles.permissionText}>
            QR kod taramak için kamera iznine ihtiyacımız var.
          </Text>
          <TouchableOpacity
            style={styles.permissionButton}
            onPress={() => Camera.requestCameraPermissionsAsync()}
          >
            <Text style={styles.permissionButtonText}>İzin Ver</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <View style={styles.container}>
      <Toast
        visible={toast?.visible}
        title={toast?.title}
        message={toast?.message}
        type={toast?.type}
        duration={toast?.duration}
        onHide={hideToast}
      />
      <StatusBar style="light" />

      <CameraView
        style={styles.camera}
        facing="back"
        onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
        barcodeScannerSettings={{ barcodeTypes: ['qr', 'pdf417'] }}
      >
        {/* Header */}
        <SafeAreaView style={styles.header}>
          <TouchableOpacity style={styles.backButton} onPress={handleGoBack}>
            <Ionicons name="chevron-back" size={24} color={COLOR_SCALES.white.white} />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>QR Kod Tarayıcı</Text>
          <View style={styles.headerRight} />
        </SafeAreaView>

        {/* QR Code Scanning Area */}
        <View style={styles.scanningArea}>
          <View style={styles.qrFrame}>
            <View style={[styles.corner, styles.topLeft]} />
            <View style={[styles.corner, styles.topRight]} />
            <View style={[styles.corner, styles.bottomLeft]} />
            <View style={[styles.corner, styles.bottomRight]} />
            <View style={styles.qrIconContainer}>
              <Ionicons name="qr-code-outline" size={48} color={COLOR_SCALES.white.white} />
            </View>
          </View>
        </View>

        {/* Bottom Info */}
        <View style={styles.bottomInfo}>
          <View style={styles.infoIcon}>
            <Ionicons name="information-circle" size={24} color={COLOR_SCALES.primary[50]} />
          </View>
          <Text style={styles.infoText}>Kamerayı QR koduna odaklayın</Text>
        </View>
      </CameraView>

      {/* Loading Overlay */}
      {isLoading && (
        <View style={styles.loadingOverlay}>
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={COLOR_SCALES.primary[50]} />
            <Text style={styles.loadingText}>Şirket bilgileri yükleniyor...</Text>
          </View>
        </View>
      )}

      {/* Company Modal */}
      <Modal
        visible={showCompanyModal}
        animationType="slide"
        transparent={true}
        onRequestClose={() => setShowCompanyModal(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <ScrollView showsVerticalScrollIndicator={false}>
              {/* Modal Header */}
              <View style={styles.modalHeader}>
                <View style={styles.modalHeaderContent}>
                  <View style={styles.companyIconLarge}>
                    <Ionicons name="business" size={32} color={COLOR_SCALES.white.white} />
                  </View>
                  <Text style={styles.modalTitle}>Şirket Bilgileri</Text>
                </View>
                <TouchableOpacity
                  style={styles.closeButton}
                  onPress={() => {
                    setShowCompanyModal(false);
                    setScanned(false);
                  }}
                >
                  <Ionicons name="close" size={24} color={COLOR_SCALES.white.white} />
                </TouchableOpacity>
              </View>

              {companyInfo && (
                <View style={styles.companyDetails}>
                  {/* Şirket Adı */}
                  <View style={styles.companyNameSection}>
                    <View style={styles.companyNameRow}>
                      <Text style={styles.companyName}>
                        {companyInfo.name || companyInfo.firstName || 'Şirket'}
                      </Text>
                      <Image source={{ uri: "https://api.bugunyap.com:1910/uploads/users/" + companyInfo.profileImage }} style={styles.companyLogo} resizeMode="contain" />
                    </View>
                    <Text style={styles.companySubtitle}>Şirket Detayları</Text>
                  </View>

                  {/* Info Cards */}
                  <View style={styles.infoCards}>
                    <View style={styles.infoCard}>
                      <View style={styles.infoCardHeader}>
                        <Ionicons name="key-outline" size={20} color={COLOR_SCALES.primary[50]} />
                        <Text style={styles.infoCardTitle}>Şirket ID</Text>
                      </View>
                      <Text style={styles.infoCardValue}>{companyInfo.id}</Text>
                    </View>

                    {companyInfo.email && (
                      <View style={styles.infoCard}>
                        <View style={styles.infoCardHeader}>
                          <Ionicons name="mail-outline" size={20} color={COLOR_SCALES.primary[50]} />
                          <Text style={styles.infoCardTitle}>E-posta</Text>
                        </View>
                        <Text style={styles.infoCardValue}>{companyInfo.email}</Text>
                      </View>
                    )}

                    {companyInfo.phone && (
                      <View style={styles.infoCard}>
                        <View style={styles.infoCardHeader}>
                          <Ionicons name="call-outline" size={20} color={COLOR_SCALES.primary[50]} />
                          <Text style={styles.infoCardTitle}>Telefon</Text>
                        </View>
                        <Text style={styles.infoCardValue}>{companyInfo.phone}</Text>
                      </View>
                    )}

                    {companyInfo.address && (
                      <View style={styles.infoCard}>
                        <View style={styles.infoCardHeader}>
                          <Ionicons name="location-outline" size={20} color={COLOR_SCALES.primary[50]} />
                          <Text style={styles.infoCardTitle}>Adres</Text>
                        </View>
                        <Text style={styles.infoCardValue}>{companyInfo.address}</Text>
                      </View>
                    )}

                    {companyInfo.city && (
                      <View style={styles.infoCard}>
                        <View style={styles.infoCardHeader}>
                          <Ionicons name="business-outline" size={20} color={COLOR_SCALES.primary[50]} />
                          <Text style={styles.infoCardTitle}>Şehir</Text>
                        </View>
                        <Text style={styles.infoCardValue}>{companyInfo.city}</Text>
                      </View>
                    )}
                  </View>

                  {/* Katıl Button */}
                  <TouchableOpacity
                    style={styles.joinButton}
                    onPress={handleJoinCompany}
                  >
                    <Ionicons name="person-add" size={20} color={COLOR_SCALES.white.white} />
                    <Text style={styles.joinButtonText}>Şirkete Katıl</Text>
                  </TouchableOpacity>

                  {/* Scan Again */}
                  <TouchableOpacity
                    style={styles.scanAgainButton}
                    onPress={() => {
                      setShowCompanyModal(false);
                      setScanned(false);
                    }}
                  >
                    <Text style={styles.scanAgainButtonText}>Tekrar Tara</Text>
                  </TouchableOpacity>
                </View>
              )}
            </ScrollView>
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: COLOR_SCALES.colorGray[90],
  },
  camera: {
    ...FLEX.fill,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  backButton: {
    padding: 8,
  },
  headerTitle: {
    ...paragraph['M/Medium'],
    color: COLOR_SCALES.white.white,
    flex: 1,
    textAlign: 'center',
  },
  headerRight: {
    width: 40,
  },
  scanningArea: {
    ...FLEX.fill,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 40,
  },
  qrFrame: {
    width: 250,
    height: 250,
    position: 'relative',
    justifyContent: 'center',
    alignItems: 'center',
  },
  corner: {
    position: 'absolute',
    width: 30,
    height: 30,
    borderColor: COLOR_SCALES.white.white,
    borderWidth: 3,
  },
  topLeft: {
    top: 0,
    left: 0,
    borderRightWidth: 0,
    borderBottomWidth: 0,
  },
  topRight: {
    top: 0,
    right: 0,
    borderLeftWidth: 0,
    borderBottomWidth: 0,
  },
  bottomLeft: {
    bottom: 0,
    left: 0,
    borderRightWidth: 0,
    borderTopWidth: 0,
  },
  bottomRight: {
    bottom: 0,
    right: 0,
    borderLeftWidth: 0,
    borderTopWidth: 0,
  },
  qrIconContainer: {
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    borderRadius: 12,
    padding: 16,
  },
  bottomInfo: {
    position: 'absolute',
    bottom: 100,
    left: 0,
    right: 0,
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  infoIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: COLOR_SCALES.white.white,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 12,
  },
  infoText: {
    ...paragraph['M/Regular'],
    color: COLOR_SCALES.white.white,
    textAlign: 'center',
  },
  permissionContainer: {
    ...FLEX.fill,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 40,
  },
  permissionTitle: {
    ...title['M/Bold'],
    color: COLOR_SCALES.colorGray[90],
    marginTop: 16,
    marginBottom: 8,
    textAlign: 'center',
  },
  permissionText: {
    ...paragraph['M/Regular'],
    color: COLOR_SCALES.colorGray[70],
    textAlign: 'center',
    marginBottom: 24,
  },
  permissionButton: {
    backgroundColor: COLOR_SCALES.primary[50],
    paddingHorizontal: 32,
    paddingVertical: 12,
    borderRadius: 8,
  },
  permissionButtonText: {
    ...paragraph['M/Medium'],
    color: COLOR_SCALES.white.white,
  },
  // Modal Styles
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  modalContent: {
    backgroundColor: COLOR_SCALES.white.white,
    borderRadius: 20,
    width: '100%',
    maxHeight: '85%',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 10 },
    shadowOpacity: 0.25,
    shadowRadius: 20,
    elevation: 10,
  },
  modalHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: COLOR_SCALES.colorGray[20],
    backgroundColor: COLOR_SCALES.primary[50],
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
  },
  modalHeaderContent: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  companyIconLarge: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 12,
  },
  modalTitle: {
    ...title['M/Bold'],
    color: COLOR_SCALES.white.white,
    flex: 1,
  },
  closeButton: {
    padding: 8,
  },
  companyDetails: {
    padding: 20,
  },
  companyNameSection: {
    alignItems: 'center',
    marginBottom: 24,
    paddingBottom: 20,
    borderBottomWidth: 1,
    borderBottomColor: COLOR_SCALES.colorGray[20],
  },
  companyNameRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
  },
  companyName: {
    ...title['L/Bold'],
    color: COLOR_SCALES.colorGray[90],
    marginBottom: 4,
    textAlign: 'center',
  },
  companyLogo: {
    width: 48,
    height: 48,
    borderRadius: 24,
    marginLeft: 8,
    backgroundColor: COLOR_SCALES.white.white,
    borderWidth: 1,
    borderColor: COLOR_SCALES.colorGray[20],
    padding: 4,
    overflow: 'hidden',
  },
  companySubtitle: {
    ...paragraph['S/Regular'],
    color: COLOR_SCALES.colorGray[60],
    textAlign: 'center',
  },
  infoCards: {
    marginBottom: 24,
  },
  infoCard: {
    backgroundColor: COLOR_SCALES.colorGray[10],
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    borderLeftWidth: 4,
    borderLeftColor: COLOR_SCALES.primary[50],
  },
  infoCardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  infoCardTitle: {
    ...paragraph['S/Medium'],
    color: COLOR_SCALES.colorGray[70],
    marginLeft: 8,
  },
  infoCardValue: {
    ...paragraph['M/Regular'],
    color: COLOR_SCALES.colorGray[90],
    marginLeft: 28,
  },
  joinButton: {
    backgroundColor: COLOR_SCALES.primary[50],
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: 'center',
    marginBottom: 12,
    flexDirection: 'row',
    justifyContent: 'center',
    shadowColor: COLOR_SCALES.primary[50],
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 5,
  },
  joinButtonText: {
    ...title['M/Bold'],
    color: COLOR_SCALES.white.white,
    marginLeft: 8,
  },
  scanAgainButton: {
    backgroundColor: COLOR_SCALES.colorGray[20],
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
  },
  scanAgainButtonText: {
    ...paragraph['M/Medium'],
    color: COLOR_SCALES.colorGray[70],
  },
});

export default QRScanner;