import {
  View,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  FlatList,
  Image,
  RefreshControl,
} from "react-native";
import React, { useState, useCallback } from "react";
import { Calender, Info } from "@src/utils/icons";
import { Add } from "@src/utils/icons";
import { appColors, appFonts, windowHeight, windowWidth } from "@src/themes";
import { useNavigation } from "@react-navigation/native";
import { useSelector, useDispatch } from "react-redux";
import Images from "@src/utils/images";
import styles from "./styles";
import { useValues } from "@src/utils/context";
import { TicketLoader } from "./TicketLoader";
import { HeaderContainer } from "@src/commonComponent";
import { ticketDataGet } from "@src/api/store/actions";
import { AppDispatch } from "@src/api/store";

export function SupportTicket() {
  const { navigate } = useNavigation();
  const dispatch = useDispatch<AppDispatch>();

  const { ticketData, loading } = useSelector((state: any) => state.tickets);
  const { translateData } = useSelector((state: any) => state.setting);

  const { textColorStyle, isDark, viewRTLStyle, bgFullStyle, textRTLStyle } =
    useValues();

  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    dispatch(ticketDataGet())
      .unwrap()
      .finally(() => {
        setRefreshing(false);
      });
  }, [dispatch]);

  const gotoAdd = () => {
    navigate("CreateTicket");
  };

  const gotoDetails = (value: any) => {
    navigate("TicketDetails", { ticketData: value });
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const day = date.getDate();
    const month = date.toLocaleString("en-US", { month: "short" });
    const year = date.getFullYear();
    return `${day} ${month}’${year}`;
  };

  const renderTicketItem = ({ item }: { item: any }) => {
    return (
      <View style={styles.renderTicketItemView}>
        <TouchableWithoutFeedback onPress={() => gotoDetails(item)}>
          <View
            style={[
              styles.ticketContainer,
              {
                backgroundColor: bgFullStyle,
                borderColor: isDark ? appColors.darkBorder : appColors.border,
              },
            ]}
          >
            <View
              style={[
                styles.row,
                {
                  flexDirection: viewRTLStyle,
                  marginHorizontal: windowWidth(15),
                  marginTop: windowHeight(5),
                },
              ]}
            >
              <View
                style={[styles.formatDateView, { flexDirection: viewRTLStyle }]}
              >
                <View
                  style={[
                    styles.statusContainer,
                    {
                      marginHorizontal: 0,
                      backgroundColor: appColors.lightGray,
                    },
                  ]}
                >
                  <Text style={styles.ticketStyle}>#{item?.ticket_number}</Text>
                </View>
                <View style={styles.statusContainer}>
                  <Text style={styles.statusText}>
                    {item?.ticketStatus?.name}
                  </Text>
                </View>
              </View>

              <View
                style={[
                  styles.status_Container,
                  { flexDirection: viewRTLStyle },
                ]}
              >
                <Calender />
                <Text style={styles.createdAt}>
                  {formatDate(item?.created_at)}
                </Text>
              </View>
            </View>

            <View
              style={[
                styles.departmentView,
                {
                  backgroundColor: isDark
                    ? appColors.solidBorder
                    : appColors.lightGray,
                },
              ]}
            />

            <View
              style={[
                {
                  flexDirection: viewRTLStyle,
                  marginHorizontal: windowWidth(15),
                },
              ]}
            >
              <View style={styles.departSubView}>
                <Text
                  style={{
                    color: appColors.darkPurpal,
                    fontFamily: appFonts.regular,
                  }}
                >
                  {item?.department?.name}
                </Text>
              </View>
              <View style={styles.priorityView}>
                <Text style={styles.priorityText}>{item?.priority?.name}</Text>
              </View>
            </View>

            <View
              style={{
                marginHorizontal: windowWidth(19),
                marginTop: windowHeight(2),
              }}
            >
              <Text
                style={[
                  styles.subjectText,
                  {
                    color: isDark
                      ? appColors.whiteColor
                      : appColors.primaryText,
                    textAlign: textRTLStyle,
                  },
                ]}
              >
                {item?.subject}
              </Text>

              <Text style={[styles.desText, { textAlign: textRTLStyle }]}>
                {item?.messages?.[0]?.message?.length > 80
                  ? `${item?.messages[0].message.substring(0, 80)}...`
                  : item?.messages?.[0]?.message}
              </Text>
            </View>
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  };

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
      }}
    >
      <HeaderContainer
        value={translateData.supportTicket}
        show
        icon={
          <TouchableOpacity
            activeOpacity={0.7}
            style={[
              styles.addBtn,
              {
                backgroundColor: isDark
                  ? appColors.darkHeader
                  : appColors.whiteColor,
                borderColor: isDark ? appColors.darkBorder : appColors.border,
              },
            ]}
            onPress={gotoAdd}
          >
            <Add colors={textColorStyle} />
          </TouchableOpacity>
        }
      />

      <FlatList
        data={ticketData?.data || []}
        renderItem={renderTicketItem}
        keyExtractor={(item) => item?.id?.toString()}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={appColors.primary}
          />
        }
        ListHeaderComponent={
          loading ? (
            <>
              <TicketLoader />
              <TicketLoader />
            </>
          ) : null
        }
        ListEmptyComponent={
          !loading ? (
            <View
              style={[
                styles.ticketSubContainer,
                {
                  backgroundColor: isDark
                    ? appColors.solidBorder
                    : appColors.lightGray,
                },
              ]}
            >
              <Image
                source={isDark ? Images.noTicketDark : Images.noTicket}
                style={styles.noImg}
              />
              <View
                style={[
                  styles.emptyTicketView,
                  { flexDirection: viewRTLStyle },
                ]}
              >
                <Text style={[styles.emptyTicket, { color: textColorStyle }]}>
                  {translateData.noTicket}
                </Text>
                <View style={styles.marginHr}>
                  <Info />
                </View>
              </View>
              <Text style={styles.noTicketText}>
                {translateData.noTicketDes}
              </Text>
            </View>
          ) : null
        }
      />
    </View>
  );
}
