import Express_diagnistika from "@/assets/images/Express_diagnistika.png";
import { useTheme } from "@/components/ThemeContext";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Image } from "expo-image";
import { router } from "expo-router";
import * as WebBrowser from "expo-web-browser";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
  ActivityIndicator,
  FlatList,
  Text,
  TouchableOpacity,
  View
} from "react-native";
import { RefreshControl } from "react-native-gesture-handler";
import { Toast } from "toastify-react-native";
import { eservices_api } from "../lib/api";

const dark = {
  bg: "#0f172a",
  card: "#334155",
  border: "#1e293b",
  muted: "#334155",
  text: "#E5B037",
  subText: "#0B0F2C",
};

export default function EServicesCategoryScreen() {
  const { isDark } = useTheme();
  const [refreshing, setRefreshing] = useState(false);
  const queryClient = useQueryClient();
  const { t } = useTranslation();

  const { data, isLoading } = useQuery({
    queryKey: ["goverment_category"],
    queryFn: () => eservices_api.category(),
  });

  const handleOpenBrowser = async (fileUrl: string) => {
    try {
      await WebBrowser.openBrowserAsync(fileUrl, {
        dismissButtonStyle: 'close',
        presentationStyle: WebBrowser.WebBrowserPresentationStyle.FULL_SCREEN,
      });
    } catch (error) {
      Toast.error(t("Xatolik yuz berdi"));
    }
  }

  const onRefresh = async () => {
    setRefreshing(true);
    try {
      await queryClient.refetchQueries({ queryKey: ["goverment_category"] });
    } finally {
      setRefreshing(false);
    }
  };

  if (isLoading) {
    return (
      <View className="flex-1 items-center justify-center">
        <ActivityIndicator size="large" />
      </View>
    );
  }

  const staticCategory = {
    id: 0,
    name: "Express Diagnostika",
    image: Express_diagnistika,
    url: "https://myorg.uz/ru",
  };

  const categories = [staticCategory, ...(data?.data?.data?.results ?? [])];

  const handlePress = (item: any) => {
    if (item.id === 0 && item.url) {
      handleOpenBrowser(item.url);
      return;
    }

    router.push({
      pathname: "/(dashboard)/e-service/e-services-category",
      params: {
        categoryId: item.id,
        categoryName: item.name,
      },
    });
  };

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: isDark ? dark.bg : "#f8fafc",
        padding: 16,
      }}
    >
      <FlatList
        data={categories}
        keyExtractor={(item) => `${item.id}-${item.name}`}
        contentContainerStyle={{ gap: 12, paddingBottom: 80 }}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={isDark ? "#f8fafc" : "#020617"}
            colors={["#3b82f6"]}
          />
        }
        renderItem={({ item }) => (
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => handlePress(item)}
            style={{
              marginHorizontal: 1,
              backgroundColor: isDark ? "#FDFDFD" : "#ffffff",
              borderRadius: 16,
              flexDirection: "row",
              alignItems: "center",
              borderWidth: isDark ? 1 : 0,
              borderColor: isDark ? dark.border : "transparent",
              shadowColor: "#000",
              shadowOffset: { width: 0, height: 2 },
              shadowOpacity: 0.15,
              shadowRadius: 4,
              elevation: 2,
            }}
          >
            <View
              style={{
                width: "100%",
                height: 100,
                borderRadius: 12,
                alignItems: "center",
                justifyContent: "center",
                marginRight: 14,
                padding: 2,
                overflow: "hidden",
              }}
            >
              {item.image ? (
                <Image
                  source={item.image}
                  style={{ width: "100%", height: "100%" }}
                  contentFit="contain"
                />
              ) : (
                <Text style={{ fontWeight: "700", color: dark.text }}>
                  {item.name[0]}
                </Text>
              )}
            </View>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}
