"use client";

import React, { useEffect, useState } from "react";
import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import {
  Input,
  Select,
  SelectItem,
  Spinner,
  Autocomplete,
  AutocompleteItem,
} from "@heroui/react";
import { useAppToast } from "@/app/[lang]/providers";
import { useLocale, useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { uploadImage } from "@/actions/upload-image";
import { completeProfile } from "@/actions/auth/login";
import { fetchCountries } from "@/lib/api";
import { API_BASE_URL } from "@/lib/axios";

export default function CompleteProfileModal({
  isOpen,
  onClose,
  token,
  user,
}: {
  isOpen: boolean;
  onClose: () => void;
  token?: string | null;
  user?: any;
}) {
  const t = useTranslations("AUTH");
  const locale = useLocale();
  const dir = (locale || "").toLowerCase().startsWith("ar") ? "rtl" : "ltr";
  const toast = useAppToast();
  const [loading, setLoading] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);
  const [uploadedFile, setUploadedFile] = useState<any>(null);
  const [countries, setCountries] = useState<{ id: number; name: string }[]>(
    [],
  );
  const [countriesLoading, setCountriesLoading] = useState(false);
  const [states, setStates] = useState<{ id: number; name: string }[]>([]);
  const [statesLoading, setStatesLoading] = useState(false);

  const { register, handleSubmit, setValue, watch, reset } = useForm({
    defaultValues: {
      stable_name: "",
      first_name: "",
      last_name: "",
      email: "",
      gender: "male",
      country_id: "",
      state_id: "",
      neighborhood: "",
    },
  });

  const gender = watch("gender");
  const countryId = watch("country_id");
  const stateId = watch("state_id");

  useEffect(() => {
    if (!isOpen || !user || typeof user !== "object") return;
    const u = user as any;
    const firstName =
      u.first_name ?? (u.name ? u.name.split(/\s+/)[0] : "") ?? "";
    const lastName =
      u.last_name ??
      (u.name && u.name.split(/\s+/).length > 1
        ? u.name.split(/\s+/).slice(1).join(" ")
        : "");
    const countryIdVal =
      u.country?.id != null
        ? String(u.country.id)
        : u.country_id != null
          ? String(u.country_id)
          : "";
    const stateIdVal =
      u.state?.id != null
        ? String(u.state.id)
        : u.state_id != null
          ? String(u.state_id)
          : "";
    const profileUrl =
      u.media_files?.profile?.url ??
      (typeof u.media_files?.profile === "string"
        ? u.media_files.profile
        : null);
    reset({
      stable_name: u.stable_name ?? "",
      first_name: firstName,
      last_name: lastName,
      email: u.email ?? "",
      gender: u.gender ?? "male",
      country_id: countryIdVal,
      state_id: stateIdVal,
      neighborhood: u.neighborhood ?? "",
    });
    if (profileUrl) {
      setPreview(profileUrl);
      setUploadedFile({ collection_name: "profile", url: profileUrl });
    } else {
      setPreview(null);
      setUploadedFile(null);
    }
  }, [isOpen, user, reset]);
  const findRiyadh = (list: any[]) => {
    return (list || []).find((s) => {
      const n = String(s?.name || "").toLowerCase();
      return n.includes("الرياض") || n.includes("riyadh");
    });
  };

  useEffect(() => {
    const loadCountries = async () => {
      try {
        setCountriesLoading(true);
        const data = await fetchCountries();
        setCountries(data);
      } catch (error) {
        console.error("Failed to load countries", error);
      } finally {
        setCountriesLoading(false);
      }
    };

    loadCountries();
  }, []);

  useEffect(() => {
    const loadStates = async () => {
      if (!countryId) {
        setStates([]);
        setValue("state_id", "");
        return;
      }

      try {
        setStatesLoading(true);
        const res = await fetch(
          `${API_BASE_URL}/user/config/reference-data?states=1&country_id=${countryId}`,
        );
        const json = await res.json();
        const list = (json?.data?.states as any[]) || json?.data || [];
        const normalized = (Array.isArray(list) ? list : []).map((s: any) => ({
          id: Number(s.id),
          name: String(s.name),
        }));

        const riyadh = findRiyadh(normalized);
        const nextStates =
          String(countryId) === "1" && riyadh
            ? [
                riyadh,
                ...normalized.filter(
                  (s: any) => String(s?.id) !== String(riyadh.id),
                ),
              ]
            : normalized;

        setStates(nextStates);

        if (String(countryId) === "1" && !stateId && riyadh?.id) {
          setValue("state_id", String(riyadh.id));
        }
      } catch (error) {
        console.error("Failed to load states", error);
        setStates([]);
      } finally {
        setStatesLoading(false);
      }
    };

    loadStates();
  }, [countryId, setValue, stateId]);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setPreview(URL.createObjectURL(file));

    try {
      const formData = new FormData();
      formData.append("model_name", "User");
      formData.append("media[profile]", file);

      const res = await uploadImage(formData);
      if (res?.success && Array.isArray(res.data) && res.data.length > 0) {
        const fileData = res.data[0];
        setUploadedFile({
          collection_name: fileData.collection_name,
          url: fileData.url,
        });
        toast.success(t("profile_image_uploaded"));
      } else {
        toast.error(t("profile_image_upload_failed"));
      }
    } catch {
      toast.error(t("profile_image_upload_failed"));
    }
  };

  const onSubmit = async (data: any) => {
    try {
      const firstName = (data.first_name || "").trim();
      const lastName = (data.last_name || "").trim();
      const stableName = (data.stable_name || "").trim();
      const email = (data.email || "").trim();
      const genderVal = (data.gender || "").trim();
      const neighborhoodVal = (data.neighborhood || "").trim();

      if (!firstName) {
        toast.error(t("fill_all_fields"));
        return;
      }
      if (!lastName) {
        toast.error(t("fill_all_fields"));
        return;
      }
      if (!email) {
        toast.error(t("fill_all_fields"));
        return;
      }
      if (!genderVal) {
        toast.error(t("fill_all_fields"));
        return;
      }
      if (!data.country_id) {
        toast.error(t("fill_all_fields"));
        return;
      }
      if (!data.state_id) {
        toast.error(t("state_required") || t("fill_all_fields"));
        return;
      }
      if (!neighborhoodVal) {
        toast.error(t("fill_all_fields"));
        return;
      }

      setLoading(true);
      const payload: Record<string, unknown> = {
        stable_name: stableName || undefined,
        first_name: firstName || undefined,
        last_name: lastName || undefined,
        email: email || undefined,
        gender: genderVal || "male",
        country_id: data.country_id ? Number(data.country_id) : undefined,
        state_id: Number(data.state_id),
        neighborhood: neighborhoodVal || undefined,
      };
      if (uploadedFile?.url) {
        payload.media_files = [
          {
            collection_name: uploadedFile.collection_name || "profile",
            url: uploadedFile.url,
          },
        ];
      }
      Object.keys(payload).forEach((k) => {
        if (
          payload[k] === undefined ||
          payload[k] === null ||
          payload[k] === ""
        ) {
          delete payload[k];
        }
      });

      const res = await completeProfile(payload, token);
      if (res?.success) {
        reset();
        setUploadedFile(null);
        setPreview(null);
        onClose();
      } else {
        toast.error(res?.message || t("profile_save_error"));
      }
    } catch {
      toast.error(t("profile_save_error"));
    } finally {
      setLoading(false);
    }
  };

  return (
    <BaseModal
      isOpen={isOpen}
      onClose={onClose}
      placement="center"
      title={t("complete_profile_title")}
      contentClassName="w-full max-w-[520px] rounded-2xl text-primary"
      isDismissable={false}
    >
      <form
        dir={dir}
        onSubmit={handleSubmit(onSubmit)}
        className="space-y-6 text-start"
      >
        <div className="flex flex-col items-center space-y-3">
          {preview ? (
            <img
              src={preview}
              alt=""
              className="w-24 h-24 rounded-full object-cover border border-gray-300"
            />
          ) : (
            <div className="w-24 h-24 rounded-full border border-dashed border-gray-400 flex items-center justify-center text-gray-400 text-sm">
              {t("no_image")}
            </div>
          )}

          <span className="text-sm font-medium text-slate-800">
            {t("profile_image")}
          </span>

          <label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-xs font-medium text-slate-800 border border-slate-300 transition">
            {t("choose_image")}
            <input
              type="file"
              accept="image/*"
              onChange={handleFileChange}
              className="hidden"
            />
          </label>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <Input
            {...register("first_name")}
            label={t("first_name")}
            placeholder={t("first_name_placeholder")}
            size="lg"
            isRequired
          />
          <Input
            {...register("last_name")}
            label={t("last_name")}
            placeholder={t("last_name_placeholder")}
            size="lg"
            isRequired
          />
          <Input
            {...register("stable_name")}
            label={t("stable_name")}
            size="lg"
          />
          <Input
            {...register("email")}
            type="email"
            label={t("email")}
            size="lg"
            isRequired
          />
          <Select
            label={t("gender")}
            selectedKeys={gender ? [String(gender)] : []}
            onSelectionChange={(keys) => {
              const k = Array.from(keys)[0];
              setValue("gender", k != null ? String(k) : "male");
            }}
            size="lg"
            isRequired
          >
            <SelectItem key="male">{t("male")}</SelectItem>
            <SelectItem key="female">{t("female")}</SelectItem>
          </Select>
          <Input
            {...register("neighborhood")}
            label={t("neighborhood")}
            size="lg"
            isRequired
          />
          <div className="sm:col-span-2">
            <label className="text-sm font-semibold text-gray-700 mb-1 block">
              {t("country")}
            </label>
            <Autocomplete
              selectedKey={countryId ? String(countryId) : undefined}
              onSelectionChange={(key) => {
                if (key) {
                  setValue("country_id", String(key));
                  setValue("state_id", "");
                }
              }}
              placeholder={t("country_placeholder") || t("country")}
              variant="flat"
              className="max-w-full"
              isDisabled={!countries.length}
              isLoading={countriesLoading}
              defaultItems={countries}
            >
              {(country: any) => (
                <AutocompleteItem key={String(country.id)}>
                  {country.name}
                </AutocompleteItem>
              )}
            </Autocomplete>
          </div>

          <div className="sm:col-span-2">
            <label className="text-sm font-semibold text-gray-700 mb-1 block">
              {t("state")}
            </label>
            <Autocomplete
              selectedKey={stateId ? String(stateId) : undefined}
              onSelectionChange={(key) => {
                if (key) setValue("state_id", String(key));
              }}
              placeholder={
                !countryId
                  ? t("select_country_first")
                  : statesLoading
                    ? t("loading") + "..."
                    : t("state_placeholder") || t("state")
              }
              variant="flat"
              className="max-w-full"
              isDisabled={!countryId || statesLoading}
              isLoading={statesLoading}
              defaultItems={states}
            >
              {(state: any) => (
                <AutocompleteItem key={String(state.id)}>
                  {state.name}
                </AutocompleteItem>
              )}
            </Autocomplete>
          </div>
        </div>

        <DynamicButton
          onClick={handleSubmit(onSubmit)}
          fullWidth
          isDisabled={loading}
          className={`py-2 rounded-lg px-4 flex items-center justify-center ${
            loading ? "bg-primary/70 cursor-not-allowed" : "bg-primary"
          } text-white transition`}
        >
          {loading ? (
            <>
              <Spinner color="white" size="sm" />
              <span className="ml-2">{t("saving")}...</span>
            </>
          ) : (
            t("saving") || t("save")
          )}
        </DynamicButton>
      </form>
    </BaseModal>
  );
}
