import ListingCard, { ListingData } from "@/components/cards/listing-card";
import CancelListingModal from "@/components/modals/cancel-listing-modal";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useState } from "react";
import {
  RefreshControl,
  ScrollView,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import BackButtonTitle from "@/components/ui/BackButtonTitle";

export default function ForSale() {
  // Modal state
  const [selectedListing, setSelectedListing] = useState<ListingData | null>(
    null,
  );
  const {
    data: listings,
    isLoading,
    refetch,
  } = useGetQuery({
    url: "/client/listings",
  });

  const handleCancelListing = (listing: ListingData) => {
    setSelectedListing(listing);
  };

  const handleCloseModal = () => {
    setSelectedListing(null);
  };

  return (
    <ScrollView
      refreshControl={
        <RefreshControl refreshing={isLoading} onRefresh={refetch} />
      }
      className="bg-white px-6"
    >
      <SafeAreaView>
        <BackButtonTitle title="Listed Shares" />
        <View className="pt-8">
          {listings?.data?.map((listing: ListingData, index: number) => (
            <ListingCard
              key={`${listing.project_id}-${index}`}
              listing={listing}
              onCancelListing={handleCancelListing}
            />
          ))}
        </View>
        {/* Cancel Modal */}
        {selectedListing && (
          <CancelListingModal
            isOpen={!!selectedListing}
            onClose={handleCloseModal}
            listingId={selectedListing.project_id}
            projectTitle={selectedListing.project.title}
            numberOfShares={selectedListing.number_of_shares}
            price={selectedListing.price}
          />
        )}
      </SafeAreaView>
    </ScrollView>
  );
}
