"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Save } from "lucide-react";
// import { toast } from "@/components/ui/use-toast";
import { getCountry, getStates, getCities } from "@/lib/api/auth"; // ⚙️ your API functions
import { DEFAULT_LANGUAGE, getStoredLanguage, Language } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { toast } from "sonner";
import { updateProfile } from "@/lib/api/apis";

interface UserData {
  name: string;
  email: string;
  mobile: string;
  country?: string;
  state?: string;
  city?: string;
  id?: string;
  gender?: string;
  date_of_birth?: string;
}

export default function EditProfilePage() {
  const [user, setUser] = useState<UserData>({
    name: "",
    email: "",
    mobile: "",
    country: "",
    state: "",
    city: "",
    id: "",
  });

  const [countries, setCountries] = useState<any[]>([]);
  const [states, setStates] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);
  const router = useRouter();
  const [mounted, setMounted] = useState(false);
  const [lang, setLang] = useState<Language>(DEFAULT_LANGUAGE);
  // Tracks which fields had a value at load time (only these are shown)
  const [visibleFields, setVisibleFields] = useState<Record<string, boolean>>(
    {},
  );

  // ⚙️ Load Countries / States / Cities
  const loadCountries = async () => {
    const res = await getCountry();
    if (res.data) setCountries(res.data || []);
  };

  const loadStates = async (countryId: string) => {
    const res = await getStates(countryId);
    if (res.data) setStates(res.data || []);
  };

  const loadCities = async (stateId: string) => {
    const res = await getCities(stateId);
    if (res.data) setCities(res.data || []);
  };

  // 🧠 Initialize profile
  useEffect(() => {
    const init = async () => {
      const storedData = localStorage.getItem("register_details");
      const stored = localStorage.getItem("user_data");

      const raw = storedData || stored;
      if (!raw) {
        router.push("/login");
        return;
      }

      const parsed = JSON.parse(raw);

      // Snapshot which fields have a value so we only render those
      setVisibleFields({
        name: !!parsed.name,
        email: !!parsed.email,
        mobile: !!parsed.mobile,
        gender: !!parsed.gender,
        date_of_birth: !!parsed.date_of_birth,
        country: !!parsed.country,
        state: !!parsed.state,
        city: !!parsed.city,
      });

      // Load countries
      const countryRes = await getCountry();
      const countriesList = countryRes?.data || [];
      setCountries(countriesList);

      // Find selected country ID from name
      const selectedCountry = countriesList.find(
        (c: any) => c.name === parsed.country,
      );

      const countryId = selectedCountry?.id ? String(selectedCountry.id) : "";

      // Load states
      let statesList: any[] = [];
      if (countryId) {
        const stateRes = await getStates(countryId);
        statesList = stateRes?.data || [];
        setStates(statesList);
      }

      // Find selected state ID from name
      const selectedState = statesList.find(
        (s: any) => s.name === parsed.state,
      );

      const stateId = selectedState?.id ? String(selectedState.id) : "";

      // Load cities
      let citiesList: any[] = [];
      if (stateId) {
        const cityRes = await getCities(stateId);
        citiesList = cityRes?.data || [];
        setCities(citiesList);
      }

      // Find selected city ID from name
      const selectedCity = citiesList.find((c: any) => c.name === parsed.city);
      const cityId = selectedCity?.id ? String(selectedCity.id) : "";

      // ✅ Now set user with IDs so dropdown auto-select works
      setUser((prev: any) => ({
        ...prev,
        ...parsed,
        // country: countryId,
        // state: stateId,
        // city: cityId,
      }));
    };

    init();
  }, [router]);

  const handleSave = async () => {
    if (!user.name) {
      toast.error(t.editProfile.enterName);
      return;
    }
    if (!user.email) {
      toast.error(t.editProfile.enterEmail);
      return;
    }
    if (!user.country) {
      toast.error(t.editProfile.selectCountryMsg);
      return;
    }
    if (!user.state) {
      toast.error(t.editProfile.selectStateMsg);
      return;
    }
    if (!user.city) {
      toast.error(t.editProfile.selectCityMsg);
      return;
    }
    const formData = new FormData();
    formData.append("user_id", user.id || "");
    formData.append("name", user.name);
    formData.append("gender", user.gender || "");
    formData.append("date_of_birth", user.date_of_birth || "");
    formData.append("country", user.country || "");
    formData.append("state", user.state || "");
    formData.append("city", user.city || "");

    try {
      const res = await updateProfile(formData);
      if (res.data) {
        localStorage.setItem("user_data", JSON.stringify(res.data));
        localStorage.setItem("register_details", JSON.stringify(res.data));
        toast.success(t.editProfile.profileUpdated);

        router.push("/profile");
      } else {
        toast.error(res.message || t.editProfile.updateFailed);
      }
    } catch (error) {
      toast.error(t.editProfile.updateError);
    }
  };

  useEffect(() => {
    setLang(getStoredLanguage());
    setMounted(true);
  }, []);

  if (!mounted) return null;

  const t = getTranslation(lang);

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-orange-50 pt-28 pb-20">
      <div className="container mx-auto max-w-3xl px-4">
        <Card className="shadow-xl border border-orange-100">
          <CardContent className="p-8">
            <h1 className="text-2xl font-semibold text-gray-800 mb-8 text-center">
              {t.editProfile.title}
            </h1>

            <div className="space-y-6">
              {/* 🔹 Name */}
              {visibleFields.name && (
                <div>
                  <Label htmlFor="name">{t.editProfile.fullName}</Label>
                  <Input
                    id="name"
                    value={user.name}
                    maxLength={30}
                    onChange={(e) => setUser({ ...user, name: e.target.value })}
                    className="border-gray-300 focus:ring-[#FAA631] focus:border-[#FAA631]"
                  />
                </div>
              )}

              {/* 🔹 Email */}
              {visibleFields.email && (
                <div>
                  <Label htmlFor="email">{t.editProfile.email}</Label>
                  <Input
                    id="email"
                    value={user.email}
                    onChange={(e) =>
                      setUser({ ...user, email: e.target.value })
                    }
                    className="border-gray-300 focus:ring-[#FAA631] focus:border-[#FAA631]"
                  />
                </div>
              )}

              {/* 🔹 Mobile (not editable) */}
              {visibleFields.mobile && (
                <div>
                  <Label htmlFor="mobile">{t.editProfile.mobile}</Label>
                  <Input
                    disabled
                    id="mobile"
                    value={user.mobile}
                    maxLength={15}
                    className="border-gray-300 bg-gray-50 text-gray-500 cursor-not-allowed"
                  />
                </div>
              )}

              {/* 🔹 Gender */}
              {visibleFields.gender && (
                <div>
                  <Label>{t.editProfile.gender}</Label>
                  <select
                    className="w-full border rounded-md p-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                    value={user.gender || ""}
                    onChange={(e) =>
                      setUser({ ...user, gender: e.target.value })
                    }
                  >
                    <option value="">{t.editProfile.selectGender}</option>
                    <option value="1">{t.editProfile.male}</option>
                    <option value="2">{t.editProfile.female}</option>
                    <option value="3">{t.editProfile.other}</option>
                  </select>
                </div>
              )}

              {/* 🔹 Date of Birth */}
              {visibleFields.date_of_birth && (
                <div>
                  <Label>{t.editProfile.dateOfBirth}</Label>
                  <Input
                    type="date"
                    value={user.date_of_birth || ""}
                    onChange={(e) =>
                      setUser({ ...user, date_of_birth: e.target.value })
                    }
                    className="border-gray-300 focus:ring-[#FAA631] focus:border-[#FAA631] w-full cursor-pointer [&::-webkit-calendar-picker-indicator]:opacity-0 [&::-webkit-calendar-picker-indicator]:absolute [&::-webkit-calendar-picker-indicator]:inset-0 [&::-webkit-calendar-picker-indicator]:w-full [&::-webkit-calendar-picker-indicator]:h-full [&::-webkit-calendar-picker-indicator]:cursor-pointer relative"
                  />
                </div>
              )}

              {/* 🌍 Country Dropdown */}
              {visibleFields.country && (
                <div>
                  <Label>{t.editProfile.country}</Label>

                  <select
                    className="w-full border rounded-md p-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                    value={user.country}
                    onChange={(e) => {
                      const countryName = e.target.value;

                      setUser({
                        ...user,
                        country: countryName,
                        state: "",
                        city: "",
                      });

                      const selected = countries.find(
                        (c: any) => c.name === countryName,
                      );
                      if (selected?.id) {
                        loadStates(selected.id);
                      }

                      setCities([]);
                    }}
                  >
                    <option value="">{t.editProfile.selectCountry}</option>

                    {countries.map((c: any) => (
                      <option key={c.id} value={c.name}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {/* 🏙️ State Dropdown */}
              {visibleFields.state && (
                <div>
                  <Label>{t.editProfile.state}</Label>

                  <select
                    className="w-full border rounded-md p-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                    value={user.state}
                    onChange={(e) => {
                      const stateName = e.target.value;

                      setUser({
                        ...user,
                        state: stateName,
                        city: "",
                      });

                      const selected = states.find(
                        (s: any) => s.name === stateName,
                      );
                      if (selected?.id) {
                        loadCities(selected.id);
                      }
                    }}
                  >
                    <option value="">{t.editProfile.selectState}</option>

                    {states.map((s: any) => (
                      <option key={s.id} value={s.name}>
                        {s.name}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {/* 🏡 City Dropdown */}
              {visibleFields.city && (
                <div>
                  <Label>{t.editProfile.city}</Label>

                  <select
                    className="w-full border rounded-md p-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                    value={user.city}
                    onChange={(e) => {
                      const cityName = e.target.value;

                      setUser({
                        ...user,
                        city: cityName,
                      });
                    }}
                  >
                    <option value="">{t.editProfile.selectCity}</option>

                    {cities.map((c: any) => (
                      <option key={c.id} value={c.name}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {/* 💾 Save Button */}
              <div className="flex justify-center pt-6">
                <Button
                  onClick={handleSave}
                  className="bg-[#FAA631] hover:bg-[#e6972c] text-white text-lg px-8"
                >
                  <Save className="mr-2" size={18} />
                  {t.editProfile.saveChanges}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
