import Styles from "@/constants/Styles";
import { apiGetDivisionOneFeature } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { View } from "react-native";
import Text from "../Text";
import DiscussionItem from "../discussionItem";
import Skeleton from "../skeleton";

type Props = {
  id: string;
  title: string;
  desc: string;
  user: string;
  date: string;
};

export default function DiscussionDivisionDetail({ refreshing }: { refreshing: boolean }) {
  const { colors } = useTheme();
  const { token, decryptToken } = useAuthSession();
  const { id } = useLocalSearchParams<{ id: string }>();
  const [data, setData] = useState<Props[]>([]);
  const [loading, setLoading] = useState(true)

  async function handleLoad(loading: boolean) {
    try {
      setLoading(loading)
      const hasil = await decryptToken(String(token?.current));
      const response = await apiGetDivisionOneFeature({
        user: hasil,
        id,
        cat: "new-discussion",
      });
      setData(response.data);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (refreshing)
      handleLoad(false)
  }, [refreshing])

  useEffect(() => {
    handleLoad(true)
  }, [])


  return (
    <View style={[Styles.mb15]}>
      <Text style={[Styles.textDefaultSemiBold, Styles.mv10]}>Diskusi</Text>
      {loading ? (
        <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.icon + '20' }, Styles.p0]}>
          <Skeleton width={100} height={70} borderRadius={10} widthType="percent" />
          <Skeleton width={100} height={70} borderRadius={10} widthType="percent" />
        </View>
      ) : data.length > 0 ? (
        <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.icon + '20' }, Styles.p0]}>
          {data.map((item, index) => (
            <DiscussionItem
              key={index}
              title={item.desc}
              user={item.user}
              date={item.date}
              onPress={() => {
                router.push(`/division/${id}/discussion/${item.id}`);
              }}
            />
          ))}
        </View>
      ) : (
        <View style={{ alignItems: 'center', paddingVertical: 16, gap: 6, opacity: 0.5 }}>
          <MaterialCommunityIcons name="chat-outline" size={28} color={colors.dimmed} />
          <Text style={[Styles.textDefault, { color: colors.dimmed }]}>Belum ada diskusi aktif</Text>
        </View>
      )}
    </View>
  );
}
