"use client";
import {
  useEffect,
  useState,
  Suspense,
  lazy,
  FormEvent,
  ChangeEvent,
  useRef,
} from "react";
import { FormInput, FormButton } from "@/app/components/form/forms";
import Image from "next/image";
import MobileNumber from "@/app/components/form/country/MobileNumber";
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
import { GeoLocation } from "@/app/components/locations/geonames";
import { toast } from "react-toastify";
import { RadioChip, SingleChip } from "@/app/components/chips";

const ZipCodeLookup = lazy(
  () => import("@/app/components/locations/ZipCodeLookup"),
);

type Category = {
  id: string;
  label: string;
};

export default function UserProfile() {
  const [userRoles, setUserRoles] = useState([
    {
      id: 1,
      role: "user_cocreator",
      label: "Co-Creator",
      image: "/icons/user-brand-partner.png",
      activate: false,
    },
    {
      id: 9,
      role: "user_seeker",
      label: "Seeker",
      image: "/icons/user-seeker.png",
      activate: false,
    },
    {
      id: 4,
      role: "user_brand_partner",
      label: "Brand Partner",
      image: "/icons/user-brand-partner.png",
      activate: false,
    },

    {
      id: 7,
      role: "user_design_house",
      label: "Design House",
      image: "/icons/user-design-house.png",
      activate: false,
    },
    {
      id: 8,
      role: "user_supplier",
      label: "Supplier",
      image: "/icons/user-supplier.png",
      activate: false,
    },
    {
      id: 6,
      role: "user_wholesaler",
      label: "Wholesaler",
      image: "/icons/user-wholesaler.png",
      activate: false,
    },
  ]);
  const [name, setName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [photo, setPhoto] = useState(
    "https://ui-avatars.com/api/?name=ft2&color=7F9CF5&background=EBF4FF",
  );

  const [gender, setGender] = useState("");
  const [dob, setDob] = useState("");
  const [loc, setLoc] = useState<GeoLocation | null>(null);
  const [vibe, setVibe] = useState<Category[]>([]);

  const [mobileCode, setMobileCode] = useState("+1");
  const [mobileNumber, setMobileNumber] = useState("");
  const [selectedRoles, setSelectedRoles] = useState<[]>([]);
  const [rolesChanged, setRolesChanged] = useState(false);

  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [selectedInterests, setSelectedInterests] = useState<string[]>([]);

  // Debug state changes
  useEffect(() => {
    console.log("State updated:", {
      gender,
      dob,
      selectedInterests: selectedInterests.length,
      loc: loc?.placeName,
    });
  }, [gender, dob, selectedInterests, loc]);

  // Debug gender specifically
  useEffect(() => {
    console.log("Gender changed to:", gender, "Type:", typeof gender);
  }, [gender]);

  useEffect(() => {
    console.log("Component mounted - fetching user data");
    fetchUserData();
  }, []); // Empty dependency array ensures this only runs once on mount

  // When the user selects a file, store it and also update preview (photoUrl)
  const handleFileSelect = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      setSelectedFile(file);

      // Create a temporary preview URL (optional)
      const previewUrl = URL.createObjectURL(file);
      setPhoto(previewUrl);
    }
  };
  const fetchUserData = async () => {
    try {
      console.log("=== fetchUserData called ===");
      const response = await fetch("/api/user/get-profile", {
        method: "GET",
        credentials: "include", // Important: includes cookies in the request
        cache: "no-store", // Always fetch fresh data
        headers: {
          "Content-Type": "application/json",
        },
      });

      console.log("Fetch User Response:", response.status, response.ok);

      const result = await response.json();
      console.log("Fetch User Result:", result);

      const user = result.data?.user;

      console.log("user", user);

      if (user) {
        // Assuming full name is returned in `name`, and split by space
        const [first, last] = user.name?.split(" ") || [];

        console.log("About to set state with:", {
          gender: user.gender,
          dob: user.dob,
          interests: user.interest?.length || 0,
        });

        setName(user.name);
        setPhoto(user.profile_photo);
        // setLastName(last || "");
        setEmail(user.email || "");
        setMobileCode(user.mobile_code || "");
        setMobileNumber(user.phone || "");
        setSelectedRoles(user.roles || []);
        setDob(user.dob || "");
        setGender(user.gender || "");

        // Parse and set location
        if (user.loc) {
          try {
            const parsedLoc = JSON.parse(user.loc);
            console.log("Parsed location:", parsedLoc);
            setLoc(parsedLoc);
          } catch (e) {
            console.error("Failed to parse location:", e);
            setLoc(null);
          }
        } else {
          setLoc(null);
        }

        // Set interests directly from user data - convert IDs to strings
        if (user.interest && Array.isArray(user.interest)) {
          const interestIds = user.interest.map((interest: any) =>
            String(interest.id),
          );
          console.log("Setting interests:", interestIds);
          setSelectedInterests(interestIds);
        } else {
          setSelectedInterests([]);
        }

        console.log("Set values - Gender:", user.gender, "DOB:", user.dob);

        // Update userRoles based on selectedRoles from API
        setUserRoles((prevRoles) =>
          prevRoles.map((role) => ({
            ...role,
            activate:
              user.roles?.some(
                (selectedRole: any) => selectedRole.id === role.id,
              ) || false,
          })),
        );

        console.log("=== fetchUserData complete ===");
      }
    } catch (error) {
      console.error("Error fetching user data:", error);
      toast.error("Failed to fetch user data");
    }
  };
  // On form submit: gather all fields (including file, if there is one) and POST/PUT to your API
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    // If you need to upload a file, use FormData:
    const formData = new FormData();
    formData.append("name", name);
    formData.append("email", email);
    formData.append("mobile_code", mobileCode);
    formData.append("mobile", mobileNumber);
    formData.append("gender", gender);
    formData.append("dob", dob);
    formData.append("location", JSON.stringify(loc));

    // Append interests as array format that Laravel expects: interest_ids[0], interest_ids[1]
    selectedInterests.forEach((interest, index) => {
      formData.append(`interests[${index}]`, interest);
    });

    // Only append 'photo' if the user actually selected a new one
    if (selectedFile) {
      formData.append("profile_photo", selectedFile);
    }

    console.log("formData", formData);
    try {
      // Call Next.js API route which handles authentication via cookies
      const response = await fetch("/api/user/profile", {
        method: "POST",
        credentials: "include", // Important: includes cookies in the request
        body: formData,
      });

      console.log("Response status:", response.status);
      console.log("Response ok:", response.ok);

      const result = await response.json();
      console.log("API Response:", result);

      if (!response.ok || !result.success) {
        const errorMessage = result.message || "Failed to update profile";
        console.error("Profile update failed:", errorMessage);
        toast.error(errorMessage);
        return;
      }

      console.log("Profile updated successfully:", result);
      toast.success(result.message || "Profile updated successfully!", {
        toastId: "profile_updated_success", // prevents duplicate toasts
      });

      // Add small delay to ensure backend has processed the update
      await new Promise((resolve) => setTimeout(resolve, 300));

      // Refetch user data to update UI with fresh data
      console.log("Refetching user data after update...");
      await fetchUserData();
    } catch (err) {
      console.error("Network or server error", err);
      toast.error("Network error. Please try again.");
    }
  };
  // When user clicks "Change photo" button, trigger our hidden file input
  const handleChangePhotoClick = () => {
    fileInputRef.current?.click();
  };

  // Handle role toggle (select/unselect)
  const handleRoleToggle = (roleId: number) => {
    setUserRoles((prevRoles) =>
      prevRoles.map((role) =>
        role.id === roleId ? { ...role, activate: !role.activate } : role,
      ),
    );
    setRolesChanged(true);
  };

  // Save role changes to backend
  const handleSaveRoles = async () => {
    const activeRoleIds = userRoles
      .filter((role) => role.activate)
      .map((role) => role.id);

    try {
      // Call Next.js API route which handles authentication via cookies
      const response = await fetch("/api/user/update-roles", {
        method: "POST",
        credentials: "include", // Important: includes cookies in the request
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ role_ids: activeRoleIds }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        toast.error(
          errorData.message || "Failed to update roles. Please try again.",
        );
        return;
      }

      const result = await response.json();
      console.log("Roles updated successfully:", result);
      toast.success(result.message || "Roles updated successfully!", {
        toastId: "roles_updated_success",
      });

      setRolesChanged(false);

      // Add small delay to ensure backend has processed the update
      await new Promise((resolve) => setTimeout(resolve, 300));

      // Refetch profile data with fresh data
      console.log("Refetching user data after roles update...");
      await fetchUserData();
    } catch (err) {
      console.error("Network or server error", err);
      toast.error("Network error. Please try again.");
    }
  };

  useEffect(() => {
    console.log("Component mounted - fetching categories");
    getCategoryList();
  }, []); // Empty dependency array ensures this only runs once on mount

  // Debug when vibe categories are loaded
  useEffect(() => {
    if (vibe && vibe.length > 0) {
      console.log(
        "Vibe categories loaded:",
        vibe.length,
        "Selected interests:",
        selectedInterests,
      );
    }
  }, [vibe, selectedInterests]);

  async function getCategoryList() {
    try {
      const response = await fetch("/api/vibe", {
        method: "GET",
        credentials: "include", // Important: includes cookies in the request
        cache: "force-cache", // Categories can be cached as they rarely change
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      const data = await response.json();
      console.log("response-category", data.data);
      if (data.data && data.data.length > 0) {
        console.log(
          "First category ID type:",
          typeof data.data[0].id,
          "Value:",
          data.data[0].id,
        );
      }
      setVibe(data.data);

      return data; // Return the data if needed
    } catch (error) {
      console.error("Error fetching category list:", error);
    }
  }
  const handleSelect = (interest: string) => {
    console.log(
      "handleSelect called with:",
      interest,
      "Type:",
      typeof interest,
    );
    console.log("Current selectedInterests:", selectedInterests);

    setSelectedInterests((prev) => {
      const newSelection = prev.includes(interest)
        ? prev.filter((item) => item !== interest)
        : [...prev, interest];

      console.log("New selectedInterests:", newSelection);
      return newSelection;
    });
  };

  return (
    <div className="flex w-full flex-1 flex-col gap-4">
      <div className="flex w-full flex-col">
        <div className="flex flex-col">
          <h1 className="med">My profile</h1>
        </div>
        <div className="mt-5 flex w-full flex-col justify-between gap-5 align-top md:flex-row">
          <div className="flex w-full flex-col">
            {/* Settings forms */}
            <div className="flex w-full flex-col gap-10">
              {/** start code for personal information */}
              <div className="grid grid-cols-1 bg-white/75 p-5 md:p-10">
                <h4 className="text-base/7">Personal Information</h4>
                <form
                  className="mt-5"
                  id="form_personal_info"
                  onSubmit={handleSubmit}
                  encType="multipart/form-data"
                >
                  <div className="grid grid-cols-1">
                    <div className="flex items-center gap-x-8">
                      <Image src={photo} alt="he" height={80} width={80} />
                      <div>
                        <button
                          type="button"
                          className="btn-outline"
                          onClick={handleChangePhotoClick}
                        >
                          Change photo
                        </button>
                        <p className="mt-2 text-xs">
                          JPG, GIF or PNG. 1MB max.
                        </p>
                      </div>
                    </div>
                    <div className="grid grid-cols-1 gap-0 md:grid-cols-2 md:gap-10">
                      <input
                        type="file"
                        accept="image/*"
                        ref={fileInputRef}
                        onChange={handleFileSelect}
                        className="hidden"
                      />

                      <FormInput
                        type="text"
                        id="full_name"
                        label="Full name"
                        require={true}
                        value={name}
                        onChange={(e: any) => setName(e.target.value)}
                      />

                      <FormInput
                        type="email"
                        id="email"
                        label="Email"
                        require={true}
                        value={email}
                        onChange={(e: any) => setEmail(e.target.value)}
                      />
                      <div className="mt-8 md:mt-0">
                        <MobileNumber
                          mobileCode={mobileCode}
                          setMobileCode={setMobileCode}
                          mobileNumber={mobileNumber}
                          setMobileNumber={setMobileNumber}
                        />
                      </div>

                      <div className="mt-8 md:mt-0">
                        <RadioChip
                          id="gender_male"
                          name="User_gender"
                          label="Male"
                          checked={gender === "male"}
                          onChange={() => {
                            console.log("RadioChip clicked: male");
                            setGender("male");
                          }}
                        />

                        <RadioChip
                          id="gender_female"
                          name="User_gender"
                          label="Female"
                          checked={gender === "female"}
                          onChange={() => {
                            console.log("RadioChip clicked: female");
                            setGender("female");
                          }}
                        />

                        <RadioChip
                          id="gender_rather"
                          name="User_gender"
                          label="rather not say"
                          checked={gender === "rather_not_say"}
                          onChange={() => {
                            console.log("RadioChip clicked: rather_not_say");
                            setGender("rather_not_say");
                          }}
                        />
                      </div>
                    </div>
                    <div className="mt-8">
                      <FormInput
                        type="date"
                        name="dob"
                        id="dob"
                        label="Date of Birth"
                        require={false}
                        value={dob}
                        onChange={(e) => setDob(e.target.value)}
                      />
                    </div>
                    <div className="relative z-50 mt-16">
                      <Suspense fallback={<p>Loading location finder...</p>}>
                        <ZipCodeLookup
                          defaultValue={loc}
                          onSelect={(loc: GeoLocation | null) => {
                            setLoc(loc);
                          }}
                        />
                      </Suspense>
                    </div>
                    <div className="mt-1 flex flex-wrap items-center gap-4">
                      <h5 className="mt-4 mr-4">I am feeling</h5>
                      <div className="flex flex-wrap gap-3">
                        {vibe &&
                          vibe.map((category, index) => {
                            const isChecked = selectedInterests.includes(
                              String(category.id),
                            );
                            if (index === 0) {
                              console.log(
                                "First chip - ID:",
                                category.id,
                                "Type:",
                                typeof category.id,
                                "Checked:",
                                isChecked,
                                "SelectedInterests:",
                                selectedInterests,
                              );
                            }
                            return (
                              <SingleChip
                                key={category.id}
                                id={category.id}
                                label={category.label}
                                value={category.id}
                                checked={isChecked}
                                onChange={() =>
                                  handleSelect(String(category.id))
                                }
                              />
                            );
                          })}
                      </div>
                    </div>
                    <div className="flex w-full md:w-[30%]">
                      <FormButton
                        id="btn_save_personal_info"
                        label="Save"
                        type="submit"
                        color="gray"
                        hairline=""
                        disabled={false}
                      />
                    </div>
                  </div>
                </form>
              </div>
              {/** end code for personal information */}
              <div className="grid grid-cols-1 bg-white/75 p-5 md:p-10">
                <div className="flex flex-col">
                  <h4 className="text-base/7">Your User Roles</h4>
                </div>
                <div className="mt-5 flex w-full">
                  <TabGroup>
                    <TabList className="grid grid-cols-3 items-center justify-center gap-5 align-middle md:grid-cols-6">
                      {userRoles.map((item) => (
                        <Tab
                          key={item.id}
                          className="flex w-full flex-col text-xs/3 font-medium outline-0 data-selected:bg-blue-100 data-selected:outline-2 data-selected:outline-blue-200"
                          onClick={() => handleRoleToggle(item.id)}
                        >
                          {item.activate ? (
                            <div className="relative flex w-full flex-col items-center justify-center gap-2 border-1 border-blue-400 p-2 outline-2 outline-blue-400">
                              <span className="absolute -top-3 -right-3 flex h-6 w-6 items-center justify-center rounded-full bg-blue-400 align-middle text-white">
                                <i className="icon-[mingcute--check-fill]"></i>
                              </span>
                              <div className="flex h-20 w-20 items-center justify-center align-middle">
                                <Image
                                  src={item.image}
                                  alt={item.label}
                                  width={128}
                                  height={128}
                                  className="img-responsive"
                                />
                              </div>
                              <div className="flex h-8">{item.label}</div>
                            </div>
                          ) : (
                            <div className="relative flex w-full flex-col items-center justify-center gap-2 border-1 border-dashed p-2">
                              <div className="flex h-20 w-20 items-center justify-center align-middle">
                                <Image
                                  src={item.image}
                                  alt={item.label}
                                  width={128}
                                  height={128}
                                  className="img-responsive"
                                />
                              </div>
                              <div className="flex h-8">{item.label}</div>
                            </div>
                          )}
                        </Tab>
                      ))}
                    </TabList>
                    <TabPanels className="py-10">
                      <TabPanel>
                        <div className="flex flex-col gap-10">
                          <div>
                            I want to design and create my own custom piece.
                          </div>
                        </div>
                      </TabPanel>
                      <TabPanel>
                        <div className="flex flex-col gap-5">
                          <div>
                            I want to browse and buy unique pieces from the
                            Morni store.
                          </div>
                        </div>
                      </TabPanel>
                      <TabPanel>
                        <div className="flex flex-col gap-10">
                          <div>
                            I run a brand and want to work with Morni to design
                            and produce clothing.
                          </div>
                        </div>
                        {/* <div className="mt-5">
                          <span className="inline-flex items-center gap-1 rounded-full bg-teal-300 px-4 py-2 text-sm font-medium text-white">
                            <i className="icon-[mingcute--check-fill]"></i>
                            Verified
                          </span>
                        </div> */}
                        {/* <div>
                          <div className="font-bogart text-lg font-light">
                            You have an authorised user role of{" "}
                            <span className="font-medium">Brand Partner</span>.
                          </div>
                        </div> */}
                      </TabPanel>
                      <TabPanel>
                        <div className="flex flex-col gap-10">
                          <div>
                            I want to work as a design house with Morni to
                            create unique clothing designs.
                          </div>
                        </div>
                      </TabPanel>
                      <TabPanel>
                        <div className="flex flex-col gap-10">
                          <div>
                            I provide natural fabrics or materials that can be
                            used in Morni’s production.
                          </div>
                        </div>
                      </TabPanel>
                      <TabPanel>
                        <div className="flex flex-col gap-10">
                          <div>
                            I want to buy Morni pieces in bulk for my store or
                            business.
                          </div>
                        </div>
                      </TabPanel>
                    </TabPanels>
                  </TabGroup>
                </div>
                {rolesChanged && (
                  <div className="mt-5 flex w-full justify-center">
                    <div className="w-auto">
                      <FormButton
                        id="btn_save_roles"
                        label="Save Role Changes"
                        type="button"
                        color="primary"
                        hairline=""
                        disabled={false}
                        onClick={handleSaveRoles}
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
