"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { FiEdit, FiTrash2 } from "react-icons/fi";
import { AddressDialog } from "./address-dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import axios from "axios";
import ToastMessage from "@/components/common/ToastMessage";



interface AddressListProps {
  initialData: Address[];
}

const AddressList: React.FC<AddressListProps> = ({ initialData }) => {
  const [addresses, setAddresses] = useState<Address[]>(initialData);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    setAddresses(initialData);
    return () => {
      // Cleanup function to cancel any pending requests if component unmounts
      // This helps prevent memory leaks
      const source = axios.CancelToken.source();
      source.cancel("Component unmounted");
    };
  }, [initialData]);

  const handleDelete = async (uuid: string) => {
    if (isDeleting) return;

    setIsDeleting(true);
    try {
      const response = await axios.delete(`/api/user/address/${uuid}`);
      if (response.status === 200) {
        ToastMessage("success", "Address deleted successfully");
        // Instead of reloading the page, update the state
        setAddresses((prev) => prev.filter((address) => address.uuid !== uuid));
      } else {
        ToastMessage("error", "Address could not be deleted");
      }
    } catch (error) {
      if (axios.isCancel(error)) {
        if (typeof error === "object" && error !== null && "message" in error) {
          console.log("Request canceled:", (error as { message: string }).message);
        } else {
          console.log("Request canceled");
        }
      } else {
        ToastMessage("error", "An error occurred while deleting the address");
      }
    } finally {
      setIsDeleting(false);
    }
  };

  const handleSetDefault = async (id: number) => {
    try {
      // Assuming you have an API endpoint to set default address
      const response = await axios.patch(`/api/user/address/default`, { id });
      if (response.status === 200) {
        setAddresses(
          addresses.map((address) => ({
            ...address,
            is_default: address.id === id,
          }))
        );
      }
    } catch (error) {
      ToastMessage("error", "Failed to set default address");
    }
  };

  return (
    <div className="grid gap-4 md:grid-cols-2">
      {addresses.length === 0 ? (
        <div className="mt-5 col-span-2 rounded-lg border border-dashed p-8 text-center">
          <h3 className="text-lg font-medium">No addresses found</h3>
          <p className="mt-1 text-sm text-muted-foreground">
            You haven&apos;t added any addresses yet.
          </p>
        </div>
      ) : (
        addresses.map((address) => (
          <Card key={address.uuid} className="relative overflow-hidden mt-5">
            {address.is_default && (
              <Badge className="absolute right-4 top-4 text-white">
                Default
              </Badge>
            )}
            <CardContent className="p-6">
              <div className="space-y-2">
                <h3 className="font-semibold">{address.name}</h3>
                <p className="text-sm text-muted-foreground">
                  {address.address_line}
                  <br />
                  {address.city}, {address.district} {address.post_code}
                  <br />
                  {address.division}
                  <br />
                </p>
              </div>
            </CardContent>
            <CardFooter className="flex justify-between border-t bg-muted/50 px-6 py-3">
              <div>
                {!address.is_default && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleSetDefault(address.id)}
                    disabled={isDeleting}
                  >
                    Set as default
                  </Button>
                )}
              </div>
              <div className="flex space-x-2">
                <AddressDialog address={address}>
                  <Button size="icon" variant="ghost" disabled={isDeleting}>
                    <FiEdit className="h-4 w-4" />
                    <span className="sr-only">Edit</span>
                  </Button>
                </AddressDialog>

                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button size="icon" variant="ghost" disabled={isDeleting}>
                      <FiTrash2 className="h-4 w-4" />
                      <span className="sr-only">Delete</span>
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent className="bg-white text-black">
                    <AlertDialogHeader>
                      <AlertDialogTitle>
                        Are you absolutely sure?
                      </AlertDialogTitle>
                      <AlertDialogDescription>
                        This action cannot be undone. This will permanently
                        delete your address and remove your data from our
                        servers.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel
                        disabled={isDeleting}
                      >
                        Cancel
                      </AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => handleDelete(address.uuid)}
                        disabled={isDeleting}
                        className="text-white"
                      >
                        {isDeleting ? "Deleting..." : "Continue"}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </CardFooter>
          </Card>
        ))
      )}
    </div>
  );
};

export default AddressList;
