import { Colors } from '@/constants/theme';
import { useAuth } from '@/utils/auth';
import { BlurView } from 'expo-blur';
import { Image } from 'expo-image';
import { router, Tabs } from 'expo-router';
import React, { useEffect } from 'react';
import { Platform, View } from 'react-native';

const HOME_ICON = require('@/assets/images/tabIcons/home.png');
const EXPLORE_ICON = require('@/assets/images/tabIcons/explore.png');
const ICON_STYLE = { width: 24, height: 24 };

function tinted(source: number) {
  function TabIcon({ color }: { color: string }) {
    return <Image style={ICON_STYLE} tintColor={color} source={source} />;
  }
  return TabIcon;
}

function plain(source: number) {
  function TabIcon() {
    return <Image style={ICON_STYLE} source={source} />;
  }
  return TabIcon;
}

function TabBarBackground() {
  return Platform.OS === 'ios'
    ? <BlurView tint="light" style={{ flex: 1 }} />
    : <View style={{ flex: 1, backgroundColor: 'rgba(255, 255, 255, 0.9)' }} />;
}

const SCREEN_OPTIONS = {
  headerShown: false,
  tabBarActiveTintColor: Colors.tint,
  tabBarStyle: { position: 'absolute' as const },
  tabBarBackground: TabBarBackground,
  lazy: true,
};

const TABS = [
  { name: 'index', title: '首页', tabBarIcon: tinted(HOME_ICON) },
  { name: 'customer', title: '客户', tabBarIcon: tinted(EXPLORE_ICON) },
  { name: 'analytics', title: '分析', tabBarIcon: tinted(EXPLORE_ICON) },
  { name: 'reports', title: '报告', tabBarIcon: tinted(EXPLORE_ICON) },
  { name: 'profile', title: '我的', tabBarIcon: plain(EXPLORE_ICON) },
];

export default function TabLayout() {
  const { authStatus } = useAuth();

  useEffect(() => {
    if (authStatus === 'fail') {
      router.push('/sign-in');
    }
  }, [authStatus]);

  if (authStatus !== 'auth') return null;

  return (
    <Tabs screenOptions={SCREEN_OPTIONS}>
      {TABS.map(({ name, title, tabBarIcon }) => (
        <Tabs.Screen key={name} name={name} options={{ title, tabBarIcon }} />
      ))}
    </Tabs>
  );
}
