import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { editProfile, getProfile } from "@/lib/services/profile.service";
import showCustomToast from "@/components/common/toaster/CustomToast";
import { APIResponseType } from "@/type/comonType";
import { ProfileDataType } from "@/type/userType";
import { mapProfileToUserDetails } from "../utils";
import { useProfesion } from "@/app/(auth)/register/hook/useProfesion";

// ─── Dialog types ──────────────────────────────────────────────────────────
const dialogConfig = {
  personalDetails: { title: "Personal Details", variant: "personalDetails" },
  otherContact: { title: "Other Contact", variant: "otherContact" },
} as const;

export type DialogKey = keyof typeof dialogConfig;
export { dialogConfig };

export function useContactSection() {
  const queryClient = useQueryClient();
  const { professionOptions } = useProfesion();

  // ─── 1. QUERY: fetch profile data ─────────────────────────────────────────
  // When this resolves, profileData contains the full profile from the API.
  // We derive mappedUserDetails and defaultValues from it.
  const { data: profileData, isLoading } = useQuery<
    APIResponseType<ProfileDataType>
  >({
    queryKey: ["profile"],
    queryFn: getProfile,
  });

  // ─── 2. DIALOG STATE ──────────────────────────────────────────────────────
  // activeDialog = null  → no dialog open
  // activeDialog = "personalDetails" → personal dialog open
  // activeDialog = "otherContact"    → other contact dialog open
  const [activeDialog, setActiveDialog] = useState<DialogKey | null>(null);

  // ─── 3. DEFAULT VALUES: auto-populated from profile ───────────────────────
  // When the user clicks "Edit Details", we read the already-fetched
  // profileData and shape it into the form's expected structure.
  //
  // Shape must match what CustomDialog / RHF expects:
  //   { personalDetails: [{ full_name, gender, phone, ... }] }
  //   { otherContact:    [{ father_name, country, city, ... }] }
  //
  // We wrap in an array because useFieldArray always works with arrays.
  const defaultValues = useMemo(() => {
    if (!profileData?.data || !activeDialog) return undefined;

    const p = profileData.data;
    console.log("--------Data-------", p);

    if (activeDialog === "personalDetails") {
      return {
        personalDetails: [
          {
            full_name: p.user?.name,
            gender: p.gender ? { label: p.gender, value: p.gender } : null,
            height: p.height,
            marital_status: p.marital_status
              ? { label: p.marital_status, value: p.marital_status }
              : null,
            phone: p.user?.phone,
            email: p.user?.email,
            national_id: p.national_id,
            dob: p.dob,
            blood_group: p.blood_group
              ? { label: p.blood_group, value: p.blood_group }
              : null,
            religion: p.religion,
            secondary_phone: p.secondary_phone,
            passport_id: p.passport_id,
            birth_certificate_id: p.birth_certificate_id,
          },
        ],
      };
    }

    if (activeDialog === "otherContact") {
      return {
        otherContact: [
          {
            father_name: p.father_name,
            mother_name: p.mother_name,
            country: p.country,
            city: p.city,
            postal_code: p.postal_code,
            emergency_contact: p.emergency_contact,
            present_address: p.present_address,
            permanent_address: p.permanent_address,
          },
        ],
      };
    }

    return undefined;
  }, [profileData, activeDialog]);
  // ↑ Recalculates only when profileData or activeDialog changes.
  //   So clicking "personalDetails" gives personal defaults,
  //   clicking "otherContact" gives other contact defaults.

  // ─── 4. MUTATION: save profile ────────────────────────────────────────────
  // Single mutation handles both personalDetails and otherContact
  // because both call the same editProfile API endpoint.
  const { mutate, isPending } = useMutation<
    APIResponseType<ProfileDataType>,
    AxiosError<{ message: string }>,
    ProfileDataType
  >({
    mutationFn: editProfile,
    onSuccess: (data) => {
      showCustomToast({ type: "success", message: data.message });
      queryClient.invalidateQueries({ queryKey: ["profile"] });
      closeDialog();
    },
    onError: (error) => {
      showCustomToast({
        type: "error",
        message: error.response?.data?.message ?? "Something went wrong",
      });
    },
  });

  // ─── 5. HANDLERS ──────────────────────────────────────────────────────────

  // Opens the correct dialog — defaultValues auto-computed from activeDialog
  const openDialog = (key: DialogKey) => setActiveDialog(key);
  const closeDialog = () => setActiveDialog(null);

  // Called by CustomDialog onSubmit.
  // data shape: { personalDetails: [{}] } or { otherContact: [{}] }
  // We extract [0] because useFieldArray wraps everything in an array.
  const handleSubmit = (data: any) => {
    console.log("data===-=-=", data);

    if (activeDialog === "personalDetails") {
      const formValues = data.personalDetails[0];

      const payload = {
        ...formValues,
        gender:
          typeof formValues.gender === "object" && formValues.gender !== null
            ? formValues.gender?.value || formValues.gender?.label
            : formValues.gender,
        marital_status:
          typeof formValues.marital_status === "object" &&
          formValues.marital_status !== null
            ? formValues.marital_status?.value ||
              formValues.marital_status?.label
            : formValues.marital_status,
        blood_group:
          typeof formValues.blood_group === "object" &&
          formValues.blood_group !== null
            ? formValues.blood_group?.value || formValues.blood_group?.label
            : formValues.blood_group,
      };

      mutate(payload);
    }
    if (activeDialog === "otherContact") {
      mutate(data.otherContact[0]);
    }
  };

  // ─── 6. MAPPED DISPLAY DATA ───────────────────────────────────────────────
  // Separate from defaultValues — this is just for rendering
  // the read-only CustomPersonalDetails display, not the form.
  const mappedUserDetails = useMemo(
    () => mapProfileToUserDetails(profileData?.data),
    [profileData],
  );

  return {
    isLoading,
    isPending,
    activeDialog,
    defaultValues, // ✅ auto-filled from profileData when dialog opens
    mappedUserDetails,
    openDialog,
    professionOptions,
    closeDialog,
    handleSubmit,
    mutate,
  };
}
