import React, { useState, useEffect } from "react";
import {
  View,
  ScrollView,
  Pressable,
  TextInput,
  ActivityIndicator,
  RefreshControl,
  Image,
} from "react-native";
import { useColorScheme } from "nativewind";
import { Text } from "@/components/ui/text";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ScreenWrapper } from "@/components/ScreenWrapper";
import { StandardHeader } from "@/components/StandardHeader";

import { useSirouRouter } from "@sirou/react-native";
import { AppRoutes } from "@/lib/routes";
import { Stack } from "expo-router";
import { api } from "@/lib/api";
import { getPlaceholderColor } from "@/lib/colors";
import { EmptyState } from "@/components/EmptyState";
import { UserPlus, Search, Mail, ChevronRight, Plus } from "@/lib/icons";

export default function TeamScreen() {
  const nav = useSirouRouter<AppRoutes>();
  const { colorScheme } = useColorScheme();
  const isDark = colorScheme === "dark";

  const [workers, setWorkers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const fetchWorkers = async () => {
    try {
      const response = await api.team.getAll();
      const data = response.data || [];
      setWorkers(data);
    } catch (error) {
      console.error("[TeamScreen] Error fetching workers:", error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchWorkers();
  }, []);

  const onRefresh = () => {
    setRefreshing(true);
    fetchWorkers();
  };

  const filteredWorkers = workers.filter((worker) => {
    const name = `${worker.firstName} ${worker.lastName}`.toLowerCase();
    const email = (worker.email || "").toLowerCase();
    const query = searchQuery.toLowerCase();
    return name.includes(query) || email.includes(query);
  });

  return (
    <ScreenWrapper className="bg-background">
      <Stack.Screen options={{ headerShown: false }} />
      <StandardHeader title="Team" showBack />

      <View className="flex-1 px-5 pt-4">
        <View className="flex-row items-center bg-card rounded-xl px-4 border border-border h-12 mb-6">
          <Search size={18} color={isDark ? "#94a3b8" : "#64748b"} />
          <TextInput
            className="flex-1 ml-3 text-foreground"
            placeholder="Search team members..."
            placeholderTextColor={getPlaceholderColor(isDark)}
            value={searchQuery}
            onChangeText={setSearchQuery}
            style={{ textAlignVertical: "center" }}
          />
        </View>
        <Button
          className="mb-4 h-10 rounded-lg bg-primary"
          onPress={() => nav.go("team/create")}
        >
          <Plus color="#ffffff" size={18} strokeWidth={2.5} />
          <Text className="text-white text-[11px] font-sans-bold uppercase tracking-widest ml-2">
            Add Team Member
          </Text>
        </Button>

        <View className="flex-row justify-between items-center mb-4">
          <Text variant="h4" className="text-foreground tracking-tight">
            Members ({filteredWorkers?.length || 0})
          </Text>
        </View>

        {loading ? (
          <View className="flex-1 justify-center items-center">
            <ActivityIndicator color="#ea580c" />
          </View>
        ) : (
          <ScrollView
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                tintColor="#ea580c"
              />
            }
            contentContainerStyle={{ paddingBottom: 100 }}
          >
            {filteredWorkers.length > 0 ? (
              filteredWorkers.map((worker) => (
                <Pressable
                  key={worker.id}
                  onPress={() => nav.go("team/[id]/details", { id: worker.id })}
                >
                  <Card className="mb-3 overflow-hidden rounded-[12px] bg-card border border-border">
                    <View className="flex-row items-center p-4">
                      {worker.avatar ? (
                        <Image
                          source={{ uri: worker.avatar }}
                          className="h-12 w-12 rounded-full mr-4"
                        />
                      ) : (
                        <View className="h-12 w-12 rounded-full bg-secondary items-center justify-center mr-4">
                          <Text className="text-primary font-sans-bold text-lg">
                            {worker.firstName?.[0]}
                            {worker.lastName?.[0]}
                          </Text>
                        </View>
                      )}

                      <View className="flex-1">
                        <Text className="text-foreground font-sans-bold text-base">
                          {worker.firstName} {worker.lastName}
                        </Text>
                        <View className="flex-row items-center mt-1">
                          <Text className="text-muted-foreground text-xs bg-muted px-2 py-0.5 rounded-md font-sans-bold text-[9px]">
                            {worker.role?.replace("_", " ") || "WORKER"}
                          </Text>
                          {worker.email && (
                            <Text variant="muted" className="text-[10px] ml-2">
                              {worker.email}
                            </Text>
                          )}
                        </View>
                      </View>

                      <ChevronRight
                        size={18}
                        color={isDark ? "#334155" : "#cbd5e1"}
                      />
                    </View>
                  </Card>
                </Pressable>
              ))
            ) : (
              <EmptyState
                title="No team members found"
                description="Start by adding your first team member."
              />
            )}
          </ScrollView>
        )}
      </View>
    </ScreenWrapper>
  );
}
