import Button from "@/components/ui/Button";
import StarRating from "@/components/ui/star-rating";
import { getQueryClient } from "@/configs/query-client";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useTranslations } from "@/providers/TranslationProviders";
import { toastConfig } from "@/components/ui/ToastConfig";
import { showToast } from "@/utils/toast";
import { useState } from "react";
import { Text, TextInput, View, Pressable, KeyboardAvoidingView, Platform, ScrollView, Modal } from "react-native";
import { XIcon } from "phosphor-react-native";
import Toast from "react-native-toast-message";

interface Review {
  id?: number;
  rating: number;
  comment: string;
}

interface ReviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectSlug: string;
  existingReview?: Review | null;
}

export default function ReviewModal({
  isOpen,
  onClose,
  projectSlug,
  existingReview,
}: ReviewModalProps) {
  const { tran, translateNumber } = useTranslations();
  const isEditing = !!existingReview?.id;

  // Initialize state from existingReview or default values
  const getInitialReview = (): Review => ({
    id: existingReview?.id,
    rating: existingReview?.rating ?? 0,
    comment: existingReview?.comment ?? "",
  });

  const [review, setReview] = useState<Review>(getInitialReview);

  const { mutate: addReview, isLoading: isAdding } = useQueryMutation({
    url: `/client/projects/${projectSlug}/reviews`,
  });

  const { mutate: updateReview, isLoading: isUpdating } = useQueryMutation({
    url: `/client/reviews/${existingReview?.id}`,
    isUpdateMethod: true,
  });

  const isLoading = isAdding || isUpdating;

  const handleSubmit = () => {
    if (!review.rating && !review.comment.trim()) {
      return;
    }
    if (!review.rating) {
      showToast({ type: "error", text: tran("Please select a star rating.") });
      return;
    }
    if (!review.comment.trim()) {
      showToast({ type: "error", text: tran("Please write a comment.") });
      return;
    }

    const mutate = isEditing ? updateReview : addReview;
    const payload = { rating: review.rating, comment: review.comment };

    mutate(payload, {
      onSuccess: (res) => {
        showToast({
          type: "success",
          text: isEditing ? tran("Review updated successfully") : tran("Review submitted successfully"),
        });

        const queryClient = getQueryClient();

        // Invalidate project and marketplace queries using a predicate to match URLs starting with these prefixes
        queryClient.invalidateQueries({
          predicate: (query) => 
            typeof query.queryKey[0] === 'string' && 
            (query.queryKey[0].startsWith('/marketplace') || 
             query.queryKey[0].startsWith('/projects') || 
             query.queryKey[0].startsWith('/client/projects'))
        });

        if (isEditing && existingReview?.id) {
          queryClient.invalidateQueries({
            queryKey: [`/client/reviews/${existingReview.id}`],
          });
        }
        handleClose();
      },
    });
  };

  const handleClose = () => {
    if (!existingReview) {
      setReview({ rating: 0, comment: "" });
    }
    onClose();
  };

  return (
    <Modal
      animationType="fade"
      transparent={true}
      visible={isOpen}
      onRequestClose={handleClose}
    >
      <View className="flex-1 bg-black/50 justify-center items-center">
        <KeyboardAvoidingView
          behavior={Platform.OS === "ios" ? "padding" : "height"}
          className="w-[90%] max-w-[400px]"
        >
          <View className="bg-white rounded-[32px] overflow-hidden shadow-2xl">
            {/* Header */}
            <View className="px-6 pt-6 pb-4 flex-row items-center justify-between border-b border-slate-50">
              <View>
                <Text className="text-xl font-manrope-extrabold text-slate-900">
                  {isEditing ? tran("Update Review") : tran("Add Review")}
                </Text>
                <Text className="text-xs font-manrope-medium text-slate-400 mt-0.5">
                  {tran("Share your experience here")}
                </Text>
              </View>
              <Pressable
                onPress={handleClose}
                hitSlop={10}
                className="w-10 h-10 rounded-full bg-slate-50 items-center justify-center active:bg-slate-100"
              >
                <View pointerEvents="none">
                  <XIcon size={20} color="#94a3b8" weight="bold" />
                </View>
              </Pressable>
            </View>

            <ScrollView className="p-6" showsVerticalScrollIndicator={false}>
              {/* Rating Section */}
              <View className="mb-8 items-center bg-slate-50 p-6 rounded-[24px] border border-slate-100">
                <Text className="text-sm font-manrope-bold text-slate-500 uppercase tracking-widest mb-4">
                  {tran("Your Rating")}
                </Text>
                <View className="flex-row items-center gap-4">
                  <StarRating
                    rating={review.rating}
                    setRating={(r) => setReview((prev) => ({ ...prev, rating: r }))}
                    editable
                    size={32}
                  />
                </View>
                <Text className="text-2xl font-manrope-extrabold text-slate-900 mt-4">
                  {translateNumber(review.rating)} <Text className="text-slate-400 text-lg">/ {translateNumber(5)}</Text>
                </Text>
              </View>

              {/* Comment Section */}
              <View className="mb-6">
                <Text className="text-sm font-manrope-bold text-slate-700 mb-3 px-1">
                  {tran("Your Feedback")}
                </Text>
                <TextInput
                  value={review.comment}
                  onChangeText={(e) => setReview((prev) => ({ ...prev, comment: e }))}
                  multiline={true}
                  numberOfLines={6}
                  className="w-full px-5 py-4 bg-slate-50 border border-slate-100 rounded-[20px] font-manrope-medium text-slate-900 h-32"
                  placeholder={tran("Write your review here") + "..."}
                  placeholderTextColor="#94a3b8"
                  textAlignVertical="top"
                />
              </View>
            </ScrollView>

            {/* Footer Actions */}
            <View className="p-6 pt-2">
              <Button
                onPress={handleSubmit}
                disabled={isLoading}
                isLoading={isLoading}
                text={isEditing ? tran("Save Changes") : tran("Submit Review")}
              />
            </View>
          </View>
        </KeyboardAvoidingView>
      </View>
      <Toast config={toastConfig} />
    </Modal>
  );
}
