"use client";

import React, { useState, useEffect } from "react";
import {
  Card,
  CardContent,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { PlusIcon } from "lucide-react";
import AddressList from "@/components/user/address/address-list";
import { AddressDialog } from "@/components/user/address/address-dialog";
import { useSession } from "next-auth/react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast, Flip } from "react-toastify";
import ToastMessage from "@/components/common/ToastMessage";

const formSchema = z.object({
  address_line: z.string(),
  post_code: z.string(),
  city: z.string(),
  district: z.string(),
  division: z.string(),
  updated_by: z.string().optional(),
});

type FormData = z.infer<typeof formSchema>;
// type Address = {
//   id: string;
//   is_default: boolean;
//   [key: string]: any;
// };

type Profile = {
  full_name: string;
  mobile_number: string;
  picture: { file_url: string };
  gender: string;
  address: Address[];
};

type User = {
  email: string;
  profile: Profile;
};

async function getUserByUuid(uuid: string): Promise<{ User: User; UserAddresses: Address[] }> {
  const res = await fetch(`/api/user/${uuid}`);
  return res.json();
}

const AddressComponentClient = () => {
  const { data: session } = useSession();
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [defaultAddress, setDefaultAddress] = useState<Address>();

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      address_line: "",
      post_code: "",
      city: "",
      district: "",
      division: "",
    },
  });

  useEffect(() => {
    const fetchUserAddresses = async () => {
      try {
        const response = await fetch("/api/user/address");
        if (response.ok) {
          const data = await response.json();
          
          console.log(data)

          setAddresses(data.mssg);
        } else {
          ToastMessage("error", "User addresses fetch error!");
        }
      } catch (error) {
        ToastMessage("error", "User addresses fetch error!");
      }
    };

    if (session?.user?.uuid) fetchUserAddresses();
  }, [session]);

  const refreshAddresses = async () => {
    if (!session?.user?.uuid) return;
    const { UserAddresses } = await getUserByUuid(session.user.uuid);
    setAddresses(UserAddresses);
    const def = UserAddresses.find((addr) => addr.is_default);
    setDefaultAddress(def);
  };

  const addNewAddress = async (data: FormData) => {
    if (!session?.user?.uuid) return;

    const res = await fetch(`/api/user/address/${session.user.uuid}`, {
      method: "POST",
      body: JSON.stringify({ ...data, updated_by: session.user.role }),
      headers: { "Content-Type": "application/json" },
    });

    const result = await res.json();

    if (res.ok) {
      await refreshAddresses();
      toast.success(result.message, {
        position: "bottom-right",
        autoClose: 4000,
        theme: "colored",
        transition: Flip,
      });
      form.reset();
    } else {
      toast.error("Failed to add address.");
    }
  };

  const updateDefaultAddress = async (addressId: string, profileId: number) => {
    if (!session?.user?.uuid) return;

    const res = await fetch("/api/user/updateaddress", {
      method: "PUT",
      body: JSON.stringify({ uuid: addressId, profileId }),
      headers: { "Content-Type": "application/json" },
    });

    if (res.ok) {
      await refreshAddresses();
      toast.success("Default address updated successfully");
    } else {
      toast.error("Failed to update default address");
    }
  };

  const deleteAddress = async (addressId: string) => {
    if (!session?.user?.uuid) return;

    const res = await fetch(`/api/user/address/${addressId}`, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
    });

    if (res.ok) {
      await refreshAddresses();
      toast.success("Address deleted successfully");
    } else {
      toast.error("Failed to delete address");
    }
  };

  return (
    <div className="space-y-2 py-5 px-2">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">My Addresses</h1>
          <p className="text-muted-foreground">
            Manage your shipping and billing addresses.
          </p>
        </div>
        <AddressDialog>
          <Button className="text-white">
            <PlusIcon className="mr-2 h-4 w-4 text-white" />
            Add New Address
          </Button>
        </AddressDialog>
      </div>

      <Card>
        <CardContent>
          {addresses.length > 0 ? (
            <AddressList initialData={addresses} />
          ) : (
            <p className="text-sm text-muted-foreground py-4">
              No addresses found. Add one to get started!
            </p>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default AddressComponentClient;
