import WishlistCard from "@/components/cards/wishlist-card";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useTranslations } from "@/providers/TranslationProviders";
import { useWishlist } from "@/providers/WishlistProvider";
import { showToast } from "@/utils/toast";
import { HeartIcon, TrashIcon } from "phosphor-react-native";
import { useState } from "react";
import {
  ActivityIndicator,
  Modal,
  RefreshControl,
  ScrollView,
  Text,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function WishlistScreen() {
  const { tran } = useTranslations();
  const { primary, danger } = useColor();
  const { 
    data: wishlistData, 
    isLoading, 
    refetch 
  } = useGetQuery({
    url: "/wishlist/get-all-with-project",
  });
  const { removeItem, clearWishlist } = useWishlist();

  // Modal State for Clear All
  const [isClearModalOpen, setIsClearModalOpen] = useState(false);
  const [isCleaning, setIsCleaning] = useState(false);

  const handleRemove = async (id: number) => {
    try {
      await removeItem(id);
      showToast({
        text: tran("Removed from wishlist"),
        type: "success",
      });
      refetch();
    } catch {
       showToast({
        text: tran("Failed to remove item"),
        type: "error",
      });
    }
  };

  const handleClearAll = async () => {
    setIsCleaning(true);
    try {
      await clearWishlist();
      showToast({
        text: tran("Wishlist cleared successfully"),
        type: "success",
      });
      refetch();
      setIsClearModalOpen(false);
    } catch {
       showToast({
        text: tran("Failed to clear wishlist"),
        type: "error",
      });
    } finally {
      setIsCleaning(false);
    }
  };

  return (
    <SafeAreaView className="flex-1 bg-white" edges={["top"]}>
      <View className="px-6 mb-4">
        <BackButtonTitle 
          title={tran("My Wishlist")} 
          renderContent={
            wishlistData && wishlistData.length > 0 ? (
              <Button 
                onPress={() => setIsClearModalOpen(true)} 
                text={tran("Clear All")} 
                type="danger" 
                size="sm"
                fullWidth={false}
                className="px-4"
              />
            ) : null
          }
        />
      </View>

      <ScrollView 
        className="flex-1"
        contentContainerStyle={{ paddingHorizontal: 24, paddingBottom: 40 }}
        refreshControl={
          <RefreshControl 
            refreshing={false} 
            onRefresh={refetch} 
            tintColor={primary.base}
            colors={[primary.base]}
          />
        }
      >
        <View className="pt-4">
          {isLoading ? (
            <View className="py-20 items-center justify-center">
              <ActivityIndicator color={primary.base} size="large" />
            </View>
          ) : wishlistData && wishlistData.length > 0 ? (
            <View className="gap-6">
              {wishlistData.map((item: any) => (
                <WishlistCard
                  key={item.id || item.project_id}
                  item={item}
                  onRemove={handleRemove}
                />
              ))}
            </View>
          ) : (
            <View className="py-20 items-center justify-center bg-slate-50 rounded-3xl border border-dotted border-slate-200">
              <View className="w-16 h-16 rounded-full bg-slate-100 items-center justify-center mb-4">
                <HeartIcon size={32} color="#cbd5e1" weight="duotone" />
              </View>
              <Text className="text-lg font-manrope-bold text-slate-400">
                {tran("Wishlist is Empty")}
              </Text>
              <Text className="text-sm font-manrope text-slate-400 mt-1 max-w-[200px] text-center">
                {tran("Explore projects and save your favorites here.")}
              </Text>
            </View>
          )}
        </View>
      </ScrollView>

      {/* Clear All Confirmation Modal */}
      <Modal
        animationType="fade"
        transparent={true}
        visible={isClearModalOpen}
        onRequestClose={() => setIsClearModalOpen(false)}
      >
        <View className="flex-1 justify-center items-center bg-black/50 px-6">
          <View className="bg-white rounded-2xl p-6 w-full shadow-lg">
             <View className="w-12 h-12 rounded-full bg-red-50 items-center justify-center mb-4">
              <TrashIcon size={24} color={danger.base} weight="bold" />
            </View>
            <Text className="text-xl font-manrope-extrabold text-slate-900 mb-2">
              {tran("Clear Wishlist?")}
            </Text>
            <Text className="text-sm font-manrope text-slate-500 mb-8 leading-relaxed">
              {tran("Are you sure you want to remove all items from your wishlist? This action cannot be undone.")}
            </Text>
            
            <View className="flex-row gap-3">
              <View className="flex-1">
                <Button 
                  onPress={() => setIsClearModalOpen(false)} 
                  text={tran("Cancel")} 
                  type="secondary" 
                  disabled={isCleaning}
                />
              </View>
              <View className="flex-1">
                <Button 
                  onPress={handleClearAll} 
                  text={isCleaning ? tran("Clearing") + "..." : tran("Clear All")} 
                  type="danger"
                  disabled={isCleaning}
                />
              </View>
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

