import Button from "@/components/ui/Button";
import { getQueryClient } from "@/configs/query-client";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import * as DocumentPicker from "expo-document-picker";
import * as ImagePicker from "expo-image-picker";
import { router } from "expo-router";
import { CaretDownIcon, RadioButtonIcon, XIcon } from "phosphor-react-native";
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { Image, Modal, Pressable, ScrollView, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

import InputGroup from "@/components/auth/InputGroup";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import { useColor } from "@/hooks/useColor";
import { showToast } from "@/utils/toast";

export type AttachmentType = {
  uri: string;
  name?: string;
  type?: string; // MIME type, e.g. "image/jpeg"
};

export type SupportFormType = {
  subject?: string;
  message: string;
  attachments: AttachmentType[] | null;
  priority: "low" | "medium" | "high";
};

export default function CreateTicket() {
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  // const player = useVideoPlayer(videoUrl || "", (player) => {
  //   player.loop = false;
  //   // player.play();
  // });
  const [modalVisible, setModalVisible] = useState(false);
  const [showPriorityModal, setShowPriorityModal] = useState(false);
  const { primary } = useColor();

  const {
    control,
    handleSubmit,
    getValues,
    formState: { errors: formErrors },
  } = useForm<SupportFormType>({
    defaultValues: {
      priority: "low",
    },
  });

  const [priorityValue, setPriorityValue] = useState(getValues("priority"));

  const {
    mutate,
    isLoading,
    backendErrors: errors,
  } = useQueryMutation({
    url: `/client/support-tickets`,
  });

  const pickImageOrVideo = async (onChange: any, currentValue: AttachmentType[], mediaType: "image" | "video") => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: mediaType === "image" ? ["images"] : ["videos"],
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
      allowsMultipleSelection: false,
    });

    if (!result.canceled && result.assets.length > 0) {
      const file = result.assets[0];
      const fileObj: AttachmentType = {
        uri: file.uri,
        name: file.fileName || file.uri.split("/").pop(),
        type: file.type === "video" ? "video/mp4" : "image/jpeg",
      };
      onChange([...(currentValue || []), fileObj]);
      if (mediaType === "video") {
        setVideoUrl(file.uri);
      }
    }
  };

  const onSubmit = handleSubmit(async (data: SupportFormType) => {
    const hasAttachments = data.attachments && data.attachments.length > 0;

    let body: any;
    if (hasAttachments) {
      const formData = new FormData();
      formData.append("subject", data.subject ?? "");
      formData.append("message", data.message);
      formData.append("priority", data.priority);
      data.attachments!.forEach((file, index) => {
        const safeName = (file.name || `attachment_${index}`).replace(/[^a-zA-Z0-9._-]/g, "_");
        formData.append("attachments[]", {
          uri: file.uri.startsWith("file://") ? file.uri : `file://${file.uri}`,
          name: safeName,
          type: file.type || "application/octet-stream",
        } as any);
      });
      body = formData;
    } else {
      body = {
        subject: data.subject ?? "",
        message: data.message,
        priority: data.priority,
      };
    }

    mutate(body, {
      onSuccess: (response: any) => {
        getQueryClient().invalidateQueries({
          queryKey: ["support-tickets"],
          exact: false,
        });
        showToast({
          text: "Ticket created successfully",
          type: "success",
        });
        router.push("/support");
      },
      onError: (error: any) => {
        console.log(error, "Error support ticket");
      },
    });
  });

  return (
    <SafeAreaView className="bg-white h-full">
      <ScrollView>
        <View className="py-4  px-4">
          <BackButtonTitle title="Create Ticket" />

          <View className=" gap-y-4 mt-6">
            <InputGroup control={control} label="Subject" name="subject" error={formErrors.subject} backendError={errors?.subject} />
            <InputGroup control={control} multiline={true} label="Message" name="message" error={formErrors.message} backendError={errors?.message} />

            <View>
              <Text className="font-medium text-slate-800 pb-2">Set Priority:</Text>
              <Pressable onPress={() => setShowPriorityModal(true)} className="text-base font-medium text-slate-800 border border-slate-200 rounded-lg px-4 py-3 flex-row justify-between items-center">
                <Text className="capitalize font-medium">{priorityValue}</Text>

                <View pointerEvents="none">
                  <CaretDownIcon size={18} color="#1e293b" />
                </View>
              </Pressable>
            </View>

            <View>
              <Text className="text-base font-medium pb-2 text-slate-800">Attachments</Text>
              <Controller
                control={control}
                name="attachments"
                render={({ field: { onChange, value } }) => (
                  <View>
                    <TouchableOpacity onPress={() => setModalVisible(true)} className="border border-slate-200 p-3 rounded-md w-full items-center">
                      <Text className="font-satoshi text-slate-800">{value && value.length > 0 ? "Add More Attachments" : "Upload File"}</Text>
                    </TouchableOpacity>

                    {value && value.length > 0 && (
                      <View className="pt-4 w-full">
                        {value.map((file, index) => (
                          <View key={index} className="flex-row justify-between items-center py-2 px-3 bg-slate-100 rounded-md mb-2">
                            {file.type?.includes("image") ? (
                              <Image source={{ uri: file.uri }} className="w-16 h-16 rounded-md mr-3" />
                            ) : file.type?.includes("video") ? (
                              // <VideoView
                              //   style={{ width: 70, height: 70, borderRadius: 8 }}
                              //   player={player}
                              //   fullscreenOptions={{ enable: true }}
                              //   contentFit="cover"
                              //   nativeControls={true}
                              //   // thumbnailSource={thumbnailSource}
                              // />
                              <Text>Video</Text>
                            ) : (
                              <Text className="font-satoshi text-slate-700 flex-1">📄 {file.name || file.uri.split("/").pop()}</Text>
                            )}
                            <TouchableOpacity
                              onPress={() => {
                                const updatedFiles = value.filter((_, i) => i !== index);
                                onChange(updatedFiles);
                              }}
                              hitSlop={8}
                              className="p-1 bg-red-500 rounded-full ml-2"
                            >
                              <View pointerEvents="none">
                                <XIcon color="white" size={16} />
                              </View>
                            </TouchableOpacity>
                          </View>
                        ))}
                      </View>
                    )}

                    {/* Modal for choosing upload type */}
                    <Modal visible={modalVisible} transparent animationType="fade" onRequestClose={() => setModalVisible(false)}>
                      <View className="flex-1 bg-black/50 justify-center items-center">
                        <View className="bg-white p-6 rounded-lg w-[80%]">
                          <Text className="text-lg font-semibold mb-4 text-center">Select Upload Type</Text>
                          <Pressable
                            onPress={() => {
                              setModalVisible(false);
                              pickImageOrVideo(onChange, value || [], "image");
                            }}
                            className="py-3 border-b border-slate-200"
                          >
                            <Text className="text-center text-blue-600">Upload Image</Text>
                          </Pressable>
                          <Pressable
                            onPress={() => {
                              setModalVisible(false);
                              pickImageOrVideo(onChange, value || [], "video");
                            }}
                            className="py-3 border-b border-slate-200"
                          >
                            <Text className="text-center text-blue-600">Upload Video</Text>
                          </Pressable>
                          <Pressable
                            onPress={async () => {
                              const res = await DocumentPicker.getDocumentAsync({
                                type: "*/*",
                                copyToCacheDirectory: true,
                              });

                              if (res.assets && res.assets.length > 0) {
                                const file = res.assets[0];
                                const fileObj = {
                                  uri: file.uri,
                                  name: file.name,
                                  type: file.mimeType || "application/octet-stream",
                                };

                                onChange([...(value || []), fileObj]); // Append to existing array
                              }
                            }}
                            className="py-3"
                          >
                            <Text className="text-center text-blue-600">Upload File</Text>
                          </Pressable>
                          <Pressable onPress={() => setModalVisible(false)} className="mt-3 py-2 bg-slate-100 rounded-md">
                            <Text className="text-center text-slate-800">Cancel</Text>
                          </Pressable>
                        </View>
                      </View>
                    </Modal>
                  </View>
                )}
              />
            </View>

            <View className="pt-6">
              <Button onPress={onSubmit} className="w-full justify-center items-center" disabled={isLoading} text="Submit" isLoading={isLoading} />
            </View>
          </View>
        </View>
      </ScrollView>

      <Modal
        animationType="fade"
        visible={showPriorityModal}
        transparent={true}
        onRequestClose={() => {
          setShowPriorityModal(!showPriorityModal);
        }}
      >
        <View className="flex-1 justify-center items-center bg-black/50">
          <View className="bg-white flex-col gap-y-4 p-4 w-[60%] max-h-[70%] ">
            <Text className=" heading-4">Set Priority</Text>
            <Controller
              control={control}
              name="priority"
              render={({ field: { onChange, value } }) => (
                <View className="border-t border-slate-300 py-4 gap-y-4">
                  {["low", "medium", "high"].map((priority) => (
                    <TouchableOpacity
                      key={priority}
                      onPress={() => {
                        onChange(priority);
                        setShowPriorityModal(false);
                        setPriorityValue(priority as "low" | "medium" | "high");
                      }}
                      className="flex-row items-center gap-2"
                    >
                      {value === priority ? <RadioButtonIcon color={primary.base} size={22} /> : <RadioButtonIcon color="#64748b" size={22} />}
                      <Text
                        className={`text-lg font-medium`}
                        style={{
                          color: value === priority ? primary.base : "#64748b",
                        }}
                      >
                        {priority.charAt(0).toUpperCase() + priority.slice(1)}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>
              )}
            />
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}
