import { useDispatch, useSelector } from "react-redux";
import { closeViewCustomer } from "@/src/redux/appActions";
import { RootState } from "@/src/redux/store";
import { Button } from "@/components/ui/button";
import { CheckCircle } from "lucide-react";
import { useEffect, useState } from "react";
import { useGetUserBioData } from "@/src/utils/hooks/useGetBioData";
import { Customer } from "@/src/utils/types";
import { useGetCustomersProfilePersona } from "@/src/utils/hooks/useGetAdmindashboardStats";
import { setViewCustomer } from "@/src/redux/appActions";
import SectionSkeleton from "./Loading";
import { useGetUserContact } from "@/src/utils/hooks/useGetContact";

export default function CustomerDetails() {
  const dispatch = useDispatch();
  const { isOpen, customerData } = useSelector(
    (state: RootState) => state.counter.viewCustomer
  );

  const [loading, setLoading] = useState<boolean>(false);

  if (!isOpen || !customerData) {
    return null;
  }

  const handleBack = () => {
    dispatch(closeViewCustomer());
  };

  useEffect(() => {
    console.log(customerData, "is customer data");
  });

  const { data: biodata, isLoading: bioDataLoading } = useGetUserBioData(
    customerData.id.toString()
  );

  const { data: profilePersona, isLoading: ProfilePersonaLoading } =
    useGetCustomersProfilePersona(customerData.id.toString());

  const { data: userContact, isLoading: userContactLoading } =
    useGetUserContact(customerData.id);

  useEffect(() => {
    setLoading(bioDataLoading || ProfilePersonaLoading || userContactLoading);

    if (!biodata?.payload || !profilePersona?.payload || !userContact?.payload)
      return;

    const bio = biodata.payload;
    const persona = profilePersona.payload;
    const contact = userContact.payload;

    const address = `${contact.house_number} ${contact.street_name}, ${contact.land_mark}, ${contact.lga}, ${contact.state}`;

    const seen = new Set<string>();
    const religions = bio.religions
      .map((item: any) => item.religion)
      .filter((religion: string) => {
        const lower = religion.toLowerCase();
        if (seen.has(lower)) return false;
        seen.add(lower);
        return true;
      });

    const userReligions = religions.join(", ");

    // Only dispatch if we don't already have the extra bio/persona fields
    if (
      !customerData.occupation &&
      !customerData.heightRange &&
      !customerData.weightRange
    ) {
      const transformedData: Customer = {
        ...customerData,
        ...(bio.occupation && { occupation: bio.occupation }),
        ...(bio.height_range && { heightRange: bio.height_range }),
        ...(bio.weight_range && { weightRange: bio.weight_range }),
        ...(bio.ethnicity && { ethnicity: bio.ethnicity }),
        ...(bio.genotype && { genotype: bio.genotype }),
        ...(bio.marital_status && { maritalStatus: bio.marital_status }),
        ...(bio.religions && { religion: userReligions }),
        ...(persona.gender && { gender: persona.gender }),
        ...(persona.date_of_birth && { dateOfBirth: persona.date_of_birth }),
        ...(contact.nationality && { nationality: contact.nationality }),
        ...(contact.state && { state: contact.state }),
        ...(contact.state &&
          contact.house_number &&
          contact.street_name &&
          contact.land_mark &&
          contact.lga && { physicalAddress: address }),
      };

      dispatch(setViewCustomer(transformedData));
    }
  }, [
    biodata,
    profilePersona,
    customerData,
    dispatch,
    bioDataLoading,
    ProfilePersonaLoading,
    userContactLoading,
    userContact,
  ]);

  return loading ? (
    <SectionSkeleton />
  ) : (
    <div className="w-full">
      <Button
        variant="ghost"
        className="mb-4 p-0 hover:bg-transparent"
        onClick={handleBack}
      >
        <span className="font-medium cursor-pointer">Back</span>
      </Button>

      <h1 className="text-xl font-bold mb-6 text-[12px]">Customer Details</h1>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-[34px]">
        <div>
          <p className="text-sm text-black font-bold text-[10px]">
            Customer Name:
          </p>
          <p className="font-medium text-[10px]">{customerData.name}</p>
        </div>

        <div>
          <p className="text-sm text-black font-bold text-[10px]">Gender:</p>
          <p className="font-medium text-[10px]">{customerData.gender}</p>
        </div>

        <div>
          <p className="text-sm text-black text-[10px] font-bold">E-mail</p>
          <p className="font-medium text-[10px]">{customerData.email}</p>
        </div>

        <div>
          <p className="text-sm text-black text-[10px] font-bold">
            Subscribed Accounts
          </p>
          <p className="font-medium text-[10px]">
            {customerData.subscribedAccounts}
          </p>
        </div>

        <div>
          <p className="text-sm text-black text-[10px] font-bold">
            Occupation:
          </p>
          <p className="font-medium text-[10px]">{customerData.occupation}</p>
        </div>

        <div>
          <p className="text-sm text-black text-[10px] font-bold">
            Height Range:
          </p>
          <p className="font-medium text-[10px]">{customerData.heightRange}</p>
        </div>

        <div>
          <p className="text-sm text-black text-[10px] font-bold">
            Weight Range:
          </p>
          <p className="font-medium text-[10px]">{customerData.weightRange}</p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">Ethnicity:</p>
          <p className="font-medium text-[10px]">{customerData.ethnicity}</p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">Genotype:</p>
          <p className="font-medium text-[10px]">{customerData.genotype}</p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">Religion:</p>
          <p className="font-medium text-[10px]">{customerData.religion}</p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">Marital Status:</p>
          <p className="font-medium text-[10px]">
            {customerData.maritalStatus}
          </p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">Nationality:</p>
          <p className="font-medium text-[10px]">{customerData.nationality}</p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">State:</p>
          <p className="font-medium text-[10px]">{customerData.state}</p>
        </div>

        <div>
          <p className="text-black text-[10px] font-bold">Mobile Number:</p>
          <p className="font-medium text-[10px]">{customerData.phoneNumber}</p>
        </div>

        <div className="col-span-1 md:col-span-2">
          <p className="text-black text-[10px] font-bold">
            Address Verification:
          </p>
          <p className="flex items-center text-[10px]">
            {customerData.isAddressVerified ? "Verified" : "Not-verified"}
          </p>
        </div>

        <div className="col-span-1 md:col-span-2">
          <p className="text-black text-[10px] font-bold">Physical address:</p>
          <div className="flex items-center">
            <p className="font-medium md:mr-1 text-[10px]">
              {customerData.physicalAddress}
            </p>
            {customerData.isAddressVerified && (
              <span className="inline-flex items-center rounded-full px-2 py-1">
                <CheckCircle className="h-3 w-3" color="#2D9CDB" />
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
